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/netty
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/netty/filter/FilterRunner.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.zuul.message.ZuulMessage; import io.netty.handler.codec.http.HttpContent; /** * Created by saroskar on 5/18/17. */ public interface FilterRunner<I extends ZuulMessage, O extends ZuulMessage> { void filter(I zuulMesg); void filter(I zuulMesg, HttpContent chunk); }
6,400
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/BaseZuulFilterRunner.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.config.CachedDynamicIntProperty; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.spectator.impl.Preconditions; import com.netflix.zuul.ExecutionStatus; import com.netflix.zuul.FilterUsageNotifier; import com.netflix.zuul.context.CommonContextKeys; import com.netflix.zuul.context.Debug; import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.exception.ZuulException; import com.netflix.zuul.filters.FilterError; import com.netflix.zuul.filters.FilterSyncType; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.filters.SyncZuulFilter; import com.netflix.zuul.filters.ZuulFilter; import com.netflix.zuul.message.ZuulMessage; 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.SpectatorUtils; import com.netflix.zuul.netty.server.MethodBinding; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.HttpContent; import io.perfmark.Link; import io.perfmark.PerfMark; import io.perfmark.TaskCloseable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observer; import rx.functions.Action0; import rx.functions.Action1; import rx.schedulers.Schedulers; import javax.annotation.concurrent.ThreadSafe; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; /** * Subclasses of this class are supposed to be thread safe and hence should not have any non final member variables * Created by saroskar on 5/18/17. */ @ThreadSafe public abstract class BaseZuulFilterRunner<I extends ZuulMessage, O extends ZuulMessage> implements FilterRunner<I, O> { private final FilterUsageNotifier usageNotifier; private final FilterRunner<O, ? extends ZuulMessage> nextStage; private final String RUNNING_FILTER_IDX_SESSION_CTX_KEY; private final String AWAITING_BODY_FLAG_SESSION_CTX_KEY; private static final Logger logger = LoggerFactory.getLogger(BaseZuulFilterRunner.class); private static final CachedDynamicIntProperty FILTER_EXCESSIVE_EXEC_TIME = new CachedDynamicIntProperty("zuul.filters.excessive.execTime", 500); private final Registry registry; private final Id filterExcessiveTimerId; protected BaseZuulFilterRunner( FilterType filterType, FilterUsageNotifier usageNotifier, FilterRunner<O, ?> nextStage, Registry registry) { this.usageNotifier = Preconditions.checkNotNull(usageNotifier, "filter usage notifier"); this.nextStage = nextStage; this.RUNNING_FILTER_IDX_SESSION_CTX_KEY = filterType + "RunningFilterIndex"; this.AWAITING_BODY_FLAG_SESSION_CTX_KEY = filterType + "IsAwaitingBody"; this.registry = registry; this.filterExcessiveTimerId = registry.createId("zuul.request.timing.filterExcessive"); } public static final ChannelHandlerContext getChannelHandlerContext(final ZuulMessage mesg) { return (ChannelHandlerContext) com.google.common.base.Preconditions.checkNotNull( mesg.getContext().get(CommonContextKeys.NETTY_SERVER_CHANNEL_HANDLER_CONTEXT), "channel handler context"); } public FilterRunner<O, ? extends ZuulMessage> getNextStage() { return nextStage; } protected final AtomicInteger initRunningFilterIndex(I zuulMesg) { final AtomicInteger idx = new AtomicInteger(0); zuulMesg.getContext().put(RUNNING_FILTER_IDX_SESSION_CTX_KEY, idx); return idx; } protected final AtomicInteger getRunningFilterIndex(I zuulMesg) { final SessionContext ctx = zuulMesg.getContext(); return (AtomicInteger) Preconditions.checkNotNull(ctx.get(RUNNING_FILTER_IDX_SESSION_CTX_KEY), "runningFilterIndex"); } protected final boolean isFilterAwaitingBody(SessionContext context) { return context.containsKey(AWAITING_BODY_FLAG_SESSION_CTX_KEY); } protected final void setFilterAwaitingBody(I zuulMesg, boolean flag) { if (flag) { zuulMesg.getContext().put(AWAITING_BODY_FLAG_SESSION_CTX_KEY, Boolean.TRUE); } else { zuulMesg.getContext().remove(AWAITING_BODY_FLAG_SESSION_CTX_KEY); } } protected final void invokeNextStage(final O zuulMesg, final HttpContent chunk) { if (nextStage != null) { try (TaskCloseable ignored = PerfMark.traceTask(this, s -> s.getClass().getSimpleName() + ".invokeNextStageChunk")) { addPerfMarkTags(zuulMesg); nextStage.filter(zuulMesg, chunk); } } else { // Next stage is Netty channel handler try (TaskCloseable ignored = PerfMark.traceTask(this, s -> s.getClass().getSimpleName() + ".fireChannelReadChunk")) { addPerfMarkTags(zuulMesg); ChannelHandlerContext channelHandlerContext = getChannelHandlerContext(zuulMesg); if (!channelHandlerContext.channel().isActive()) { zuulMesg.getContext().cancel(); zuulMesg.disposeBufferedBody(); SpectatorUtils.newCounter( "zuul.filterChain.chunk.hanging", zuulMesg.getClass().getSimpleName()) .increment(); } else { channelHandlerContext.fireChannelRead(chunk); } } } } protected final void invokeNextStage(final O zuulMesg) { if (nextStage != null) { try (TaskCloseable ignored = PerfMark.traceTask(this, s -> s.getClass().getSimpleName() + ".invokeNextStage")) { addPerfMarkTags(zuulMesg); nextStage.filter(zuulMesg); } } else { // Next stage is Netty channel handler try (TaskCloseable ignored = PerfMark.traceTask(this, s -> s.getClass().getSimpleName() + ".fireChannelRead")) { addPerfMarkTags(zuulMesg); ChannelHandlerContext channelHandlerContext = getChannelHandlerContext(zuulMesg); if (!channelHandlerContext.channel().isActive()) { zuulMesg.getContext().cancel(); zuulMesg.disposeBufferedBody(); SpectatorUtils.newCounter( "zuul.filterChain.message.hanging", zuulMesg.getClass().getSimpleName()) .increment(); } else { channelHandlerContext.fireChannelRead(zuulMesg); } } } } protected final void addPerfMarkTags(ZuulMessage inMesg) { HttpRequestInfo req = null; if (inMesg instanceof HttpRequestInfo) { req = (HttpRequestInfo) inMesg; } if (inMesg instanceof HttpResponseMessage) { HttpResponseMessage msg = (HttpResponseMessage) inMesg; req = msg.getOutboundRequest(); PerfMark.attachTag("statuscode", msg.getStatus()); } if (req != null) { PerfMark.attachTag("path", req, HttpRequestInfo::getPath); PerfMark.attachTag("originalhost", req, HttpRequestInfo::getOriginalHost); } PerfMark.attachTag("uuid", inMesg, m -> m.getContext().getUUID()); } protected final O filter(final ZuulFilter<I, O> filter, final I inMesg) { final long startTime = System.nanoTime(); final ZuulMessage snapshot = inMesg.getContext().debugRouting() ? inMesg.clone() : null; FilterChainResumer resumer = null; try (TaskCloseable ignored = PerfMark.traceTask(filter, f -> f.filterName() + ".filter")) { addPerfMarkTags(inMesg); ExecutionStatus filterRunStatus = null; if (filter.filterType() == FilterType.INBOUND && inMesg.getContext().shouldSendErrorResponse()) { // Pass request down the pipeline, all the way to error endpoint if error response needs to be generated filterRunStatus = ExecutionStatus.SKIPPED; } ; try (TaskCloseable ignored2 = PerfMark.traceTask(filter, f -> f.filterName() + ".shouldSkipFilter")) { if (shouldSkipFilter(inMesg, filter)) { filterRunStatus = ExecutionStatus.SKIPPED; } } if (filter.isDisabled()) { filterRunStatus = ExecutionStatus.DISABLED; } if (filterRunStatus != null) { recordFilterCompletion(filterRunStatus, filter, startTime, inMesg, snapshot); return filter.getDefaultOutput(inMesg); } if (!isMessageBodyReadyForFilter(filter, inMesg)) { setFilterAwaitingBody(inMesg, true); logger.debug( "Filter {} waiting for body, UUID {}", filter.filterName(), inMesg.getContext().getUUID()); return null; // wait for whole body to be buffered } setFilterAwaitingBody(inMesg, false); if (snapshot != null) { Debug.addRoutingDebug( inMesg.getContext(), "Filter " + filter.filterType().toString() + " " + filter.filterOrder() + " " + filter.filterName()); } // run body contents accumulated so far through this filter inMesg.runBufferedBodyContentThroughFilter(filter); if (filter.getSyncType() == FilterSyncType.SYNC) { final SyncZuulFilter<I, O> syncFilter = (SyncZuulFilter) filter; final O outMesg; try (TaskCloseable ignored2 = PerfMark.traceTask(filter, f -> f.filterName() + ".apply")) { addPerfMarkTags(inMesg); outMesg = syncFilter.apply(inMesg); } recordFilterCompletion(ExecutionStatus.SUCCESS, filter, startTime, inMesg, snapshot); return (outMesg != null) ? outMesg : filter.getDefaultOutput(inMesg); } // async filter try (TaskCloseable ignored2 = PerfMark.traceTask(filter, f -> f.filterName() + ".applyAsync")) { final Link nettyToSchedulerLink = PerfMark.linkOut(); filter.incrementConcurrency(); resumer = new FilterChainResumer(inMesg, filter, snapshot, startTime); filter.applyAsync(inMesg) .doOnSubscribe(() -> { try (TaskCloseable ignored3 = PerfMark.traceTask(filter, f -> f.filterName() + ".onSubscribeAsync")) { PerfMark.linkIn(nettyToSchedulerLink); } }) .doOnNext(resumer.onNextStarted(nettyToSchedulerLink)) .doOnError(resumer.onErrorStarted(nettyToSchedulerLink)) .doOnCompleted(resumer.onCompletedStarted(nettyToSchedulerLink)) .observeOn( Schedulers.from(getChannelHandlerContext(inMesg).executor())) .doOnUnsubscribe(resumer::decrementConcurrency) .subscribe(resumer); } return null; // wait for the async filter to finish } catch (Throwable t) { if (resumer != null) { resumer.decrementConcurrency(); } final O outMesg = handleFilterException(inMesg, filter, t); outMesg.finishBufferedBodyIfIncomplete(); recordFilterCompletion(ExecutionStatus.FAILED, filter, startTime, inMesg, snapshot); return outMesg; } } /* This is typically set by a filter when wanting to reject a request and also reduce load on the server by not processing any more filterChain */ protected final boolean shouldSkipFilter(final I inMesg, final ZuulFilter<I, O> filter) { if (filter.filterType() == FilterType.ENDPOINT) { // Endpoints may not be skipped return false; } final SessionContext zuulCtx = inMesg.getContext(); if ((zuulCtx.shouldStopFilterProcessing()) && (!filter.overrideStopFilterProcessing())) { return true; } if (zuulCtx.isCancelled()) { return true; } if (!filter.shouldFilter(inMesg)) { return true; } return false; } private boolean isMessageBodyReadyForFilter(final ZuulFilter filter, final I inMesg) { return ((!filter.needsBodyBuffered(inMesg)) || (inMesg.hasCompleteBody())); } protected O handleFilterException(final I inMesg, final ZuulFilter<I, O> filter, final Throwable ex) { inMesg.getContext().setError(ex); if (filter.filterType() == FilterType.ENDPOINT) { inMesg.getContext().setShouldSendErrorResponse(true); } recordFilterError(inMesg, filter, ex); return filter.getDefaultOutput(inMesg); } protected void recordFilterError(final I inMesg, final ZuulFilter<I, O> filter, final Throwable t) { // Add a log statement for this exception. final String errorMsg = "Filter Exception: filter=" + filter.filterName() + ", request-info=" + inMesg.getInfoForLogging() + ", msg=" + String.valueOf(t.getMessage()); if (t instanceof ZuulException && !((ZuulException) t).shouldLogAsError()) { logger.warn(errorMsg); } else { logger.error(errorMsg, t); } // Store this filter error for possible future use. But we still continue with next filter in the chain. final SessionContext zuulCtx = inMesg.getContext(); zuulCtx.getFilterErrors() .add(new FilterError(filter.filterName(), filter.filterType().toString(), t)); if (zuulCtx.debugRouting()) { Debug.addRoutingDebug( zuulCtx, "Running Filter failed " + filter.filterName() + " type:" + filter.filterType() + " order:" + filter.filterOrder() + " " + t.getMessage()); } } protected void recordFilterCompletion( final ExecutionStatus status, final ZuulFilter<I, O> filter, long startTime, final ZuulMessage zuulMesg, final ZuulMessage startSnapshot) { final SessionContext zuulCtx = zuulMesg.getContext(); final long execTimeNs = System.nanoTime() - startTime; final long execTimeMs = execTimeNs / 1_000_000L; if (execTimeMs >= FILTER_EXCESSIVE_EXEC_TIME.get()) { registry.timer(filterExcessiveTimerId .withTag("id", filter.filterName()) .withTag("status", status.name())) .record(execTimeMs, TimeUnit.MILLISECONDS); } // Record the execution summary in context. switch (status) { case FAILED: if (logger.isDebugEnabled()) { zuulCtx.addFilterExecutionSummary(filter.filterName(), ExecutionStatus.FAILED.name(), execTimeMs); } break; case SUCCESS: if (logger.isDebugEnabled()) { zuulCtx.addFilterExecutionSummary(filter.filterName(), ExecutionStatus.SUCCESS.name(), execTimeMs); } if (startSnapshot != null) { // debugRouting == true Debug.addRoutingDebug( zuulCtx, "Filter {" + filter.filterName() + " TYPE:" + filter.filterType().toString() + " ORDER:" + filter.filterOrder() + "} Execution time = " + execTimeMs + "ms"); Debug.compareContextState(filter.filterName(), zuulCtx, startSnapshot.getContext()); } break; default: break; } logger.debug( "Filter {} completed with status {}, UUID {}", filter.filterName(), status.name(), zuulMesg.getContext().getUUID()); // Notify configured listener. usageNotifier.notify(filter, status); } protected void handleException(final ZuulMessage zuulMesg, final String filterName, final Exception ex) { HttpRequestInfo zuulReq = null; if (zuulMesg instanceof HttpRequestMessage) { zuulReq = (HttpRequestMessage) zuulMesg; } else if (zuulMesg instanceof HttpResponseMessage) { zuulReq = ((HttpResponseMessage) zuulMesg).getInboundRequest(); } final String path = (zuulReq != null) ? zuulReq.getPathAndQuery() : "-"; final String method = (zuulReq != null) ? zuulReq.getMethod() : "-"; final String errMesg = "Error with filter: " + filterName + ", path: " + path + ", method: " + method; logger.error(errMesg, ex); getChannelHandlerContext(zuulMesg).fireExceptionCaught(ex); } protected abstract void resume(O zuulMesg); protected MethodBinding<?> methodBinding(ZuulMessage zuulMesg) { return MethodBinding.NO_OP_BINDING; } protected void resumeInBindingContext(final O zuulMesg, final String filterName) { try { methodBinding(zuulMesg).bind(() -> resume(zuulMesg)); } catch (Exception ex) { handleException(zuulMesg, filterName, ex); } } private final class FilterChainResumer implements Observer<O> { private final I inMesg; private final ZuulFilter<I, O> filter; private final long startTime; private ZuulMessage snapshot; private AtomicBoolean concurrencyDecremented; private final AtomicReference<Link> onNextLinkOut = new AtomicReference<>(); private final AtomicReference<Link> onErrorLinkOut = new AtomicReference<>(); private final AtomicReference<Link> onCompletedLinkOut = new AtomicReference<>(); public FilterChainResumer(I inMesg, ZuulFilter<I, O> filter, ZuulMessage snapshot, long startTime) { this.inMesg = Preconditions.checkNotNull(inMesg, "input message"); this.filter = Preconditions.checkNotNull(filter, "filter"); this.snapshot = snapshot; this.startTime = startTime; this.concurrencyDecremented = new AtomicBoolean(false); } void decrementConcurrency() { if (concurrencyDecremented.compareAndSet(false, true)) { filter.decrementConcurrency(); } } @Override public void onNext(O outMesg) { try (TaskCloseable ignored = PerfMark.traceTask(filter, f -> f.filterName() + ".onNextAsync")) { PerfMark.linkIn(onNextLinkOut.get()); addPerfMarkTags(inMesg); recordFilterCompletion(ExecutionStatus.SUCCESS, filter, startTime, inMesg, snapshot); if (outMesg == null) { outMesg = filter.getDefaultOutput(inMesg); } resumeInBindingContext(outMesg, filter.filterName()); } catch (Exception e) { decrementConcurrency(); handleException(inMesg, filter.filterName(), e); } } @Override public void onError(Throwable ex) { try (TaskCloseable ignored = PerfMark.traceTask(filter, f -> f.filterName() + ".onErrorAsync")) { PerfMark.linkIn(onErrorLinkOut.get()); decrementConcurrency(); recordFilterCompletion(ExecutionStatus.FAILED, filter, startTime, inMesg, snapshot); final O outMesg = handleFilterException(inMesg, filter, ex); resumeInBindingContext(outMesg, filter.filterName()); } catch (Exception e) { handleException(inMesg, filter.filterName(), e); } } @Override public void onCompleted() { try (TaskCloseable ignored = PerfMark.traceTask(filter, f -> f.filterName() + ".onCompletedAsync")) { PerfMark.linkIn(onCompletedLinkOut.get()); decrementConcurrency(); } } private Action1<O> onNextStarted(Link onNextLinkIn) { return o -> { try (TaskCloseable ignored = PerfMark.traceTask(filter, f -> f.filterName() + ".onNext")) { PerfMark.linkIn(onNextLinkIn); onNextLinkOut.compareAndSet(null, PerfMark.linkOut()); } }; } private Action1<Throwable> onErrorStarted(Link onErrorLinkIn) { return t -> { try (TaskCloseable ignored = PerfMark.traceTask(filter, f -> f.filterName() + ".onError")) { PerfMark.linkIn(onErrorLinkIn); onErrorLinkOut.compareAndSet(null, PerfMark.linkOut()); } }; } private Action0 onCompletedStarted(Link onCompletedLinkIn) { return () -> { try (TaskCloseable ignored = PerfMark.traceTask(filter, f -> f.filterName() + ".onCompleted")) { PerfMark.linkIn(onCompletedLinkIn); onCompletedLinkOut.compareAndSet(null, PerfMark.linkOut()); } }; } } }
6,401
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/ZuulEndPointRunner.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.Strings; import com.netflix.config.DynamicStringProperty; import com.netflix.netty.common.ByteBufUtil; import com.netflix.spectator.api.Registry; import com.netflix.spectator.impl.Preconditions; import com.netflix.zuul.FilterLoader; import com.netflix.zuul.FilterUsageNotifier; import com.netflix.zuul.context.CommonContextKeys; import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.filters.Endpoint; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.filters.SyncZuulFilterAdapter; import com.netflix.zuul.filters.ZuulFilter; import com.netflix.zuul.filters.endpoint.MissingEndpointHandlingFilter; import com.netflix.zuul.filters.endpoint.ProxyEndpoint; import com.netflix.zuul.message.ZuulMessage; import com.netflix.zuul.message.http.HttpRequestMessage; import com.netflix.zuul.message.http.HttpResponseMessage; import com.netflix.zuul.message.http.HttpResponseMessageImpl; import com.netflix.zuul.netty.server.MethodBinding; import io.netty.handler.codec.http.HttpContent; import io.netty.util.ReferenceCountUtil; import io.perfmark.PerfMark; import io.perfmark.TaskCloseable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; /** * This class is supposed to be thread safe and hence should not have any non final member variables * Created by saroskar on 5/18/17. */ @ThreadSafe public class ZuulEndPointRunner extends BaseZuulFilterRunner<HttpRequestMessage, HttpResponseMessage> { private final FilterLoader filterLoader; private static Logger logger = LoggerFactory.getLogger(ZuulEndPointRunner.class); public static final String PROXY_ENDPOINT_FILTER_NAME = ProxyEndpoint.class.getCanonicalName(); public static final DynamicStringProperty DEFAULT_ERROR_ENDPOINT = new DynamicStringProperty("zuul.filters.error.default", "endpoint.ErrorResponse"); public ZuulEndPointRunner( FilterUsageNotifier usageNotifier, FilterLoader filterLoader, FilterRunner<HttpResponseMessage, HttpResponseMessage> respFilters, Registry registry) { super(FilterType.ENDPOINT, usageNotifier, respFilters, registry); this.filterLoader = filterLoader; } @Nullable public static ZuulFilter<HttpRequestMessage, HttpResponseMessage> getEndpoint( @Nullable final HttpRequestMessage zuulReq) { if (zuulReq != null) { return zuulReq.getContext().get(CommonContextKeys.ZUUL_ENDPOINT); } return null; } public static void setEndpoint( HttpRequestMessage zuulReq, ZuulFilter<HttpRequestMessage, HttpResponseMessage> endpoint) { zuulReq.getContext().put(CommonContextKeys.ZUUL_ENDPOINT, endpoint); } @Override public void filter(final HttpRequestMessage zuulReq) { if (zuulReq.getContext().isCancelled()) { PerfMark.event(getClass().getName(), "filterCancelled"); zuulReq.disposeBufferedBody(); logger.debug("Request was cancelled, UUID {}", zuulReq.getContext().getUUID()); return; } final String endpointName = getEndPointName(zuulReq.getContext()); try (TaskCloseable ignored = PerfMark.traceTask(this, s -> s.getClass().getSimpleName() + ".filter")) { Preconditions.checkNotNull(zuulReq, "input message"); addPerfMarkTags(zuulReq); final ZuulFilter<HttpRequestMessage, HttpResponseMessage> endpoint = getEndpoint(endpointName, zuulReq); logger.debug( "Got endpoint {}, UUID {}", endpoint.filterName(), zuulReq.getContext().getUUID()); setEndpoint(zuulReq, endpoint); final HttpResponseMessage zuulResp = filter(endpoint, zuulReq); if ((zuulResp != null) && (!(endpoint instanceof ProxyEndpoint))) { // EdgeProxyEndpoint calls invokeNextStage internally logger.debug( "Endpoint calling invokeNextStage, UUID {}", zuulReq.getContext().getUUID()); invokeNextStage(zuulResp); } } catch (Exception ex) { handleException(zuulReq, endpointName, ex); } } @Override protected void resume(final HttpResponseMessage zuulMesg) { try (TaskCloseable ignored = PerfMark.traceTask(this, s -> s.getClass().getSimpleName() + ".resume")) { if (zuulMesg.getContext().isCancelled()) { return; } invokeNextStage(zuulMesg); } } @Override public void filter(final HttpRequestMessage zuulReq, final HttpContent chunk) { if (zuulReq.getContext().isCancelled()) { chunk.release(); return; } String endpointName = "-"; try (TaskCloseable ignored = PerfMark.traceTask(this, s -> s.getClass().getSimpleName() + ".filterChunk")) { addPerfMarkTags(zuulReq); ZuulFilter<HttpRequestMessage, HttpResponseMessage> endpoint = Preconditions.checkNotNull(getEndpoint(zuulReq), "endpoint"); endpointName = endpoint.filterName(); ByteBufUtil.touch(chunk, "Endpoint processing chunk, ZuulMessage: ", zuulReq); final HttpContent newChunk = endpoint.processContentChunk(zuulReq, chunk); if (newChunk != null) { ByteBufUtil.touch(newChunk, "Endpoint buffering newChunk, ZuulMessage: ", zuulReq); // Endpoints do not directly forward content chunks to next stage in the filter chain. zuulReq.bufferBodyContents(newChunk); // deallocate original chunk if necessary if (newChunk != chunk) { chunk.release(); } if (isFilterAwaitingBody(zuulReq.getContext()) && zuulReq.hasCompleteBody() && !(endpoint instanceof ProxyEndpoint)) { // whole body has arrived, resume filter chain ByteBufUtil.touch(newChunk, "Endpoint body complete, resume chain, ZuulMessage: ", zuulReq); invokeNextStage(filter(endpoint, zuulReq)); } } } catch (Exception ex) { ReferenceCountUtil.safeRelease(chunk); handleException(zuulReq, endpointName, ex); } } protected String getEndPointName(final SessionContext zuulCtx) { if (zuulCtx.shouldSendErrorResponse()) { zuulCtx.setShouldSendErrorResponse(false); zuulCtx.setErrorResponseSent(true); final String errEndPointName = zuulCtx.getErrorEndpoint(); return (Strings.isNullOrEmpty(errEndPointName)) ? DEFAULT_ERROR_ENDPOINT.get() : errEndPointName; } else { return zuulCtx.getEndpoint(); } } protected ZuulFilter<HttpRequestMessage, HttpResponseMessage> getEndpoint( final String endpointName, final HttpRequestMessage zuulRequest) { final SessionContext zuulCtx = zuulRequest.getContext(); if (zuulCtx.getStaticResponse() != null) { return STATIC_RESPONSE_ENDPOINT; } if (endpointName == null) { return new MissingEndpointHandlingFilter("NO_ENDPOINT_NAME"); } if (PROXY_ENDPOINT_FILTER_NAME.equals(endpointName)) { return newProxyEndpoint(zuulRequest); } final Endpoint<HttpRequestMessage, HttpResponseMessage> filter = getEndpointFilter(endpointName); if (filter == null) { return new MissingEndpointHandlingFilter(endpointName); } return filter; } /** * Override to inject your own proxy endpoint implementation * * @param zuulRequest - the request message * @return the proxy endpoint */ protected ZuulFilter<HttpRequestMessage, HttpResponseMessage> newProxyEndpoint(HttpRequestMessage zuulRequest) { return new ProxyEndpoint( zuulRequest, getChannelHandlerContext(zuulRequest), getNextStage(), MethodBinding.NO_OP_BINDING); } protected <I extends ZuulMessage, O extends ZuulMessage> Endpoint<I, O> getEndpointFilter(String endpointName) { return (Endpoint<I, O>) filterLoader.getFilterByNameAndType(endpointName, FilterType.ENDPOINT); } protected static final ZuulFilter<HttpRequestMessage, HttpResponseMessage> STATIC_RESPONSE_ENDPOINT = new SyncZuulFilterAdapter<HttpRequestMessage, HttpResponseMessage>() { @Override public HttpResponseMessage apply(HttpRequestMessage request) { final HttpResponseMessage resp = request.getContext().getStaticResponse(); resp.finishBufferedBodyIfIncomplete(); return resp; } @Override public String filterName() { return "StaticResponseEndpoint"; } @Override public HttpResponseMessage getDefaultOutput(HttpRequestMessage input) { return HttpResponseMessageImpl.defaultErrorResponse(input); } }; }
6,402
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/passport/CurrentPassport.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.passport; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Ticker; import com.google.common.collect.Sets; import com.netflix.config.CachedDynamicBooleanProperty; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Spectator; import com.netflix.zuul.context.CommonContextKeys; import com.netflix.zuul.context.SessionContext; import io.netty.channel.Channel; import io.netty.util.AttributeKey; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.ConcurrentModificationException; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.locks.ReentrantLock; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CurrentPassport { private static final Logger logger = LoggerFactory.getLogger(CurrentPassport.class); private static final CachedDynamicBooleanProperty COUNT_STATES = new CachedDynamicBooleanProperty("zuul.passport.count.enabled", false); public static final AttributeKey<CurrentPassport> CHANNEL_ATTR = AttributeKey.newInstance("_current_passport"); private static final Ticker SYSTEM_TICKER = Ticker.systemTicker(); private static final Set<PassportState> CONTENT_STATES = Sets.newHashSet( PassportState.IN_REQ_CONTENT_RECEIVED, PassportState.IN_RESP_CONTENT_RECEIVED, PassportState.OUT_REQ_CONTENT_SENDING, PassportState.OUT_REQ_CONTENT_SENT, PassportState.OUT_RESP_CONTENT_SENDING, PassportState.OUT_RESP_CONTENT_SENT); private static final CachedDynamicBooleanProperty CONTENT_STATE_ENABLED = new CachedDynamicBooleanProperty("zuul.passport.state.content.enabled", false); private final Ticker ticker; private final LinkedList<PassportItem> history; private final HashSet<PassportState> statesAdded; private final long creationTimeSinceEpochMs; private final IntrospectiveReentrantLock historyLock = new IntrospectiveReentrantLock(); private final Unlocker unlocker = new Unlocker(); private final class Unlocker implements AutoCloseable { @Override public void close() { historyLock.unlock(); } } private static final class IntrospectiveReentrantLock extends ReentrantLock { @Override protected Thread getOwner() { return super.getOwner(); } } private Unlocker lock() { boolean locked = false; if ((historyLock.isLocked() && !historyLock.isHeldByCurrentThread()) || !(locked = historyLock.tryLock())) { Thread owner = historyLock.getOwner(); String ownerStack = String.valueOf(owner != null ? Arrays.asList(owner.getStackTrace()) : historyLock); logger.warn( "CurrentPassport already locked!, other={}, self={}", ownerStack, Thread.currentThread(), new ConcurrentModificationException()); } if (!locked) { historyLock.lock(); } return unlocker; } CurrentPassport() { this(SYSTEM_TICKER); } @VisibleForTesting public CurrentPassport(Ticker ticker) { this.ticker = ticker; this.history = new LinkedList<>(); this.statesAdded = new HashSet<>(); this.creationTimeSinceEpochMs = System.currentTimeMillis(); } public static CurrentPassport create() { if (COUNT_STATES.get()) { return new CountingCurrentPassport(); } return new CurrentPassport(); } public static CurrentPassport fromSessionContext(SessionContext ctx) { return ctx.get(CommonContextKeys.PASSPORT); } public static CurrentPassport createForChannel(Channel ch) { CurrentPassport passport = create(); passport.setOnChannel(ch); return passport; } public static CurrentPassport fromChannel(Channel ch) { CurrentPassport passport = fromChannelOrNull(ch); if (passport == null) { passport = create(); ch.attr(CHANNEL_ATTR).set(passport); } return passport; } public static CurrentPassport fromChannelOrNull(Channel ch) { return ch.attr(CHANNEL_ATTR).get(); } public void setOnChannel(Channel ch) { ch.attr(CHANNEL_ATTR).set(this); } public static void clearFromChannel(Channel ch) { ch.attr(CHANNEL_ATTR).set(null); } public PassportState getState() { try (Unlocker ignored = lock()) { PassportItem passportItem = history.peekLast(); return passportItem != null ? passportItem.getState() : null; } } @VisibleForTesting public LinkedList<PassportItem> getHistory() { try (Unlocker ignored = lock()) { // best effort, but doesn't actually protect anything return history; } } public void add(PassportState state) { if (!CONTENT_STATE_ENABLED.get()) { if (CONTENT_STATES.contains(state)) { // Discard. return; } } try (Unlocker ignored = lock()) { history.addLast(new PassportItem(state, now())); } statesAdded.add(state); } public void addIfNotAlready(PassportState state) { if (!statesAdded.contains(state)) { add(state); } } public long calculateTimeBetweenFirstAnd(PassportState endState) { long startTime = firstTime(); try (Unlocker ignored = lock()) { for (PassportItem item : history) { if (item.getState() == endState) { return item.getTime() - startTime; } } } return now() - startTime; } /** * NOTE: This is NOT nanos since epoch. It's just since an arbitrary point in time. So only use relatively. */ public long firstTime() { try (Unlocker ignored = lock()) { return history.getFirst().getTime(); } } public long creationTimeSinceEpochMs() { return creationTimeSinceEpochMs; } public long calculateTimeBetween(StartAndEnd sae) { if (sae.startNotFound() || sae.endNotFound()) { return 0; } return sae.endTime - sae.startTime; } public long calculateTimeBetweenButIfNoEndThenUseNow(StartAndEnd sae) { if (sae.startNotFound()) { return 0; } // If no end state found, then default to now. if (sae.endNotFound()) { sae.endTime = now(); } return sae.endTime - sae.startTime; } public StartAndEnd findStartAndEndStates(PassportState startState, PassportState endState) { StartAndEnd sae = new StartAndEnd(); try (Unlocker ignored = lock()) { for (PassportItem item : history) { if (item.getState() == startState) { sae.startTime = item.getTime(); } else if (item.getState() == endState) { sae.endTime = item.getTime(); } } } return sae; } public StartAndEnd findFirstStartAndLastEndStates(PassportState startState, PassportState endState) { StartAndEnd sae = new StartAndEnd(); try (Unlocker ignored = lock()) { for (PassportItem item : history) { if (sae.startNotFound() && item.getState() == startState) { sae.startTime = item.getTime(); } else if (item.getState() == endState) { sae.endTime = item.getTime(); } } } return sae; } public StartAndEnd findLastStartAndFirstEndStates(PassportState startState, PassportState endState) { StartAndEnd sae = new StartAndEnd(); try (Unlocker ignored = lock()) { for (PassportItem item : history) { if (item.getState() == startState) { sae.startTime = item.getTime(); } else if (sae.endNotFound() && item.getState() == endState) { sae.endTime = item.getTime(); } } } return sae; } public List<StartAndEnd> findEachPairOf(PassportState startState, PassportState endState) { ArrayList<StartAndEnd> items = new ArrayList<>(); StartAndEnd currentPair = null; try (Unlocker ignored = lock()) { for (PassportItem item : history) { if (item.getState() == startState) { if (currentPair == null) { currentPair = new StartAndEnd(); currentPair.startTime = item.getTime(); } } else if (item.getState() == endState) { if (currentPair != null) { currentPair.endTime = item.getTime(); items.add(currentPair); currentPair = null; } } } } return items; } public PassportItem findState(PassportState state) { try (Unlocker ignored = lock()) { for (PassportItem item : history) { if (item.getState() == state) { return item; } } } return null; } public PassportItem findStateBackwards(PassportState state) { try (Unlocker ignored = lock()) { Iterator itr = history.descendingIterator(); while (itr.hasNext()) { PassportItem item = (PassportItem) itr.next(); if (item.getState() == state) { return item; } } } return null; } public List<PassportItem> findStates(PassportState state) { ArrayList<PassportItem> items = new ArrayList<>(); try (Unlocker ignored = lock()) { for (PassportItem item : history) { if (item.getState() == state) { items.add(item); } } } return items; } public List<Long> findTimes(PassportState state) { long startTick = firstTime(); ArrayList<Long> items = new ArrayList<>(); try (Unlocker ignored = lock()) { for (PassportItem item : history) { if (item.getState() == state) { items.add(item.getTime() - startTick); } } } return items; } public boolean wasProxyAttempt() { // If an attempt was made to send outbound request headers on this session, then assume it was an // attempt to proxy. return findState(PassportState.OUT_REQ_HEADERS_SENDING) != null; } private long now() { return ticker.read(); } @Override public String toString() { try (Unlocker ignored = lock()) { long startTime = history.size() > 0 ? firstTime() : 0; long now = now(); StringBuilder sb = new StringBuilder(); sb.append("CurrentPassport {"); sb.append("start_ms=").append(creationTimeSinceEpochMs()).append(", "); sb.append('['); for (PassportItem item : history) { sb.append('+') .append(item.getTime() - startTime) .append('=') .append(item.getState().name()) .append(", "); } sb.append('+').append(now - startTime).append('=').append("NOW"); sb.append(']'); sb.append('}'); return sb.toString(); } } @VisibleForTesting public static CurrentPassport parseFromToString(String text) { CurrentPassport passport = null; Pattern ptn = Pattern.compile("CurrentPassport \\{start_ms=\\d+, \\[(.*)\\]\\}"); Pattern ptnState = Pattern.compile("^\\+(\\d+)=(.+)$"); Matcher m = ptn.matcher(text); if (m.matches()) { String[] stateStrs = m.group(1).split(", "); MockTicker ticker = new MockTicker(); passport = new CurrentPassport(ticker); try (Unlocker ignored = passport.lock()) { for (String stateStr : stateStrs) { Matcher stateMatch = ptnState.matcher(stateStr); if (stateMatch.matches()) { String stateName = stateMatch.group(2); if (stateName.equals("NOW")) { long startTime = passport.history.size() > 0 ? passport.firstTime() : 0; long now = Long.parseLong(stateMatch.group(1)) + startTime; ticker.setNow(now); } else { PassportState state = PassportState.valueOf(stateName); PassportItem item = new PassportItem(state, Long.parseLong(stateMatch.group(1))); passport.history.add(item); } } } } } return passport; } private static class MockTicker extends Ticker { private long now = -1; @Override public long read() { if (now == -1) { throw new IllegalStateException(); } return now; } public void setNow(long now) { this.now = now; } } } class CountingCurrentPassport extends CurrentPassport { private static final Counter IN_REQ_HEADERS_RECEIVED_CNT = createCounter("in_req_hdrs_rec"); private static final Counter IN_REQ_LAST_CONTENT_RECEIVED_CNT = createCounter("in_req_last_cont_rec"); private static final Counter IN_RESP_HEADERS_RECEIVED_CNT = createCounter("in_resp_hdrs_rec"); private static final Counter IN_RESP_LAST_CONTENT_RECEIVED_CNT = createCounter("in_resp_last_cont_rec"); private static final Counter OUT_REQ_HEADERS_SENT_CNT = createCounter("out_req_hdrs_sent"); private static final Counter OUT_REQ_LAST_CONTENT_SENT_CNT = createCounter("out_req_last_cont_sent"); private static final Counter OUT_RESP_HEADERS_SENT_CNT = createCounter("out_resp_hdrs_sent"); private static final Counter OUT_RESP_LAST_CONTENT_SENT_CNT = createCounter("out_resp_last_cont_sent"); private static Counter createCounter(String name) { return Spectator.globalRegistry().counter("zuul.passport." + name); } public CountingCurrentPassport() { super(); incrementStateCounter(getState()); } @Override public void add(PassportState state) { super.add(state); incrementStateCounter(state); } private void incrementStateCounter(PassportState state) { switch (state) { case IN_REQ_HEADERS_RECEIVED: IN_REQ_HEADERS_RECEIVED_CNT.increment(); break; case IN_REQ_LAST_CONTENT_RECEIVED: IN_REQ_LAST_CONTENT_RECEIVED_CNT.increment(); break; case OUT_REQ_HEADERS_SENT: OUT_REQ_HEADERS_SENT_CNT.increment(); break; case OUT_REQ_LAST_CONTENT_SENT: OUT_REQ_LAST_CONTENT_SENT_CNT.increment(); break; case IN_RESP_HEADERS_RECEIVED: IN_RESP_HEADERS_RECEIVED_CNT.increment(); break; case IN_RESP_LAST_CONTENT_RECEIVED: IN_RESP_LAST_CONTENT_RECEIVED_CNT.increment(); break; case OUT_RESP_HEADERS_SENT: OUT_RESP_HEADERS_SENT_CNT.increment(); break; case OUT_RESP_LAST_CONTENT_SENT: OUT_RESP_LAST_CONTENT_SENT_CNT.increment(); break; } } }
6,403
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/passport/PassportState.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.passport; public enum PassportState { IN_REQ_HEADERS_RECEIVED, IN_REQ_CONTENT_RECEIVED, IN_REQ_LAST_CONTENT_RECEIVED, IN_REQ_REJECTED, IN_REQ_READ_TIMEOUT, IN_REQ_CANCELLED, OUT_REQ_HEADERS_SENDING, OUT_REQ_HEADERS_SENT, OUT_REQ_HEADERS_ERROR_SENDING, OUT_REQ_CONTENT_SENDING, OUT_REQ_CONTENT_SENT, OUT_REQ_CONTENT_ERROR_SENDING, OUT_REQ_LAST_CONTENT_SENDING, OUT_REQ_LAST_CONTENT_SENT, OUT_REQ_LAST_CONTENT_ERROR_SENDING, IN_RESP_HEADERS_RECEIVED, IN_RESP_CONTENT_RECEIVED, IN_RESP_LAST_CONTENT_RECEIVED, OUT_RESP_HEADERS_SENDING, OUT_RESP_HEADERS_SENT, OUT_RESP_HEADERS_ERROR_SENDING, OUT_RESP_CONTENT_SENDING, OUT_RESP_CONTENT_SENT, OUT_RESP_CONTENT_ERROR_SENDING, OUT_RESP_LAST_CONTENT_SENDING, OUT_RESP_LAST_CONTENT_SENT, OUT_RESP_LAST_CONTENT_ERROR_SENDING, FILTERS_INBOUND_START, FILTERS_INBOUND_END, FILTERS_OUTBOUND_START, FILTERS_OUTBOUND_END, FILTERS_INBOUND_BUF_START, FILTERS_INBOUND_BUF_END, FILTERS_OUTBOUND_BUF_START, FILTERS_OUTBOUND_BUF_END, ORIGIN_CONN_ACQUIRE_START, ORIGIN_CONN_ACQUIRE_END, ORIGIN_CONN_ACQUIRE_FAILED, MISC_IO_START, MISC_IO_STOP, SERVER_CH_DISCONNECT, SERVER_CH_CLOSE, SERVER_CH_EXCEPTION, SERVER_CH_IDLE_TIMEOUT, SERVER_CH_ACTIVE, SERVER_CH_INACTIVE, SERVER_CH_THROTTLING, SERVER_CH_REJECTING, SERVER_CH_SSL_HANDSHAKE_COMPLETE, ORIGIN_CH_CONNECTING, ORIGIN_CH_CONNECTED, ORIGIN_CH_DISCONNECT, ORIGIN_CH_CLOSE, ORIGIN_CH_EXCEPTION, ORIGIN_CH_ACTIVE, ORIGIN_CH_INACTIVE, ORIGIN_CH_IDLE_TIMEOUT, ORIGIN_CH_POOL_RETURNED, ORIGIN_CH_READ_TIMEOUT, ORIGIN_CH_IO_EX, ORIGIN_RETRY_START, }
6,404
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/passport/PassportItem.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.passport; public class PassportItem { private final long time; private final PassportState state; public PassportItem(PassportState state, long time) { this.time = time; this.state = state; } public long getTime() { return time; } public PassportState getState() { return state; } @Override public String toString() { return time + "=" + state; } }
6,405
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/passport/StartAndEnd.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.passport; public class StartAndEnd { long startTime = -1; long endTime = -1; public long getStart() { return startTime; } public long getEnd() { return endTime; } boolean startNotFound() { return startTime == -1; } boolean endNotFound() { return endTime == -1; } }
6,406
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/monitoring/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.monitoring; /** * Time based monitoring metric. * * @author mhawthorne */ public interface Tracer { /** * Stops and Logs a time based tracer * */ void stopAndLog(); /** * Sets the name for the time based tracer * * @param name a <code>String</code> value */ void setName(String name); }
6,407
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/monitoring/TracerFactory.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.monitoring; /** * Abstraction layer to provide time-based monitoring. * * @author mhawthorne */ public abstract class TracerFactory { private static TracerFactory INSTANCE; /** * sets a TracerFactory Implementation * * @param f a <code>TracerFactory</code> value */ public static final void initialize(TracerFactory f) { INSTANCE = f; } /** * Returns the singleton TracerFactory * * @return a <code>TracerFactory</code> value */ public static final TracerFactory instance() { if (INSTANCE == null) { throw new IllegalStateException(String.format("%s not initialized", TracerFactory.class.getSimpleName())); } return INSTANCE; } public abstract Tracer startMicroTracer(String name); }
6,408
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/monitoring/ConnTimer.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.monitoring; import com.netflix.config.DynamicBooleanProperty; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.histogram.PercentileTimer; import com.netflix.zuul.Attrs; import com.netflix.zuul.netty.server.Server; import io.netty.channel.Channel; import io.netty.util.AttributeKey; import javax.annotation.Nullable; import java.time.Duration; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit; /** * A timer for connection stats. Not thread-safe. */ public final class ConnTimer { private static final DynamicBooleanProperty PRECISE_TIMING = new DynamicBooleanProperty("zuul.conn.precise_timing", false); private static final AttributeKey<ConnTimer> CONN_TIMER = AttributeKey.newInstance("zuul.conntimer"); private static final Duration MIN_CONN_TIMING = Duration.ofNanos(1024); private static final Duration MAX_CONN_TIMING = Duration.ofDays(366); private static final Attrs EMPTY = Attrs.newInstance(); private final Registry registry; private final Channel chan; // TODO(carl-mastrangelo): make this changeable. private final Id metricBase; @Nullable private final Id preciseMetricBase; private final Map<String, Long> timings = new LinkedHashMap<>(); private ConnTimer(Registry registry, Channel chan, Id metricBase) { this.registry = Objects.requireNonNull(registry); this.chan = Objects.requireNonNull(chan); this.metricBase = Objects.requireNonNull(metricBase); if (PRECISE_TIMING.get()) { preciseMetricBase = registry.createId(metricBase.name() + ".pct").withTags(metricBase.tags()); } else { preciseMetricBase = null; } } public static ConnTimer install(Channel chan, Registry registry, Id metricBase) { ConnTimer timer = new ConnTimer(registry, chan, metricBase); if (!chan.attr(CONN_TIMER).compareAndSet(null, timer)) { throw new IllegalStateException("pre-existing timer already present"); } return timer; } public static ConnTimer from(Channel chan) { Objects.requireNonNull(chan); ConnTimer timer = chan.attr(CONN_TIMER).get(); if (timer != null) { return timer; } if (chan.parent() != null && (timer = chan.parent().attr(CONN_TIMER).get()) != null) { return timer; } throw new IllegalStateException("no timer on channel"); } public void record(Long now, String event) { record(now, event, EMPTY); } public void record(Long now, String event, Attrs extraDimensions) { if (timings.containsKey(event)) { return; } Objects.requireNonNull(now); Objects.requireNonNull(event); Objects.requireNonNull(extraDimensions); Attrs connDims = chan.attr(Server.CONN_DIMENSIONS).get(); Map<String, String> dimTags = new HashMap<>(connDims.size() + extraDimensions.size()); connDims.forEach((k, v) -> dimTags.put(k.name(), String.valueOf(v))); extraDimensions.forEach((k, v) -> dimTags.put(k.name(), String.valueOf(v))); // Note: this is effectively O(n^2) because it will be called for each event in the connection // setup. It should be bounded to at most 10 or so. timings.forEach((from, stamp) -> { long durationNanos = now - stamp; if (durationNanos == 0) { // This may happen if an event is double listed, or if the timer is not accurate enough to record // it. return; } registry.timer(buildId(metricBase, from, event, dimTags)).record(durationNanos, TimeUnit.NANOSECONDS); if (preciseMetricBase != null) { PercentileTimer.builder(registry) .withId(buildId(preciseMetricBase, from, event, dimTags)) .withRange(MIN_CONN_TIMING, MAX_CONN_TIMING) .build() .record(durationNanos, TimeUnit.NANOSECONDS); } }); timings.put(event, now); } private Id buildId(Id base, String from, String to, Map<String, String> tags) { return registry.createId(metricBase.name() + '.' + from + '-' + to) .withTags(base.tags()) .withTags(tags); } }
6,409
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/monitoring/MonitoringHelper.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.monitoring; /** * Dummy implementations of CounterFactory, TracerFactory, and Tracer * @author mhawthorne */ public class MonitoringHelper { public static final void initMocks() { TracerFactory.initialize(new TracerFactoryImpl()); } private static final class TracerFactoryImpl extends TracerFactory { @Override public Tracer startMicroTracer(String name) { return new TracerImpl(); } } private static final class TracerImpl implements Tracer { @Override public void setName(String name) {} @Override public void stopAndLog() {} } }
6,410
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/monitoring/ConnCounter.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.monitoring; import com.netflix.spectator.api.Gauge; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.zuul.Attrs; import com.netflix.zuul.netty.server.Server; import io.netty.channel.Channel; import io.netty.util.AttributeKey; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * A counter for connection stats. Not thread-safe. */ public final class ConnCounter { private static final Logger logger = LoggerFactory.getLogger(ConnCounter.class); private static final AttributeKey<ConnCounter> CONN_COUNTER = AttributeKey.newInstance("zuul.conncounter"); private static final int LOCK_COUNT = 256; private static final int LOCK_MASK = LOCK_COUNT - 1; private static final Attrs EMPTY = Attrs.newInstance(); /** * An array of locks to guard the gauges. This is the same as Guava's Striped, but avoids the dep. * <p> * This can be removed after https://github.com/Netflix/spectator/issues/862 is fixed. */ private static final Object[] locks = new Object[LOCK_COUNT]; static { assert (LOCK_COUNT & LOCK_MASK) == 0; for (int i = 0; i < locks.length; i++) { locks[i] = new Object(); } } private final Registry registry; private final Channel chan; private final Id metricBase; private String lastCountKey; private final Map<String, Gauge> counts = new HashMap<>(); private ConnCounter(Registry registry, Channel chan, Id metricBase) { this.registry = Objects.requireNonNull(registry); this.chan = Objects.requireNonNull(chan); this.metricBase = Objects.requireNonNull(metricBase); } public static ConnCounter install(Channel chan, Registry registry, Id metricBase) { ConnCounter counter = new ConnCounter(registry, chan, metricBase); if (!chan.attr(CONN_COUNTER).compareAndSet(null, counter)) { throw new IllegalStateException("pre-existing counter already present"); } return counter; } public static ConnCounter from(Channel chan) { Objects.requireNonNull(chan); ConnCounter counter = chan.attr(CONN_COUNTER).get(); if (counter != null) { return counter; } if (chan.parent() != null && (counter = chan.parent().attr(CONN_COUNTER).get()) != null) { return counter; } throw new IllegalStateException("no counter on channel"); } public void increment(String event) { increment(event, EMPTY); } public void increment(String event, Attrs extraDimensions) { Objects.requireNonNull(event); Objects.requireNonNull(extraDimensions); if (counts.containsKey(event)) { // TODO(carl-mastrangelo): make this throw IllegalStateException after verifying this doesn't happen. logger.warn("Duplicate conn counter increment {}", event); return; } Attrs connDims = chan.attr(Server.CONN_DIMENSIONS).get(); Map<String, String> dimTags = new HashMap<>(connDims.size() + extraDimensions.size()); connDims.forEach((k, v) -> dimTags.put(k.name(), String.valueOf(v))); extraDimensions.forEach((k, v) -> dimTags.put(k.name(), String.valueOf(v))); dimTags.put("from", lastCountKey != null ? lastCountKey : "nascent"); lastCountKey = event; Id id = registry.createId(metricBase.name() + '.' + event) .withTags(metricBase.tags()) .withTags(dimTags); Gauge gauge = registry.gauge(id); synchronized (getLock(id)) { double current = gauge.value(); gauge.set(Double.isNaN(current) ? 1 : current + 1); } counts.put(event, gauge); } public double getCurrentActiveConns() { return counts.containsKey("active") ? counts.get("active").value() : 0.0; } public void decrement(String event) { Objects.requireNonNull(event); Gauge gauge = counts.remove(event); if (gauge == null) { // TODO(carl-mastrangelo): make this throw IllegalStateException after verifying this doesn't happen. logger.warn("Missing conn counter increment {}", event); return; } synchronized (getLock(gauge.id())) { // Noop gauges break this assertion in tests, but the type is package private. Check to make sure // the gauge has a value, or by implementation cannot have a value. assert !Double.isNaN(gauge.value()) || gauge.getClass().getName().equals("com.netflix.spectator.api.NoopGauge"); gauge.set(gauge.value() - 1); } } // This is here to pick the correct lock stripe. This avoids multiple threads synchronizing on the // same lock in the common case. This can go away once there is an atomic gauge update implemented // in spectator. private static Object getLock(Id id) { return locks[id.hashCode() & LOCK_MASK]; } }
6,411
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/origins/OriginManager.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.origins; import com.netflix.zuul.context.SessionContext; /** * User: michaels@netflix.com * Date: 5/11/15 * Time: 3:15 PM */ public interface OriginManager<T extends Origin> { T getOrigin(OriginName originName, String uri, SessionContext ctx); T createOrigin(OriginName originName, String uri, SessionContext ctx); }
6,412
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/origins/OriginName.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.origins; import com.netflix.zuul.util.VipUtils; import java.util.Locale; import java.util.Objects; /** * An Origin Name is a tuple of a target to connect to, an authority to use for connecting, and an NIWS client name * used for configuration of an Origin. These fields are semi independent, but are usually used in proximity to each * other, and thus makes sense to group them together. * * <p>The {@code target} represents the string used to look up the origin during name resolution. Currently, this is * a {@code VIP}, which is passed to a Eureka name resolved. In the future, other targets will be supported, such as * DNS. * * <p>The {@code authority} represents who we plan to connect to. In the case of TLS / SSL connections, this can be * used to verify the remote endpoint. It is not specified what the format is, but it may not be null. In the case * of VIPs, which are frequently used with AWS clusters, this is the Application Name. * * <p>The {@code NIWS Client Name} is a legacy construct, which is used to configure an origin. When the origin is * created, the NIWS client name can be used as a key into a configuration mapping to decide how the Origin should * behave. By default, the VIP is the same for the NIWS client name, but it can be different in scenarios where * multiple connections to the same origin are needed. Additionally, the NIWS client name also functions as a key * in metrics. */ public final class OriginName { /** * The NIWS client name of the origin. This is typically used in metrics and for configuration of NIWS * {@link com.netflix.client.config.IClientConfig} objects. */ private final String niwsClientName; /** * This should not be used in {@link #equals} or {@link #hashCode} as it is already covered by * {@link #niwsClientName}. */ private final String metricId; /** * The target to connect to, used for name resolution. This is typically the VIP. */ private final String target; /** * The authority of this origin. Usually this is the Application name of origin. It is primarily * used for establishing a secure connection, as well as logging. */ private final String authority; /** * @deprecated use {@link #fromVipAndApp(String, String)} */ @Deprecated public static OriginName fromVip(String vip) { return fromVipAndApp(vip, VipUtils.extractUntrustedAppNameFromVIP(vip)); } /** * @deprecated use {@link #fromVipAndApp(String, String, String)} */ @Deprecated public static OriginName fromVip(String vip, String niwsClientName) { return fromVipAndApp(vip, VipUtils.extractUntrustedAppNameFromVIP(vip), niwsClientName); } /** * Constructs an OriginName with a target and authority from the vip and app name. The vip is used as the NIWS * client name, which is frequently used for configuration. */ public static OriginName fromVipAndApp(String vip, String appName) { return fromVipAndApp(vip, appName, vip); } /** * Constructs an OriginName with a target, authority, and NIWS client name. The NIWS client name can be different * from the vip in cases where custom configuration for an Origin is needed. */ public static OriginName fromVipAndApp(String vip, String appName, String niwsClientName) { return new OriginName(vip, appName, niwsClientName); } private OriginName(String target, String authority, String niwsClientName) { this.target = Objects.requireNonNull(target, "target"); this.authority = Objects.requireNonNull(authority, "authority"); this.niwsClientName = Objects.requireNonNull(niwsClientName, "niwsClientName"); this.metricId = niwsClientName.toLowerCase(Locale.ROOT); } /** * This is typically the VIP for the given Origin. */ public String getTarget() { return target; } /** * Returns the niwsClientName. This is normally used for interaction with NIWS, and should be used without prior * knowledge that the value will be used in NIWS libraries. */ public String getNiwsClientName() { return niwsClientName; } /** * Returns the identifier for this this metric name. This may be different than any of the other * fields; currently it is equivalent to the lowercased {@link #getNiwsClientName()}. */ public String getMetricId() { return metricId; } /** * Returns the Authority of this origin. This is used for establishing secure connections. May be absent * if the authority is not trusted. */ public String getAuthority() { return authority; } @Override public boolean equals(Object o) { if (!(o instanceof OriginName)) { return false; } OriginName that = (OriginName) o; return Objects.equals(niwsClientName, that.niwsClientName) && Objects.equals(target, that.target) && Objects.equals(authority, that.authority); } @Override public int hashCode() { return Objects.hash(niwsClientName, target, authority); } @Override public String toString() { return "OriginName{" + "niwsClientName='" + niwsClientName + '\'' + ", target='" + target + '\'' + ", authority='" + authority + '\'' + '}'; } }
6,413
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/origins/OriginConcurrencyExceededException.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.origins; import com.netflix.zuul.stats.status.ZuulStatusCategory; public class OriginConcurrencyExceededException extends OriginThrottledException { public OriginConcurrencyExceededException(OriginName originName) { super( originName, "Max concurrent requests on origin exceeded", ZuulStatusCategory.FAILURE_LOCAL_THROTTLED_ORIGIN_CONCURRENCY); } }
6,414
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/origins/BasicNettyOriginManager.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.origins; import com.netflix.spectator.api.Registry; import com.netflix.zuul.context.SessionContext; import javax.inject.Inject; import javax.inject.Singleton; import java.util.concurrent.ConcurrentHashMap; /** * Basic Netty Origin Manager that most apps can use. This can also serve as a useful template for creating more * complex origin managers. * * Author: Arthur Gonigberg * Date: November 30, 2017 */ @Singleton public class BasicNettyOriginManager implements OriginManager<BasicNettyOrigin> { private final Registry registry; private final ConcurrentHashMap<OriginName, BasicNettyOrigin> originMappings; @Inject public BasicNettyOriginManager(Registry registry) { this.registry = registry; this.originMappings = new ConcurrentHashMap<>(); } @Override public BasicNettyOrigin getOrigin(OriginName originName, String uri, SessionContext ctx) { return originMappings.computeIfAbsent(originName, n -> createOrigin(originName, uri, ctx)); } @Override public BasicNettyOrigin createOrigin(OriginName originName, String uri, SessionContext ctx) { return new BasicNettyOrigin(originName, registry); } }
6,415
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/origins/OriginThrottledException.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.origins; import com.netflix.zuul.exception.ZuulException; import com.netflix.zuul.stats.status.StatusCategory; import java.util.Objects; public abstract class OriginThrottledException extends ZuulException { private final OriginName originName; private final StatusCategory statusCategory; public OriginThrottledException(OriginName originName, String msg, StatusCategory statusCategory) { // Ensure this exception does not fill its stacktrace as causes too much load. super(msg + ", origin=" + originName, true); this.originName = Objects.requireNonNull(originName, "originName"); this.statusCategory = statusCategory; this.setStatusCode(503); } public OriginName getOriginName() { return originName; } public StatusCategory getStatusCategory() { return statusCategory; } }
6,416
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/origins/InstrumentedOrigin.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.origins; import com.netflix.zuul.message.http.HttpRequestMessage; /** * User: michaels@netflix.com * Date: 10/8/14 * Time: 6:15 PM */ public interface InstrumentedOrigin extends Origin { double getErrorPercentage(); double getErrorAllPercentage(); void adjustRetryPolicyIfNeeded(HttpRequestMessage zuulRequest); void preRequestChecks(HttpRequestMessage zuulRequest); void recordSuccessResponse(); void recordProxyRequestEnd(); }
6,417
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/origins/NettyOrigin.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.origins; import com.netflix.client.config.IClientConfig; import com.netflix.spectator.api.Registry; import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.discovery.DiscoveryResult; import com.netflix.zuul.message.http.HttpRequestMessage; import com.netflix.zuul.message.http.HttpResponseMessage; import com.netflix.zuul.netty.connectionpool.PooledConnection; import com.netflix.zuul.niws.RequestAttempt; 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; /** * Netty Origin interface for integrating cleanly with the ProxyEndpoint state management class. * * Author: Arthur Gonigberg * Date: November 29, 2017 */ public interface NettyOrigin extends InstrumentedOrigin { Promise<PooledConnection> connectToOrigin( final HttpRequestMessage zuulReq, EventLoop eventLoop, int attemptNumber, CurrentPassport passport, AtomicReference<DiscoveryResult> chosenServer, AtomicReference<? super InetAddress> chosenHostAddr); int getMaxRetriesForRequest(SessionContext context); void onRequestExecutionStart(final HttpRequestMessage zuulReq); void onRequestStartWithServer( final HttpRequestMessage zuulReq, final DiscoveryResult discoveryResult, int attemptNum); void onRequestExceptionWithServer( final HttpRequestMessage zuulReq, final DiscoveryResult discoveryResult, final int attemptNum, Throwable t); void onRequestExecutionSuccess( final HttpRequestMessage zuulReq, final HttpResponseMessage zuulResp, final DiscoveryResult discoveryResult, final int attemptNum); void onRequestExecutionFailed( final HttpRequestMessage zuulReq, final DiscoveryResult discoveryResult, final int attemptNum, Throwable t); void recordFinalError(final HttpRequestMessage requestMsg, final Throwable throwable); void recordFinalResponse(final HttpResponseMessage resp); RequestAttempt newRequestAttempt( final DiscoveryResult server, final InetAddress serverAddr, final SessionContext zuulCtx, int attemptNum); String getIpAddrFromServer(DiscoveryResult server); IClientConfig getClientConfig(); Registry getSpectatorRegistry(); }
6,418
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/origins/Origin.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.origins; /** * User: michaels@netflix.com * Date: 5/11/15 * Time: 3:14 PM */ public interface Origin { OriginName getName(); boolean isAvailable(); boolean isCold(); }
6,419
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/origins/BasicNettyOrigin.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.origins; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfig; import com.netflix.config.CachedDynamicBooleanProperty; import com.netflix.config.CachedDynamicIntProperty; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.Registry; import com.netflix.zuul.context.CommonContextKeys; import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.discovery.DiscoveryResult; import com.netflix.zuul.exception.ErrorType; import com.netflix.zuul.message.http.HttpRequestMessage; import com.netflix.zuul.message.http.HttpResponseMessage; import com.netflix.zuul.netty.NettyRequestAttemptFactory; import com.netflix.zuul.netty.SpectatorUtils; import com.netflix.zuul.netty.connectionpool.ClientChannelManager; import com.netflix.zuul.netty.connectionpool.DefaultClientChannelManager; import com.netflix.zuul.netty.connectionpool.PooledConnection; import com.netflix.zuul.niws.RequestAttempt; import com.netflix.zuul.passport.CurrentPassport; 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.EventLoop; import io.netty.util.concurrent.Promise; import java.net.InetAddress; import java.util.Objects; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; /** * Netty Origin basic implementation that can be used for most apps, with the more complex methods having no-op * implementations. * * Author: Arthur Gonigberg * Date: December 01, 2017 */ public class BasicNettyOrigin implements NettyOrigin { private final OriginName originName; private final Registry registry; private final IClientConfig config; private final ClientChannelManager clientChannelManager; private final NettyRequestAttemptFactory requestAttemptFactory; private final AtomicInteger concurrentRequests; private final Counter rejectedRequests; private final CachedDynamicIntProperty concurrencyMax; private final CachedDynamicBooleanProperty concurrencyProtectionEnabled; public BasicNettyOrigin(OriginName originName, Registry registry) { this.originName = Objects.requireNonNull(originName, "originName"); this.registry = registry; this.config = setupClientConfig(originName); this.clientChannelManager = new DefaultClientChannelManager(originName, config, registry); this.clientChannelManager.init(); this.requestAttemptFactory = new NettyRequestAttemptFactory(); String niwsClientName = getName().getNiwsClientName(); this.concurrentRequests = SpectatorUtils.newGauge("zuul.origin.concurrent.requests", niwsClientName, new AtomicInteger(0)); this.rejectedRequests = SpectatorUtils.newCounter("zuul.origin.rejected.requests", niwsClientName); this.concurrencyMax = new CachedDynamicIntProperty("zuul.origin." + niwsClientName + ".concurrency.max.requests", 200); this.concurrencyProtectionEnabled = new CachedDynamicBooleanProperty( "zuul.origin." + niwsClientName + ".concurrency.protect.enabled", true); } protected IClientConfig setupClientConfig(OriginName originName) { // Get the NIWS properties for this Origin. IClientConfig niwsClientConfig = DefaultClientConfigImpl.getClientConfigWithDefaultValues(originName.getNiwsClientName()); niwsClientConfig.set(CommonClientConfigKey.ClientClassName, originName.getNiwsClientName()); niwsClientConfig.loadProperties(originName.getNiwsClientName()); return niwsClientConfig; } @Override public OriginName getName() { return originName; } @Override public boolean isAvailable() { return clientChannelManager.isAvailable(); } @Override public boolean isCold() { return clientChannelManager.isCold(); } @Override public Promise<PooledConnection> connectToOrigin( HttpRequestMessage zuulReq, EventLoop eventLoop, int attemptNumber, CurrentPassport passport, AtomicReference<DiscoveryResult> chosenServer, AtomicReference<? super InetAddress> chosenHostAddr) { return clientChannelManager.acquire(eventLoop, null, passport, chosenServer, chosenHostAddr); } @Override public int getMaxRetriesForRequest(SessionContext context) { return config.get(CommonClientConfigKey.MaxAutoRetriesNextServer, 0); } @Override public RequestAttempt newRequestAttempt( DiscoveryResult server, InetAddress serverAddr, SessionContext zuulCtx, int attemptNum) { return new RequestAttempt( server, serverAddr, config, attemptNum, config.get(CommonClientConfigKey.ReadTimeout)); } @Override public String getIpAddrFromServer(DiscoveryResult discoveryResult) { final Optional<String> ipAddr = discoveryResult.getIPAddr(); return ipAddr.isPresent() ? ipAddr.get() : null; } @Override public IClientConfig getClientConfig() { return config; } @Override public Registry getSpectatorRegistry() { return registry; } @Override public void recordFinalError(HttpRequestMessage requestMsg, Throwable throwable) { if (throwable == null) { return; } final SessionContext zuulCtx = requestMsg.getContext(); // Choose StatusCategory based on the ErrorType. final ErrorType et = requestAttemptFactory.mapNettyToOutboundErrorType(throwable); final StatusCategory nfs = et.getStatusCategory(); StatusCategoryUtils.setStatusCategory(zuulCtx, nfs); StatusCategoryUtils.setOriginStatusCategory(zuulCtx, nfs); zuulCtx.setError(throwable); } @Override public void recordFinalResponse(HttpResponseMessage resp) { if (resp != null) { final SessionContext zuulCtx = resp.getContext(); // Store the status code of final attempt response. int originStatusCode = resp.getStatus(); zuulCtx.put(CommonContextKeys.ORIGIN_STATUS, originStatusCode); // Mark origin StatusCategory based on http status code. StatusCategory originNfs = ZuulStatusCategory.SUCCESS; if (originStatusCode == 503) { originNfs = ZuulStatusCategory.FAILURE_ORIGIN_THROTTLED; } else if (StatusCategoryUtils.isResponseHttpErrorStatus(originStatusCode)) { originNfs = ZuulStatusCategory.FAILURE_ORIGIN; } StatusCategoryUtils.setOriginStatusCategory(zuulCtx, originNfs); // Choose the zuul StatusCategory based on the origin one... // ... but only if existing one has not already been set to a non-success value. StatusCategoryUtils.storeStatusCategoryIfNotAlreadyFailure(zuulCtx, originNfs); } } @Override public void preRequestChecks(HttpRequestMessage zuulRequest) { if (concurrencyProtectionEnabled.get() && concurrentRequests.get() > concurrencyMax.get()) { rejectedRequests.increment(); throw new OriginConcurrencyExceededException(getName()); } concurrentRequests.incrementAndGet(); } @Override public void recordProxyRequestEnd() { concurrentRequests.decrementAndGet(); } /* Not required for basic operation */ @Override public double getErrorPercentage() { return 0; } @Override public double getErrorAllPercentage() { return 0; } @Override public void onRequestExecutionStart(HttpRequestMessage zuulReq) {} @Override public void onRequestStartWithServer(HttpRequestMessage zuulReq, DiscoveryResult discoveryResult, int attemptNum) {} @Override public void onRequestExceptionWithServer( HttpRequestMessage zuulReq, DiscoveryResult discoveryResult, int attemptNum, Throwable t) {} @Override public void onRequestExecutionSuccess( HttpRequestMessage zuulReq, HttpResponseMessage zuulResp, DiscoveryResult discoveryResult, int attemptNum) {} @Override public void onRequestExecutionFailed( HttpRequestMessage zuulReq, DiscoveryResult discoveryResult, int attemptNum, Throwable t) {} @Override public void adjustRetryPolicyIfNeeded(HttpRequestMessage zuulRequest) {} @Override public void recordSuccessResponse() {} }
6,420
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/exception/OutboundErrorType.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.exception; import com.netflix.client.ClientException; import com.netflix.zuul.stats.status.StatusCategory; import com.netflix.zuul.stats.status.ZuulStatusCategory; /** * Outbound Error Type * * Author: Arthur Gonigberg * Date: November 28, 2017 */ public enum OutboundErrorType implements ErrorType { READ_TIMEOUT( ERROR_TYPE_READ_TIMEOUT_STATUS.get(), ZuulStatusCategory.FAILURE_ORIGIN_READ_TIMEOUT, ClientException.ErrorType.READ_TIMEOUT_EXCEPTION), CONNECT_ERROR( ERROR_TYPE_CONNECT_ERROR_STATUS.get(), ZuulStatusCategory.FAILURE_ORIGIN_CONNECTIVITY, ClientException.ErrorType.CONNECT_EXCEPTION), SERVICE_UNAVAILABLE( ERROR_TYPE_SERVICE_UNAVAILABLE_STATUS.get(), ZuulStatusCategory.FAILURE_ORIGIN_THROTTLED, ClientException.ErrorType.SERVER_THROTTLED), ERROR_STATUS_RESPONSE( ERROR_TYPE_ERROR_STATUS_RESPONSE_STATUS.get(), ZuulStatusCategory.FAILURE_ORIGIN, ClientException.ErrorType.GENERAL), NO_AVAILABLE_SERVERS( ERROR_TYPE_NOSERVERS_STATUS.get(), ZuulStatusCategory.FAILURE_ORIGIN_NO_SERVERS, ClientException.ErrorType.CONNECT_EXCEPTION), ORIGIN_SERVER_MAX_CONNS( ERROR_TYPE_ORIGIN_SERVER_MAX_CONNS_STATUS.get(), ZuulStatusCategory.FAILURE_LOCAL_THROTTLED_ORIGIN_SERVER_MAXCONN, ClientException.ErrorType.CLIENT_THROTTLED), RESET_CONNECTION( ERROR_TYPE_ORIGIN_RESET_CONN_STATUS.get(), ZuulStatusCategory.FAILURE_ORIGIN_RESET_CONNECTION, ClientException.ErrorType.CONNECT_EXCEPTION), CANCELLED(400, ZuulStatusCategory.FAILURE_CLIENT_CANCELLED, ClientException.ErrorType.SOCKET_TIMEOUT_EXCEPTION), ORIGIN_CONCURRENCY_EXCEEDED( ERROR_TYPE_ORIGIN_CONCURRENCY_EXCEEDED_STATUS.get(), ZuulStatusCategory.FAILURE_LOCAL_THROTTLED_ORIGIN_CONCURRENCY, ClientException.ErrorType.SERVER_THROTTLED), OTHER(ERROR_TYPE_OTHER_STATUS.get(), ZuulStatusCategory.FAILURE_LOCAL, ClientException.ErrorType.GENERAL); private static final String NAME_PREFIX = "ORIGIN_"; private final int statusCodeToReturn; private final StatusCategory statusCategory; private final ClientException.ErrorType clientErrorType; OutboundErrorType( int statusCodeToReturn, StatusCategory statusCategory, ClientException.ErrorType clientErrorType) { this.statusCodeToReturn = statusCodeToReturn; this.statusCategory = statusCategory; this.clientErrorType = clientErrorType; } @Override public int getStatusCodeToReturn() { return statusCodeToReturn; } @Override public StatusCategory getStatusCategory() { return statusCategory; } @Override public ClientException.ErrorType getClientErrorType() { return clientErrorType; } @Override public String toString() { return NAME_PREFIX + name(); } }
6,421
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/exception/RequestExpiredException.java
/* * Copyright 2023 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.exception; /** * @author Argha C * @since 4/26/23 */ public class RequestExpiredException extends ZuulException { public RequestExpiredException(String message) { super(message, true); setStatusCode(504); } }
6,422
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/exception/ZuulFilterConcurrencyExceededException.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.exception; import com.netflix.zuul.filters.ZuulFilter; public class ZuulFilterConcurrencyExceededException extends ZuulException { public ZuulFilterConcurrencyExceededException(ZuulFilter filter, int concurrencyLimit) { super(filter.filterName() + " exceeded concurrency limit of " + concurrencyLimit, true); } }
6,423
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/exception/ZuulException.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.exception; /** * All handled exceptions in Zuul are ZuulExceptions * @author Mikey Cohen * Date: 10/20/11 * Time: 4:33 PM */ public class ZuulException extends RuntimeException { private String errorCause; private int statusCode = 500; private boolean shouldLogAsError = true; /** * Source Throwable, message, status code and info about the cause * @param sMessage * @param throwable * @param errorCause */ public ZuulException(String sMessage, Throwable throwable, String errorCause) { super(sMessage, throwable); this.errorCause = errorCause; } /** * error message, status code and info about the cause * @param sMessage * @param errorCause */ public ZuulException(String sMessage, String errorCause) { this(sMessage, errorCause, false); } public ZuulException(String sMessage, String errorCause, boolean noStackTrace) { super(sMessage, null, noStackTrace, !noStackTrace); this.errorCause = errorCause; } public ZuulException(Throwable throwable, String sMessage, boolean noStackTrace) { super(sMessage, throwable, noStackTrace, !noStackTrace); this.errorCause = "GENERAL"; } public ZuulException(Throwable throwable) { super(throwable); this.errorCause = "GENERAL"; } public ZuulException(String sMessage) { this(sMessage, false); } public ZuulException(String sMessage, boolean noStackTrace) { super(sMessage, null, noStackTrace, !noStackTrace); this.errorCause = "GENERAL"; } public int getStatusCode() { return statusCode; } public void setStatusCode(int statusCode) { this.statusCode = statusCode; } public void dontLogAsError() { shouldLogAsError = false; } public boolean shouldLogAsError() { return shouldLogAsError; } public String getErrorCause() { return errorCause; } }
6,424
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/exception/ErrorType.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.exception; import com.netflix.client.ClientException; import com.netflix.config.DynamicIntProperty; import com.netflix.zuul.stats.status.StatusCategory; /** * Error Type * * Author: Arthur Gonigberg * Date: November 28, 2017 */ public interface ErrorType { String PROP_PREFIX = "zuul.error.outbound"; DynamicIntProperty ERROR_TYPE_READ_TIMEOUT_STATUS = new DynamicIntProperty(PROP_PREFIX + ".readtimeout.status", 504); DynamicIntProperty ERROR_TYPE_CONNECT_ERROR_STATUS = new DynamicIntProperty(PROP_PREFIX + ".connecterror.status", 502); DynamicIntProperty ERROR_TYPE_SERVICE_UNAVAILABLE_STATUS = new DynamicIntProperty(PROP_PREFIX + ".serviceunavailable.status", 503); DynamicIntProperty ERROR_TYPE_ORIGIN_CONCURRENCY_EXCEEDED_STATUS = new DynamicIntProperty(PROP_PREFIX + ".originconcurrencyexceeded.status", 503); DynamicIntProperty ERROR_TYPE_ERROR_STATUS_RESPONSE_STATUS = new DynamicIntProperty(PROP_PREFIX + ".errorstatusresponse.status", 500); DynamicIntProperty ERROR_TYPE_NOSERVERS_STATUS = new DynamicIntProperty(PROP_PREFIX + ".noservers.status", 502); DynamicIntProperty ERROR_TYPE_ORIGIN_SERVER_MAX_CONNS_STATUS = new DynamicIntProperty(PROP_PREFIX + ".servermaxconns.status", 503); DynamicIntProperty ERROR_TYPE_ORIGIN_RESET_CONN_STATUS = new DynamicIntProperty(PROP_PREFIX + ".originresetconnection.status", 504); DynamicIntProperty ERROR_TYPE_OTHER_STATUS = new DynamicIntProperty(PROP_PREFIX + ".other.status", 500); int getStatusCodeToReturn(); StatusCategory getStatusCategory(); ClientException.ErrorType getClientErrorType(); }
6,425
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/exception/OutboundException.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.exception; import com.netflix.zuul.niws.RequestAttempt; import com.netflix.zuul.niws.RequestAttempts; /** * Outbound Exception Decorator * * User: Mike Smith * Date: 10/21/15 * Time: 11:46 AM */ public class OutboundException extends ZuulException { private final ErrorType outboundErrorType; private final RequestAttempts requestAttempts; public OutboundException(ErrorType outboundErrorType, RequestAttempts requestAttempts) { super(outboundErrorType.toString(), outboundErrorType.toString(), true); this.outboundErrorType = outboundErrorType; this.requestAttempts = requestAttempts; this.setStatusCode(outboundErrorType.getStatusCodeToReturn()); this.dontLogAsError(); } public OutboundException(ErrorType outboundErrorType, RequestAttempts requestAttempts, Throwable cause) { super(outboundErrorType.toString(), cause.getMessage(), true); this.outboundErrorType = outboundErrorType; this.requestAttempts = requestAttempts; this.setStatusCode(outboundErrorType.getStatusCodeToReturn()); this.dontLogAsError(); } public RequestAttempt getFinalRequestAttempt() { return requestAttempts == null ? null : requestAttempts.getFinalAttempt(); } public ErrorType getOutboundErrorType() { return outboundErrorType; } }
6,426
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/logging/Http2FrameLoggingPerClientIpHandler.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.logging; import com.netflix.config.DynamicStringSetProperty; import com.netflix.netty.common.SourceAddressChannelHandler; import com.netflix.netty.common.http2.DynamicHttp2FrameLogger; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; /** * Be aware that this will only work correctly for devices connected _directly_ to Zuul - ie. connected * through an ELB TCP Listener. And not through FTL either. */ public class Http2FrameLoggingPerClientIpHandler extends ChannelInboundHandlerAdapter { private static DynamicStringSetProperty IPS = new DynamicStringSetProperty("server.http2.frame.logging.ips", ""); @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { try { String clientIP = ctx.channel() .attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS) .get(); if (IPS.get().contains(clientIP)) { ctx.channel().attr(DynamicHttp2FrameLogger.ATTR_ENABLE).set(Boolean.TRUE); ctx.pipeline().remove(this); } } finally { super.channelRead(ctx, msg); } } }
6,427
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/stats/BasicRequestMetricsPublisher.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.stats; import com.netflix.zuul.context.SessionContext; /** * User: michaels@netflix.com * Date: 6/4/15 * Time: 4:22 PM */ public class BasicRequestMetricsPublisher implements RequestMetricsPublisher { @Override public void collectAndPublish(SessionContext context) { // Record metrics here. } }
6,428
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/stats/NamedCountingMonitor.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.stats; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Spectator; import com.netflix.spectator.api.patterns.PolledMeter; import com.netflix.zuul.stats.monitoring.MonitorRegistry; import com.netflix.zuul.stats.monitoring.NamedCount; import java.util.concurrent.atomic.AtomicLong; /** * Simple Epic counter with a name and a count. * * @author mhawthorne */ public class NamedCountingMonitor implements NamedCount { private final String name; private final AtomicLong count = new AtomicLong(); public NamedCountingMonitor(String name) { this.name = name; Registry registry = Spectator.globalRegistry(); PolledMeter.using(registry) .withId(registry.createId("zuul.ErrorStatsData", "ID", name)) .monitorValue(this, NamedCountingMonitor::getCount); } /** * registers this objects */ public NamedCountingMonitor register() { MonitorRegistry.getInstance().registerObject(this); return this; } /** * increments the counter */ public long increment() { return this.count.incrementAndGet(); } @Override public String getName() { return name; } /** * @return the current count */ @Override public long getCount() { return this.count.get(); } }
6,429
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/stats/StatsManager.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.stats; import com.google.common.annotations.VisibleForTesting; import com.netflix.zuul.message.http.HttpRequestInfo; import com.netflix.zuul.stats.monitoring.MonitorRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * High level statistics counter manager to count stats on various aspects of requests * * @author Mikey Cohen * Date: 2/3/12 * Time: 3:25 PM */ public class StatsManager { private static final Logger LOG = LoggerFactory.getLogger(StatsManager.class); protected static final Pattern HEX_PATTERN = Pattern.compile("[0-9a-fA-F]+"); // should match *.amazonaws.com, *.nflxvideo.net, or raw IP addresses. private static final Pattern HOST_PATTERN = Pattern.compile("(?:(.+)\\.amazonaws\\.com)|((?:\\d{1,3}\\.?){4})|(ip-\\d+-\\d+-\\d+-\\d+)|" + "(?:(.+)\\.nflxvideo\\.net)|(?:(.+)\\.llnwd\\.net)|(?:(.+)\\.nflximg\\.com)"); @VisibleForTesting static final String HOST_HEADER = "host"; private static final String X_FORWARDED_FOR_HEADER = "x-forwarded-for"; @VisibleForTesting static final String X_FORWARDED_PROTO_HEADER = "x-forwarded-proto"; @VisibleForTesting final ConcurrentMap<String, ConcurrentHashMap<Integer, RouteStatusCodeMonitor>> routeStatusMap = new ConcurrentHashMap<String, ConcurrentHashMap<Integer, RouteStatusCodeMonitor>>(); private final ConcurrentMap<String, NamedCountingMonitor> namedStatusMap = new ConcurrentHashMap<String, NamedCountingMonitor>(); private final ConcurrentMap<String, NamedCountingMonitor> hostCounterMap = new ConcurrentHashMap<String, NamedCountingMonitor>(); private final ConcurrentMap<String, NamedCountingMonitor> protocolCounterMap = new ConcurrentHashMap<String, NamedCountingMonitor>(); private final ConcurrentMap<String, NamedCountingMonitor> ipVersionCounterMap = new ConcurrentHashMap<String, NamedCountingMonitor>(); protected static StatsManager INSTANCE = new StatsManager(); public static StatsManager getManager() { return INSTANCE; } /** * @param route * @param statusCode * @return the RouteStatusCodeMonitor for the given route and status code */ public RouteStatusCodeMonitor getRouteStatusCodeMonitor(String route, int statusCode) { Map<Integer, RouteStatusCodeMonitor> map = routeStatusMap.get(route); if (map == null) { return null; } return map.get(statusCode); } @VisibleForTesting NamedCountingMonitor getHostMonitor(String host) { return this.hostCounterMap.get(hostKey(host)); } @VisibleForTesting NamedCountingMonitor getProtocolMonitor(String proto) { return this.protocolCounterMap.get(protocolKey(proto)); } @VisibleForTesting static final String hostKey(String host) { try { final Matcher m = HOST_PATTERN.matcher(host); // I know which type of host matched by the number of the group that is non-null // I use a different replacement string per host type to make the Epic stats more clear if (m.matches()) { if (m.group(1) != null) { host = host.replace(m.group(1), "EC2"); } else if (m.group(2) != null) { host = host.replace(m.group(2), "IP"); } else if (m.group(3) != null) { host = host.replace(m.group(3), "IP"); } else if (m.group(4) != null) { host = host.replace(m.group(4), "CDN"); } else if (m.group(5) != null) { host = host.replace(m.group(5), "CDN"); } else if (m.group(6) != null) { host = host.replace(m.group(6), "CDN"); } } } catch (Exception e) { LOG.error(e.getMessage(), e); } finally { return String.format("host_%s", host); } } private static final String protocolKey(String proto) { return String.format("protocol_%s", proto); } /** * Collects counts statistics about the request: client ip address from the x-forwarded-for header; * ipv4 or ipv6 and host name from the host header; * * @param req */ public void collectRequestStats(HttpRequestInfo req) { // ipv4/ipv6 tracking String clientIp; final String xForwardedFor = req.getHeaders().getFirst(X_FORWARDED_FOR_HEADER); if (xForwardedFor == null) { clientIp = req.getClientIp(); } else { clientIp = extractClientIpFromXForwardedFor(xForwardedFor); } final boolean isIPv6 = (clientIp != null) ? isIPv6(clientIp) : false; final String ipVersionKey = isIPv6 ? "ipv6" : "ipv4"; incrementNamedCountingMonitor(ipVersionKey, ipVersionCounterMap); // host header String host = req.getHeaders().getFirst(HOST_HEADER); if (host != null) { int colonIdx; if (isIPv6) { // an ipv6 host might be a raw IP with 7+ colons colonIdx = host.lastIndexOf(":"); } else { // strips port from host colonIdx = host.indexOf(":"); } if (colonIdx > -1) { host = host.substring(0, colonIdx); } incrementNamedCountingMonitor(hostKey(host), this.hostCounterMap); } // http vs. https String protocol = req.getHeaders().getFirst(X_FORWARDED_PROTO_HEADER); if (protocol == null) { protocol = req.getScheme(); } incrementNamedCountingMonitor(protocolKey(protocol), this.protocolCounterMap); } @VisibleForTesting static final boolean isIPv6(String ip) { return ip.split(":").length == 8; } @VisibleForTesting static final String extractClientIpFromXForwardedFor(String xForwardedFor) { return xForwardedFor.split(",")[0]; } /** * helper method to create new monitor, place into map, and register with Epic, if necessary */ protected void incrementNamedCountingMonitor(String name, ConcurrentMap<String, NamedCountingMonitor> map) { NamedCountingMonitor monitor = map.get(name); if (monitor == null) { monitor = new NamedCountingMonitor(name); NamedCountingMonitor conflict = map.putIfAbsent(name, monitor); if (conflict != null) { monitor = conflict; } else { MonitorRegistry.getInstance().registerObject(monitor); } } monitor.increment(); } /** * collects and increments counts of status code, route/status code and statuc_code bucket, eg 2xx 3xx 4xx 5xx * * @param route * @param statusCode */ public void collectRouteStats(String route, int statusCode) { // increments 200, 301, 401, 503, etc. status counters final String preciseStatusString = String.format("status_%d", statusCode); NamedCountingMonitor preciseStatus = namedStatusMap.get(preciseStatusString); if (preciseStatus == null) { preciseStatus = new NamedCountingMonitor(preciseStatusString); NamedCountingMonitor found = namedStatusMap.putIfAbsent(preciseStatusString, preciseStatus); if (found != null) { preciseStatus = found; } else { MonitorRegistry.getInstance().registerObject(preciseStatus); } } preciseStatus.increment(); // increments 2xx, 3xx, 4xx, 5xx status counters final String summaryStatusString = String.format("status_%dxx", statusCode / 100); NamedCountingMonitor summaryStatus = namedStatusMap.get(summaryStatusString); if (summaryStatus == null) { summaryStatus = new NamedCountingMonitor(summaryStatusString); NamedCountingMonitor found = namedStatusMap.putIfAbsent(summaryStatusString, summaryStatus); if (found != null) { summaryStatus = found; } else { MonitorRegistry.getInstance().registerObject(summaryStatus); } } summaryStatus.increment(); // increments route and status counter if (route == null) { route = "ROUTE_NOT_FOUND"; } route = route.replace("/", "_"); ConcurrentHashMap<Integer, RouteStatusCodeMonitor> statsMap = routeStatusMap.get(route); if (statsMap == null) { statsMap = new ConcurrentHashMap<Integer, RouteStatusCodeMonitor>(); routeStatusMap.putIfAbsent(route, statsMap); } RouteStatusCodeMonitor sd = statsMap.get(statusCode); if (sd == null) { // don't register only 404 status codes (these are garbage endpoints) if (statusCode == 404) { if (statsMap.size() == 0) { return; } } sd = new RouteStatusCodeMonitor(route, statusCode); RouteStatusCodeMonitor sd1 = statsMap.putIfAbsent(statusCode, sd); if (sd1 != null) { sd = sd1; } else { MonitorRegistry.getInstance().registerObject(sd); } } sd.update(); } }
6,430
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/stats/RouteStatusCodeMonitor.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.stats; import com.google.common.annotations.VisibleForTesting; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Spectator; import com.netflix.spectator.api.patterns.PolledMeter; import com.netflix.zuul.stats.monitoring.NamedCount; import javax.annotation.Nullable; import java.util.Objects; import java.util.concurrent.atomic.AtomicLong; /** * counter for per route/status code counting * @author Mikey Cohen * Date: 2/3/12 * Time: 3:04 PM */ public class RouteStatusCodeMonitor implements NamedCount { private final String routeCode; @VisibleForTesting final String route; private final int statusCode; private final AtomicLong count = new AtomicLong(); public RouteStatusCodeMonitor(@Nullable String route, int statusCode) { if (route == null) { route = ""; } this.route = route; this.statusCode = statusCode; this.routeCode = route + "_" + statusCode; Registry registry = Spectator.globalRegistry(); PolledMeter.using(registry) .withId(registry.createId("zuul.RouteStatusCodeMonitor", "ID", routeCode)) .monitorValue(this, RouteStatusCodeMonitor::getCount); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RouteStatusCodeMonitor statsData = (RouteStatusCodeMonitor) o; if (statusCode != statsData.statusCode) { return false; } if (!Objects.equals(route, statsData.route)) { return false; } return true; } @Override public int hashCode() { int result = route != null ? route.hashCode() : 0; result = 31 * result + statusCode; return result; } @Override public String getName() { return routeCode; } @Override public long getCount() { return count.get(); } /** * increment the count */ public void update() { count.incrementAndGet(); } }
6,431
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/stats/ErrorStatsData.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.stats; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Spectator; import com.netflix.spectator.api.patterns.PolledMeter; import com.netflix.zuul.stats.monitoring.NamedCount; import java.util.concurrent.atomic.AtomicLong; /** * Implementation of a Named counter to monitor and count error causes by route. Route is a defined zuul concept to * categorize requests into buckets. By default this is the first segment of the uri * @author Mikey Cohen * Date: 2/23/12 * Time: 4:16 PM */ public class ErrorStatsData implements NamedCount { private final String id; private final String errorCause; private final AtomicLong count = new AtomicLong(); /** * create a counter by route and cause of error * @param route * @param cause */ public ErrorStatsData(String route, String cause) { if (null == route || "".equals(route)) { route = "UNKNOWN"; } id = route + "_" + cause; this.errorCause = cause; Registry registry = Spectator.globalRegistry(); PolledMeter.using(registry) .withId(registry.createId("zuul.ErrorStatsData", "ID", id)) .monitorValue(this, ErrorStatsData::getCount); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ErrorStatsData that = (ErrorStatsData) o; return !(errorCause != null ? !errorCause.equals(that.errorCause) : that.errorCause != null); } @Override public int hashCode() { return errorCause != null ? errorCause.hashCode() : 0; } /** * increments the counter */ public void update() { count.incrementAndGet(); } @Override public String getName() { return id; } @Override public long getCount() { return count.get(); } }
6,432
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/stats/AmazonInfoHolder.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.stats; import com.netflix.appinfo.AmazonInfo; /** * Builds and caches an <code>AmazonInfo</code> instance in memory. * * @author mhawthorne */ public class AmazonInfoHolder { private static final AmazonInfo INFO = AmazonInfo.Builder.newBuilder().autoBuild("eureka"); public static final AmazonInfo getInfo() { return INFO; } private AmazonInfoHolder() {} }
6,433
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/stats/ErrorStatsManager.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.stats; import com.netflix.zuul.stats.monitoring.MonitorRegistry; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Manager to handle Error Statistics * @author Mikey Cohen * Date: 2/23/12 * Time: 4:16 PM */ public class ErrorStatsManager { ConcurrentHashMap<String, ConcurrentHashMap<String, ErrorStatsData>> routeMap = new ConcurrentHashMap<String, ConcurrentHashMap<String, ErrorStatsData>>(); static final ErrorStatsManager INSTANCE = new ErrorStatsManager(); /** * * @return Singleton */ public static ErrorStatsManager getManager() { return INSTANCE; } /** * * @param route * @param cause * @return data structure for holding count information for a route and cause */ public ErrorStatsData getStats(String route, String cause) { Map<String, ErrorStatsData> map = routeMap.get(route); if (map == null) { return null; } return map.get(cause); } /** * updates count for the given route and error cause * @param route * @param cause */ public void putStats(String route, String cause) { if (route == null) { route = "UNKNOWN_ROUTE"; } route = route.replace("/", "_"); ConcurrentHashMap<String, ErrorStatsData> statsMap = routeMap.get(route); if (statsMap == null) { statsMap = new ConcurrentHashMap<String, ErrorStatsData>(); routeMap.putIfAbsent(route, statsMap); } ErrorStatsData sd = statsMap.get(cause); if (sd == null) { sd = new ErrorStatsData(route, cause); ErrorStatsData sd1 = statsMap.putIfAbsent(cause, sd); if (sd1 != null) { sd = sd1; } else { MonitorRegistry.getInstance().registerObject(sd); } } sd.update(); } public static class UnitTest {} }
6,434
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/stats/RequestMetricsPublisher.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.stats; import com.netflix.zuul.context.SessionContext; /** * User: michaels@netflix.com * Date: 3/9/15 * Time: 5:56 PM */ public interface RequestMetricsPublisher { void collectAndPublish(SessionContext context); }
6,435
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/stats
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/stats/status/StatusCategory.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.stats.status; /** * Status Category * * Author: Arthur Gonigberg * Date: December 20, 2017 */ public interface StatusCategory { String getId(); StatusCategoryGroup getGroup(); String getReason(); String name(); }
6,436
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/stats
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/stats/status/StatusCategoryGroup.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.stats.status; /** * Status Category Group * * Author: Arthur Gonigberg * Date: December 20, 2017 */ public interface StatusCategoryGroup { int getId(); String name(); }
6,437
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/stats
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/stats/status/ZuulStatusCategory.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.stats.status; /** * Zuul Status Category * * As some of the origin servers won't/can't return correct HTTP status codes in responses, we use set an * StatusCategory attribute to distinguish the main statuses that we care about from Zuul's perspective. * * These status categories are split into 2 groups: * * SUCCESS | FAILURE * * each of which can have a narrower definition, eg: * * FAILURE_THROTTLED * FAILURE_ORIGIN * etc... * * which _should_ also be subdivided with one of: * * ORIGIN * CLIENT * LOCAL */ public enum ZuulStatusCategory implements StatusCategory { SUCCESS(ZuulStatusCategoryGroup.SUCCESS, 1, "Successfully proxied"), SUCCESS_NOT_FOUND( ZuulStatusCategoryGroup.SUCCESS, 3, "Successfully proxied, origin responded with no resource found"), // This is set on for all 404 responses SUCCESS_LOCAL_NOTSET( ZuulStatusCategoryGroup.SUCCESS, 4, "Default status"), // This is set on the SessionContext as the default value. SUCCESS_LOCAL_NO_ROUTE(ZuulStatusCategoryGroup.SUCCESS, 5, "Unable to determine an origin to handle request"), FAILURE_LOCAL(ZuulStatusCategoryGroup.FAILURE, 1, "Failed internally"), FAILURE_LOCAL_THROTTLED_ORIGIN_SERVER_MAXCONN( ZuulStatusCategoryGroup.FAILURE, 7, "Throttled due to reaching max number of connections to origin"), FAILURE_LOCAL_THROTTLED_ORIGIN_CONCURRENCY( ZuulStatusCategoryGroup.FAILURE, 8, "Throttled due to reaching concurrency limit to origin"), FAILURE_LOCAL_IDLE_TIMEOUT(ZuulStatusCategoryGroup.FAILURE, 9, "Idle timeout due to channel inactivity"), FAILURE_CLIENT_BAD_REQUEST(ZuulStatusCategoryGroup.FAILURE, 12, "Invalid request provided"), FAILURE_CLIENT_CANCELLED(ZuulStatusCategoryGroup.FAILURE, 13, "Client abandoned/closed the connection"), FAILURE_CLIENT_PIPELINE_REJECT(ZuulStatusCategoryGroup.FAILURE, 17, "Client rejected due to HTTP Pipelining"), FAILURE_CLIENT_TIMEOUT(ZuulStatusCategoryGroup.FAILURE, 18, "Timeout reading the client request"), FAILURE_ORIGIN(ZuulStatusCategoryGroup.FAILURE, 2, "Origin returned an error status"), FAILURE_ORIGIN_READ_TIMEOUT(ZuulStatusCategoryGroup.FAILURE, 3, "Timeout reading the response from origin"), FAILURE_ORIGIN_CONNECTIVITY(ZuulStatusCategoryGroup.FAILURE, 4, "Connection to origin failed"), FAILURE_ORIGIN_THROTTLED(ZuulStatusCategoryGroup.FAILURE, 6, "Throttled by origin returning 503 status"), FAILURE_ORIGIN_NO_SERVERS(ZuulStatusCategoryGroup.FAILURE, 14, "No UP origin servers available in Discovery"), FAILURE_ORIGIN_RESET_CONNECTION( ZuulStatusCategoryGroup.FAILURE, 15, "Connection reset on an established origin connection"); private final StatusCategoryGroup group; private final String id; private final String reason; ZuulStatusCategory(StatusCategoryGroup group, int index, String reason) { this.group = group; this.id = (group.getId() + "_" + index).intern(); this.reason = reason; } @Override public String getId() { return id; } @Override public StatusCategoryGroup getGroup() { return group; } @Override public String getReason() { return reason; } }
6,438
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/stats
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/stats/status/StatusCategoryUtils.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.stats.status; import com.netflix.zuul.context.CommonContextKeys; import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.message.ZuulMessage; import com.netflix.zuul.message.http.HttpResponseMessage; import javax.annotation.Nullable; /** * User: michaels@netflix.com * Date: 6/9/15 * Time: 2:48 PM */ public class StatusCategoryUtils { public static StatusCategory getStatusCategory(ZuulMessage msg) { return getStatusCategory(msg.getContext()); } @Nullable public static StatusCategory getStatusCategory(SessionContext ctx) { return ctx.get(CommonContextKeys.STATUS_CATEGORY); } @Nullable public static String getStatusCategoryReason(SessionContext ctx) { return ctx.get(CommonContextKeys.STATUS_CATEGORY_REASON); } public static void setStatusCategory(SessionContext ctx, StatusCategory statusCategory) { setStatusCategory(ctx, statusCategory, statusCategory.getReason()); } public static void setStatusCategory(SessionContext ctx, StatusCategory statusCategory, String reason) { ctx.put(CommonContextKeys.STATUS_CATEGORY, statusCategory); ctx.put(CommonContextKeys.STATUS_CATEGORY_REASON, reason); } public static void clearStatusCategory(SessionContext ctx) { ctx.remove(CommonContextKeys.STATUS_CATEGORY); ctx.remove(CommonContextKeys.STATUS_CATEGORY_REASON); } @Nullable public static StatusCategory getOriginStatusCategory(SessionContext ctx) { return ctx.get(CommonContextKeys.ORIGIN_STATUS_CATEGORY); } @Nullable public static String getOriginStatusCategoryReason(SessionContext ctx) { return ctx.get(CommonContextKeys.ORIGIN_STATUS_CATEGORY_REASON); } public static void setOriginStatusCategory(SessionContext ctx, StatusCategory statusCategory) { setOriginStatusCategory(ctx, statusCategory, statusCategory.getReason()); } public static void setOriginStatusCategory(SessionContext ctx, StatusCategory statusCategory, String reason) { ctx.put(CommonContextKeys.ORIGIN_STATUS_CATEGORY, statusCategory); ctx.put(CommonContextKeys.ORIGIN_STATUS_CATEGORY_REASON, reason); } public static void clearOriginStatusCategory(SessionContext ctx) { ctx.remove(CommonContextKeys.ORIGIN_STATUS_CATEGORY); ctx.remove(CommonContextKeys.ORIGIN_STATUS_CATEGORY_REASON); } public static boolean isResponseHttpErrorStatus(HttpResponseMessage response) { boolean isHttpError = false; if (response != null) { int status = response.getStatus(); isHttpError = isResponseHttpErrorStatus(status); } return isHttpError; } public static boolean isResponseHttpErrorStatus(int status) { return (status < 100 || status >= 500); } public static void storeStatusCategoryIfNotAlreadyFailure( final SessionContext context, final StatusCategory statusCategory) { if (statusCategory != null) { final StatusCategory nfs = getStatusCategory(context); if (nfs == null || nfs.getGroup().getId() == ZuulStatusCategoryGroup.SUCCESS.getId()) { setStatusCategory(context, statusCategory); } } } }
6,439
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/stats
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/stats/status/ZuulStatusCategoryGroup.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.stats.status; /** * Zuul Status Category Group * * Author: Arthur Gonigberg * Date: December 20, 2017 */ public enum ZuulStatusCategoryGroup implements StatusCategoryGroup { SUCCESS(1), FAILURE(2); private final int id; ZuulStatusCategoryGroup(int id) { this.id = id; } @Override public int getId() { return id; } }
6,440
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/stats
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/stats/monitoring/MonitorRegistry.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.stats.monitoring; /** * Registry to register a Counter. a Monitor publisher should be set to get counter information. * If it isn't set, registration will be ignored. * @author Mikey Cohen * Date: 3/18/13 * Time: 4:24 PM */ public class MonitorRegistry { private static final MonitorRegistry instance = new MonitorRegistry(); private Monitor publisher; /** * A Monitor implementation should be set here * @param publisher */ public void setPublisher(Monitor publisher) { this.publisher = publisher; } public static MonitorRegistry getInstance() { return instance; } public void registerObject(NamedCount monitorObj) { if (publisher != null) { publisher.register(monitorObj); } } }
6,441
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/stats
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/stats/monitoring/Monitor.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.stats.monitoring; /** * Interface to register a counter to monitor * @author Mikey Cohen * Date: 3/18/13 * Time: 4:33 PM */ public interface Monitor { /** * Implement this to add this Counter to a Registry * @param monitorObj */ void register(NamedCount monitorObj); }
6,442
0
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/stats
Create_ds/zuul/zuul-core/src/main/java/com/netflix/zuul/stats/monitoring/NamedCount.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.stats.monitoring; /** * Interface for a named counter * @author Mikey Cohen * Date: 3/18/13 * Time: 4:33 PM */ public interface NamedCount { String getName(); long getCount(); }
6,443
0
Create_ds/zuul/zuul-core/src/jmh/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/jmh/java/com/netflix/zuul/message/HeadersBenchmark.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.message; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import java.util.List; import java.util.UUID; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; @State(Scope.Thread) public class HeadersBenchmark { @State(Scope.Thread) public static class AddHeaders { @Param({"0", "1", "5", "10", "30"}) public int count; @Param({"10"}) public int nameLength; private String[] stringNames; private HeaderName[] names; private String[] values; @Setup public void setUp() { stringNames = new String[count]; names = new HeaderName[stringNames.length]; values = new String[stringNames.length]; for (int i = 0; i < stringNames.length; i++) { UUID uuid = new UUID( ThreadLocalRandom.current().nextLong(), ThreadLocalRandom.current().nextLong()); String name = uuid.toString(); assert name.length() >= nameLength; name = name.substring(0, nameLength); names[i] = new HeaderName(name); stringNames[i] = name; values[i] = name; } } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Headers addHeaders_string() { Headers headers = new Headers(); for (int i = 0; i < count; i++) { headers.add(stringNames[i], values[i]); } return headers; } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Headers addHeaders_headerName() { Headers headers = new Headers(); for (int i = 0; i < count; i++) { headers.add(names[i], values[i]); } return headers; } } @State(Scope.Thread) public static class GetSetHeaders { @Param({"1", "5", "10", "30"}) public int count; @Param({"10"}) public int nameLength; private String[] stringNames; private HeaderName[] names; private String[] values; Headers headers; @Setup public void setUp() { headers = new Headers(); stringNames = new String[count]; names = new HeaderName[stringNames.length]; values = new String[stringNames.length]; for (int i = 0; i < stringNames.length; i++) { UUID uuid = new UUID( ThreadLocalRandom.current().nextLong(), ThreadLocalRandom.current().nextLong()); String name = uuid.toString(); assert name.length() >= nameLength; name = name.substring(0, nameLength); names[i] = new HeaderName(name); stringNames[i] = name; values[i] = name; headers.add(names[i], values[i]); } } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void setHeader_first() { headers.set(names[0], "blah"); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void setHeader_last() { headers.set(names[count - 1], "blah"); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public List<String> getHeader_first() { return headers.getAll(names[0]); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public List<String> getHeader_last() { return headers.getAll(names[count - 1]); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void entries(Blackhole blackhole) { for (Header header : headers.entries()) { blackhole.consume(header); } } } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Headers newHeaders() { return new Headers(); } }
6,444
0
Create_ds/zuul/zuul-guice/src/test/java/com/netflix
Create_ds/zuul/zuul-guice/src/test/java/com/netflix/zuul/BaseInjectionIntegTest.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; import com.google.inject.Guice; import com.google.inject.Injector; import com.netflix.zuul.init.InitTestModule; import com.netflix.zuul.init.ZuulFiltersModule; import org.junit.jupiter.api.BeforeEach; /** * Base Injection Integration Test * * This test should be extended for integration tests requiring Guice injection. * * @author Arthur Gonigberg * @since February 22, 2021 */ public abstract class BaseInjectionIntegTest { protected Injector injector = Guice.createInjector(new InitTestModule(), new ZuulFiltersModule()); @BeforeEach void setup() { injector.injectMembers(this); } }
6,445
0
Create_ds/zuul/zuul-guice/src/test/java/com/netflix/zuul
Create_ds/zuul/zuul-guice/src/test/java/com/netflix/zuul/init/ZuulFiltersModuleTest.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.init; import com.netflix.zuul.init2.TestZuulFilter2; import org.apache.commons.configuration.AbstractConfiguration; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; @ExtendWith(MockitoExtension.class) class ZuulFiltersModuleTest { @Mock AbstractConfiguration configuration; private final ZuulFiltersModule module = new ZuulFiltersModule(); @Test void testDefaultFilterLocations() { Mockito.when(configuration.getStringArray("zuul.filters.locations")) .thenReturn("inbound,outbound,endpoint".split(",")); String[] filterLocations = module.findFilterLocations(configuration); assertThat(filterLocations.length, equalTo(3)); assertThat(filterLocations[1], equalTo("outbound")); } @Test void testEmptyFilterLocations() { Mockito.when(configuration.getStringArray("zuul.filters.locations")).thenReturn(new String[0]); String[] filterLocations = module.findFilterLocations(configuration); assertThat(filterLocations.length, equalTo(0)); } @Test void testEmptyClassNames() { Mockito.when(configuration.getStringArray("zuul.filters.classes")).thenReturn(new String[] {}); Mockito.when(configuration.getStringArray("zuul.filters.packages")).thenReturn(new String[] {}); String[] classNames = module.findClassNames(configuration); assertThat(classNames.length, equalTo(0)); } @Test void testClassNamesOnly() { Class<?> expectedClass = TestZuulFilter.class; Mockito.when(configuration.getStringArray("zuul.filters.classes")) .thenReturn(new String[] {"com.netflix.zuul.init.TestZuulFilter"}); Mockito.when(configuration.getStringArray("zuul.filters.packages")).thenReturn(new String[] {}); String[] classNames = module.findClassNames(configuration); assertThat(classNames.length, equalTo(1)); assertThat(classNames[0], equalTo(expectedClass.getCanonicalName())); } @Test void testClassNamesPackagesOnly() { Class<?> expectedClass = TestZuulFilter.class; Mockito.when(configuration.getStringArray("zuul.filters.classes")).thenReturn(new String[] {}); Mockito.when(configuration.getStringArray("zuul.filters.packages")) .thenReturn(new String[] {"com.netflix.zuul.init"}); String[] classNames = module.findClassNames(configuration); assertThat(classNames.length, equalTo(1)); assertThat(classNames[0], equalTo(expectedClass.getCanonicalName())); } @Test void testMultiClasses() { Class<?> expectedClass1 = TestZuulFilter.class; Class<?> expectedClass2 = TestZuulFilter2.class; Mockito.when(configuration.getStringArray("zuul.filters.classes")).thenReturn(new String[] { "com.netflix.zuul.init.TestZuulFilter", "com.netflix.zuul.init2.TestZuulFilter2" }); Mockito.when(configuration.getStringArray("zuul.filters.packages")).thenReturn(new String[0]); String[] classNames = module.findClassNames(configuration); assertThat(classNames.length, equalTo(2)); assertThat(classNames[0], equalTo(expectedClass1.getCanonicalName())); assertThat(classNames[1], equalTo(expectedClass2.getCanonicalName())); } @Test void testMultiPackages() { Class<?> expectedClass1 = TestZuulFilter.class; Class<?> expectedClass2 = TestZuulFilter2.class; Mockito.when(configuration.getStringArray("zuul.filters.classes")).thenReturn(new String[0]); Mockito.when(configuration.getStringArray("zuul.filters.packages")) .thenReturn(new String[] {"com.netflix.zuul.init", "com.netflix.zuul.init2"}); String[] classNames = module.findClassNames(configuration); assertThat(classNames.length, equalTo(2)); assertThat(classNames[0], equalTo(expectedClass1.getCanonicalName())); assertThat(classNames[1], equalTo(expectedClass2.getCanonicalName())); } }
6,446
0
Create_ds/zuul/zuul-guice/src/test/java/com/netflix/zuul
Create_ds/zuul/zuul-guice/src/test/java/com/netflix/zuul/init/InitTestModule.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.init; import com.google.inject.AbstractModule; import com.netflix.config.ConfigurationManager; import com.netflix.spectator.api.NoopRegistry; import com.netflix.spectator.api.Registry; import org.apache.commons.configuration.AbstractConfiguration; import java.io.FilenameFilter; public class InitTestModule extends AbstractModule { @Override protected void configure() { bind(AbstractConfiguration.class).toInstance(ConfigurationManager.getConfigInstance()); bind(FilenameFilter.class).toInstance((dir, name) -> false); bind(Registry.class).to(NoopRegistry.class); } }
6,447
0
Create_ds/zuul/zuul-guice/src/test/java/com/netflix/zuul
Create_ds/zuul/zuul-guice/src/test/java/com/netflix/zuul/init/ZuulFiltersModuleIntegTest.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.init; import com.netflix.config.ConfigurationManager; import com.netflix.zuul.BaseInjectionIntegTest; import com.netflix.zuul.FilterFileManager.FilterFileManagerConfig; import org.apache.commons.configuration.AbstractConfiguration; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import javax.inject.Inject; import static org.junit.jupiter.api.Assertions.assertEquals; class ZuulFiltersModuleIntegTest extends BaseInjectionIntegTest { @Inject private FilterFileManagerConfig filterFileManagerConfig; @BeforeAll static void before() { AbstractConfiguration configuration = ConfigurationManager.getConfigInstance(); configuration.setProperty("zuul.filters.locations", "inbound,outbound,endpoint"); configuration.setProperty("zuul.filters.packages", "com.netflix.zuul.init,com.netflix.zuul.init2"); } @Test void scanningWorks() { String[] filterLocations = filterFileManagerConfig.getDirectories(); String[] classNames = filterFileManagerConfig.getClassNames(); assertEquals(3, filterLocations.length); assertEquals("outbound", filterLocations[1]); assertEquals(2, classNames.length); assertEquals("com.netflix.zuul.init.TestZuulFilter", classNames[0]); assertEquals("com.netflix.zuul.init2.TestZuulFilter2", classNames[1]); } }
6,448
0
Create_ds/zuul/zuul-guice/src/test/java/com/netflix/zuul
Create_ds/zuul/zuul-guice/src/test/java/com/netflix/zuul/init/TestZuulFilter.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.init; import com.netflix.zuul.filters.BaseSyncFilter; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.message.ZuulMessage; public class TestZuulFilter extends BaseSyncFilter { @Override public FilterType filterType() { return FilterType.INBOUND; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter(ZuulMessage msg) { return false; } @Override public ZuulMessage apply(ZuulMessage msg) { return null; } }
6,449
0
Create_ds/zuul/zuul-guice/src/test/java/com/netflix/zuul
Create_ds/zuul/zuul-guice/src/test/java/com/netflix/zuul/guice/TestGuiceFieldFilter.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.guice; import com.google.inject.Injector; import com.netflix.zuul.filters.BaseSyncFilter; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.message.ZuulMessage; import javax.inject.Inject; public class TestGuiceFieldFilter extends BaseSyncFilter { @Inject Injector injector; @Override public FilterType filterType() { return FilterType.INBOUND; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter(ZuulMessage msg) { return false; } @Override public ZuulMessage apply(ZuulMessage msg) { return null; } }
6,450
0
Create_ds/zuul/zuul-guice/src/test/java/com/netflix/zuul
Create_ds/zuul/zuul-guice/src/test/java/com/netflix/zuul/guice/TestGuiceConstructorFilter.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.guice; import com.google.inject.Injector; import com.netflix.zuul.filters.BaseSyncFilter; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.message.ZuulMessage; import javax.inject.Inject; public class TestGuiceConstructorFilter extends BaseSyncFilter { final Injector injector; @Inject public TestGuiceConstructorFilter(Injector injector) { this.injector = injector; } @Override public FilterType filterType() { return FilterType.INBOUND; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter(ZuulMessage msg) { return false; } @Override public ZuulMessage apply(ZuulMessage msg) { return null; } }
6,451
0
Create_ds/zuul/zuul-guice/src/test/java/com/netflix/zuul
Create_ds/zuul/zuul-guice/src/test/java/com/netflix/zuul/guice/GuiceFilterFactoryIntegTest.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.guice; import com.google.inject.Inject; import com.netflix.zuul.BaseInjectionIntegTest; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertNotNull; class GuiceFilterFactoryIntegTest extends BaseInjectionIntegTest { @Inject private GuiceFilterFactory filterFactory; @Test void ctorInjection() throws Exception { TestGuiceConstructorFilter filter = (TestGuiceConstructorFilter) filterFactory.newInstance(TestGuiceConstructorFilter.class); assertNotNull(filter.injector); } @Test void fieldInjection() throws Exception { TestGuiceFieldFilter filter = (TestGuiceFieldFilter) filterFactory.newInstance(TestGuiceFieldFilter.class); assertNotNull(filter.injector); } }
6,452
0
Create_ds/zuul/zuul-guice/src/test/java/com/netflix/zuul
Create_ds/zuul/zuul-guice/src/test/java/com/netflix/zuul/init2/TestZuulFilter2.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.init2; import com.netflix.zuul.filters.BaseSyncFilter; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.message.ZuulMessage; public class TestZuulFilter2 extends BaseSyncFilter { @Override public FilterType filterType() { return FilterType.INBOUND; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter(ZuulMessage msg) { return false; } @Override public ZuulMessage apply(ZuulMessage msg) { return null; } }
6,453
0
Create_ds/zuul/zuul-guice/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-guice/src/main/java/com/netflix/zuul/init/ZuulFiltersModule.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.init; import com.google.common.annotations.VisibleForTesting; import com.google.common.reflect.ClassPath; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.netflix.zuul.BasicFilterUsageNotifier; import com.netflix.zuul.FilterFactory; import com.netflix.zuul.FilterFileManager.FilterFileManagerConfig; import com.netflix.zuul.FilterUsageNotifier; import com.netflix.zuul.filters.ZuulFilter; import com.netflix.zuul.guice.GuiceFilterFactory; import org.apache.commons.configuration.AbstractConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FilenameFilter; import java.io.IOException; import java.util.Arrays; import java.util.function.Predicate; import java.util.stream.Stream; /** * User: michaels@netflix.com * Date: 5/8/15 * Time: 6:15 PM */ public class ZuulFiltersModule extends AbstractModule { private static final Logger LOG = LoggerFactory.getLogger(ZuulFiltersModule.class); private static Predicate<String> blank = String::isEmpty; @Override protected void configure() { LOG.info("Starting Groovy Filter file manager"); bind(FilterFactory.class).to(GuiceFilterFactory.class); bind(FilterUsageNotifier.class).to(BasicFilterUsageNotifier.class); LOG.info("Groovy Filter file manager started"); } @Provides FilterFileManagerConfig provideFilterFileManagerConfig( AbstractConfiguration config, FilenameFilter filenameFilter) { // Get filter directories. String[] filterLocations = findFilterLocations(config); String[] filterClassNames = findClassNames(config); // Init the FilterStore. FilterFileManagerConfig filterConfig = new FilterFileManagerConfig(filterLocations, filterClassNames, 5, filenameFilter); return filterConfig; } // Get compiled filter classes to be found on classpath. @VisibleForTesting String[] findClassNames(AbstractConfiguration config) { // Find individually-specified filter classes. String[] filterClassNamesStrArray = config.getStringArray("zuul.filters.classes"); Stream<String> classNameStream = Arrays.stream(filterClassNamesStrArray).map(String::trim).filter(blank.negate()); // Find filter classes in specified packages. String[] packageNamesStrArray = config.getStringArray("zuul.filters.packages"); ClassPath cp; try { cp = ClassPath.from(this.getClass().getClassLoader()); } catch (IOException e) { throw new RuntimeException("Error attempting to read classpath to find filters!", e); } Stream<String> packageStream = Arrays.stream(packageNamesStrArray) .map(String::trim) .filter(blank.negate()) .flatMap(packageName -> cp.getTopLevelClasses(packageName).stream()) .map(ClassPath.ClassInfo::load) .filter(ZuulFilter.class::isAssignableFrom) .map(Class::getCanonicalName); String[] filterClassNames = Stream.concat(classNameStream, packageStream).toArray(String[]::new); if (filterClassNames.length != 0) { LOG.info("Using filter classnames: "); for (String location : filterClassNames) { LOG.info(" {}", location); } } return filterClassNames; } @VisibleForTesting String[] findFilterLocations(AbstractConfiguration config) { String[] locations = config.getStringArray("zuul.filters.locations"); if (locations == null) { locations = new String[] {"inbound", "outbound", "endpoint"}; } String[] filterLocations = Arrays.stream(locations) .map(String::trim) .filter(blank.negate()) .toArray(String[]::new); if (filterLocations.length != 0) { LOG.info("Using filter locations: "); for (String location : filterLocations) { LOG.info(" {}", location); } } return filterLocations; } }
6,454
0
Create_ds/zuul/zuul-guice/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-guice/src/main/java/com/netflix/zuul/guice/GuiceFilterFactory.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.guice; import com.google.inject.Injector; import com.netflix.zuul.FilterFactory; import com.netflix.zuul.filters.ZuulFilter; import javax.inject.Inject; import javax.inject.Singleton; @Singleton public class GuiceFilterFactory implements FilterFactory { private final Injector injector; @Inject public GuiceFilterFactory(Injector injector) { this.injector = injector; } @Override public ZuulFilter<?, ?> newInstance(Class<?> clazz) throws Exception { return injector.getInstance(clazz.asSubclass(ZuulFilter.class)); } }
6,455
0
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/netty/common
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/netty/common/metrics/CustomLeakDetector.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.netty.common.metrics; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.assertTrue; public class CustomLeakDetector extends InstrumentedResourceLeakDetector { private static final List<CustomLeakDetector> GLOBAL_REGISTRY = new CopyOnWriteArrayList<>(); public static void assertZeroLeaks() { List<CustomLeakDetector> leaks = GLOBAL_REGISTRY.stream() .filter(detector -> detector.leakCounter.get() > 0) .collect(Collectors.toList()); assertTrue(leaks.isEmpty(), "LEAKS DETECTED: " + leaks); } private final String resourceTypeName; public CustomLeakDetector(Class<?> resourceType, int samplingInterval) { super(resourceType, samplingInterval); this.resourceTypeName = resourceType.getSimpleName(); GLOBAL_REGISTRY.add(this); } public CustomLeakDetector(Class<?> resourceType, int samplingInterval, long maxActive) { this(resourceType, samplingInterval); } @Override public String toString() { return "CustomLeakDetector: " + this.resourceTypeName + " leakCount=" + leakCounter.get(); } }
6,456
0
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration/IntegrationTest.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.integration; import com.aayushatharva.brotli4j.decoder.DecoderJNI; import com.aayushatharva.brotli4j.decoder.DirectDecompress; import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.common.Slf4jNotifier; import com.github.tomakehurst.wiremock.core.Options; import com.github.tomakehurst.wiremock.http.Fault; import com.github.tomakehurst.wiremock.junit5.WireMockExtension; import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; import com.google.common.collect.ImmutableSet; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.config.ConfigurationManager; import com.netflix.netty.common.metrics.CustomLeakDetector; import com.netflix.zuul.integration.server.Bootstrap; import com.netflix.zuul.integration.server.HeaderNames; import com.netflix.zuul.integration.server.TestUtil; import io.netty.channel.epoll.Epoll; import io.netty.handler.codec.compression.Brotli; import io.netty.incubator.channel.uring.IOUring; import io.netty.util.ResourceLeakDetector; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.Protocol; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import org.apache.commons.configuration.AbstractConfiguration; import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledOnOs; import org.junit.jupiter.api.condition.OS; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.ServerSocket; import java.net.URL; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.stream.Stream; import java.util.zip.GZIPInputStream; import java.util.zip.Inflater; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.anyRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.ok; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; class IntegrationTest { static { System.setProperty("io.netty.customResourceLeakDetector", CustomLeakDetector.class.getCanonicalName()); } private static Bootstrap bootstrap; private static final int ZUUL_SERVER_PORT = findAvailableTcpPort(); private static final Duration CLIENT_READ_TIMEOUT = Duration.ofMillis(3000); private static final Duration ORIGIN_READ_TIMEOUT = Duration.ofMillis(1000); private final String zuulBaseUri = "http://localhost:" + ZUUL_SERVER_PORT; private String pathSegment; private WireMockRuntimeInfo wmRuntimeInfo; private WireMock wireMock; @RegisterExtension static WireMockExtension wireMockExtension = WireMockExtension.newInstance() .configureStaticDsl(true) .options(wireMockConfig() .maxLoggedResponseSize(1000) .dynamicPort() .useChunkedTransferEncoding(Options.ChunkedEncodingPolicy.ALWAYS) .notifier(new Slf4jNotifier(true))) .build(); @BeforeAll static void beforeAll() { System.out.println("Epoll.isAvailable: " + Epoll.isAvailable()); System.out.println("IOUring.isAvailable: " + IOUring.isAvailable()); assertTrue(ResourceLeakDetector.isEnabled()); assertEquals(ResourceLeakDetector.Level.PARANOID, ResourceLeakDetector.getLevel()); final int wireMockPort = wireMockExtension.getPort(); AbstractConfiguration config = ConfigurationManager.getConfigInstance(); config.setProperty("zuul.server.netty.socket.force_nio", "true"); config.setProperty("zuul.server.port.main", ZUUL_SERVER_PORT); config.setProperty("api.ribbon.listOfServers", "127.0.0.1:" + wireMockPort); config.setProperty("api.ribbon." + CommonClientConfigKey.ReadTimeout.key(), ORIGIN_READ_TIMEOUT.toMillis()); bootstrap = new Bootstrap(); bootstrap.start(); assertTrue(bootstrap.isRunning()); CustomLeakDetector.assertZeroLeaks(); } @AfterAll static void afterAll() { if (bootstrap != null) { bootstrap.stop(); } CustomLeakDetector.assertZeroLeaks(); } @BeforeEach void beforeEachTest() { this.pathSegment = randomPathSegment(); this.wmRuntimeInfo = wireMockExtension.getRuntimeInfo(); this.wireMock = wireMockExtension.getRuntimeInfo().getWireMock(); } private static OkHttpClient setupOkHttpClient(final Protocol... protocols) { return new OkHttpClient.Builder() .connectTimeout(30, TimeUnit.MILLISECONDS) .readTimeout(CLIENT_READ_TIMEOUT) .followRedirects(false) .followSslRedirects(false) .retryOnConnectionFailure(false) .protocols(Arrays.asList(protocols)) .build(); } private Request.Builder setupRequestBuilder( final boolean requestBodyBuffering, final boolean responseBodyBuffering) { final HttpUrl url = new HttpUrl.Builder() .scheme("http") .host("localhost") .port(ZUUL_SERVER_PORT) .addPathSegment(pathSegment) .addQueryParameter("bufferRequestBody", "" + requestBodyBuffering) .addQueryParameter("bufferResponseBody", "" + responseBodyBuffering) .build(); return new Request.Builder().url(url); } static Stream<Arguments> arguments() { List<Arguments> list = new ArrayList<Arguments>(); for (Protocol protocol : ImmutableSet.of(Protocol.HTTP_1_1)) { for (boolean requestBodyBuffering : ImmutableSet.of(Boolean.TRUE, Boolean.FALSE)) { for (boolean responseBodyBuffering : ImmutableSet.of(Boolean.TRUE, Boolean.FALSE)) { list.add(Arguments.of( protocol.name(), setupOkHttpClient(protocol), requestBodyBuffering, responseBodyBuffering)); } } } return list.stream(); } @ParameterizedTest @MethodSource("arguments") void httpGetHappyPath( final String description, final OkHttpClient okHttp, final boolean requestBodyBuffering, final boolean responseBodyBuffering) throws Exception { wireMock.register(get(anyUrl()).willReturn(ok().withBody("hello world"))); Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering) .get() .build(); Response response = okHttp.newCall(request).execute(); assertThat(response.code()).isEqualTo(200); assertThat(response.body().string()).isEqualTo("hello world"); verifyResponseHeaders(response); } @ParameterizedTest @MethodSource("arguments") void httpPostHappyPath( final String description, final OkHttpClient okHttp, final boolean requestBodyBuffering, final boolean responseBodyBuffering) throws Exception { wireMock.register(post(anyUrl()).willReturn(ok().withBody("Thank you next"))); Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering) .post(RequestBody.create("Simple POST request body".getBytes(StandardCharsets.UTF_8))) .build(); Response response = okHttp.newCall(request).execute(); assertThat(response.code()).isEqualTo(200); assertThat(response.body().string()).isEqualTo("Thank you next"); verifyResponseHeaders(response); } @ParameterizedTest @MethodSource("arguments") void httpPostWithInvalidHostHeader( final String description, final OkHttpClient okHttp, final boolean requestBodyBuffering, final boolean responseBodyBuffering) throws Exception { wireMock.register(post(anyUrl()).willReturn(ok().withBody("Thank you next"))); Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering) .addHeader("Host", "_invalid_hostname_") .post(RequestBody.create("Simple POST request body".getBytes(StandardCharsets.UTF_8))) .build(); Response response = okHttp.newCall(request).execute(); assertThat(response.code()).isEqualTo(500); verify(0, anyRequestedFor(anyUrl())); } @ParameterizedTest @MethodSource("arguments") void httpGetFailsDueToOriginReadTimeout( final String description, final OkHttpClient okHttp, final boolean requestBodyBuffering, final boolean responseBodyBuffering) throws Exception { wireMock.register(get(anyUrl()) .willReturn(ok().withFixedDelay((int) ORIGIN_READ_TIMEOUT.toMillis() + 50) .withBody("Slow poke"))); Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering) .get() .build(); Response response = okHttp.newCall(request).execute(); assertThat(response.code()).isEqualTo(504); assertThat(response.body().string()).isEqualTo(""); verifyResponseHeaders(response); } @ParameterizedTest @MethodSource("arguments") void httpGetFailsDueToMalformedResponseChunk( final String description, final OkHttpClient okHttp, final boolean requestBodyBuffering, final boolean responseBodyBuffering) throws Exception { wireMock.register(get(anyUrl()).willReturn(aResponse().withFault(Fault.MALFORMED_RESPONSE_CHUNK))); Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering) .get() .build(); Response response = okHttp.newCall(request).execute(); final int expectedStatusCode = (responseBodyBuffering) ? 504 : 200; assertThat(response.code()).isEqualTo(expectedStatusCode); response.close(); } @ParameterizedTest @MethodSource("arguments") void zuulWillRetryHttpGetWhenOriginReturns500( final String description, final OkHttpClient okHttp, final boolean requestBodyBuffering, final boolean responseBodyBuffering) throws Exception { wireMock.register(get(anyUrl()).willReturn(aResponse().withStatus(500))); Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering) .get() .build(); Response response = okHttp.newCall(request).execute(); assertThat(response.code()).isEqualTo(500); assertThat(response.body().string()).isEqualTo(""); verify(2, getRequestedFor(anyUrl())); } @ParameterizedTest @MethodSource("arguments") void zuulWillRetryHttpGetWhenOriginReturns503( final String description, final OkHttpClient okHttp, final boolean requestBodyBuffering, final boolean responseBodyBuffering) throws Exception { wireMock.register(get(anyUrl()).willReturn(aResponse().withStatus(503))); Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering) .get() .build(); Response response = okHttp.newCall(request).execute(); assertThat(response.code()).isEqualTo(503); assertThat(response.body().string()).isEqualTo(""); verify(2, getRequestedFor(anyUrl())); } @ParameterizedTest @MethodSource("arguments") void httpGetReturnsStatus500DueToConnectionResetByPeer( final String description, final OkHttpClient okHttp, final boolean requestBodyBuffering, final boolean responseBodyBuffering) throws Exception { wireMock.register(get(anyUrl()).willReturn(aResponse().withFault(Fault.CONNECTION_RESET_BY_PEER))); Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering) .get() .build(); Response response = okHttp.newCall(request).execute(); assertThat(response.code()).isEqualTo(500); assertThat(response.body().string()).isEqualTo(""); verify(1, getRequestedFor(anyUrl())); } @ParameterizedTest @MethodSource("arguments") void httpGet_ServerChunkedDribbleDelay( final String description, final OkHttpClient okHttp, final boolean requestBodyBuffering, final boolean responseBodyBuffering) throws Exception { wireMock.register(get(anyUrl()) .willReturn(aResponse() .withStatus(200) .withBody("Hello world, is anybody listening?") .withChunkedDribbleDelay(10, (int) CLIENT_READ_TIMEOUT.toMillis() + 500))); Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering) .get() .build(); Response response = okHttp.newCall(request).execute(); final int expectedStatusCode = (responseBodyBuffering) ? 504 : 200; assertThat(response.code()).isEqualTo(expectedStatusCode); response.close(); } @ParameterizedTest @MethodSource("arguments") void blockRequestWithMultipleHostHeaders( final String description, final OkHttpClient okHttp, final boolean requestBodyBuffering, final boolean responseBodyBuffering) throws Exception { wireMock.register(get(anyUrl()).willReturn(aResponse().withStatus(200))); Request request = setupRequestBuilder(requestBodyBuffering, responseBodyBuffering) .get() .addHeader("Host", "aaa.example.com") .addHeader("Host", "aaa.foobar.com") .build(); Response response = okHttp.newCall(request).execute(); assertThat(response.code()).isEqualTo(500); verify(0, anyRequestedFor(anyUrl())); response.close(); } @Test void deflateOnly() throws Exception { final String expectedResponseBody = TestUtil.COMPRESSIBLE_CONTENT; wireMock.register(get(anyUrl()) .willReturn(aResponse() .withStatus(200) .withBody(expectedResponseBody) .withHeader("Content-Type", TestUtil.COMPRESSIBLE_CONTENT_TYPE))); URL url = new URL(zuulBaseUri); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setAllowUserInteraction(false); connection.setRequestProperty("Accept-Encoding", "deflate"); InputStream inputStream = connection.getInputStream(); assertEquals(200, connection.getResponseCode()); assertEquals("text/plain", connection.getHeaderField("Content-Type")); assertEquals("deflate", connection.getHeaderField("Content-Encoding")); byte[] compressedData = IOUtils.toByteArray(inputStream); Inflater inflater = new Inflater(); inflater.setInput(compressedData); byte[] result = new byte[1000]; int nBytes = inflater.inflate(result); String text = new String(result, 0, nBytes, TestUtil.CHARSET); assertEquals(expectedResponseBody, text); inputStream.close(); connection.disconnect(); } @Test void gzipOnly() throws Exception { final String expectedResponseBody = TestUtil.COMPRESSIBLE_CONTENT; wireMock.register(get(anyUrl()) .willReturn(aResponse() .withStatus(200) .withBody(expectedResponseBody) .withHeader("Content-Type", TestUtil.COMPRESSIBLE_CONTENT_TYPE))); URL url = new URL(zuulBaseUri); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setAllowUserInteraction(false); connection.setRequestProperty("Accept-Encoding", "gzip"); InputStream inputStream = connection.getInputStream(); assertEquals(200, connection.getResponseCode()); assertEquals("text/plain", connection.getHeaderField("Content-Type")); assertEquals("gzip", connection.getHeaderField("Content-Encoding")); GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream); byte[] data = IOUtils.toByteArray(gzipInputStream); String text = new String(data, TestUtil.CHARSET); assertEquals(expectedResponseBody, text); inputStream.close(); gzipInputStream.close(); connection.disconnect(); } @Test void brotliOnly() throws Throwable { Brotli.ensureAvailability(); final String expectedResponseBody = TestUtil.COMPRESSIBLE_CONTENT; wireMock.register(get(anyUrl()) .willReturn(aResponse() .withStatus(200) .withBody(expectedResponseBody) .withHeader("Content-Type", TestUtil.COMPRESSIBLE_CONTENT_TYPE))); URL url = new URL(zuulBaseUri); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setAllowUserInteraction(false); connection.setRequestProperty("Accept-Encoding", "br"); InputStream inputStream = connection.getInputStream(); assertEquals(200, connection.getResponseCode()); assertEquals("text/plain", connection.getHeaderField("Content-Type")); assertEquals("br", connection.getHeaderField("Content-Encoding")); byte[] compressedData = IOUtils.toByteArray(inputStream); assertTrue(compressedData.length > 0); DirectDecompress decompressResult = DirectDecompress.decompress(compressedData); assertEquals(DecoderJNI.Status.DONE, decompressResult.getResultStatus()); assertEquals( "Hello Hello Hello Hello Hello", new String(decompressResult.getDecompressedData(), TestUtil.CHARSET)); inputStream.close(); connection.disconnect(); } @Test void noCompression() throws Exception { final String expectedResponseBody = TestUtil.COMPRESSIBLE_CONTENT; wireMock.register(get(anyUrl()) .willReturn(aResponse() .withStatus(200) .withBody(expectedResponseBody) .withHeader("Content-Type", TestUtil.COMPRESSIBLE_CONTENT_TYPE))); URL url = new URL(zuulBaseUri); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setAllowUserInteraction(false); connection.setRequestProperty("Accept-Encoding", ""); // no compression InputStream inputStream = connection.getInputStream(); assertEquals(200, connection.getResponseCode()); assertEquals("text/plain", connection.getHeaderField("Content-Type")); assertNull(connection.getHeaderField("Content-Encoding")); byte[] data = IOUtils.toByteArray(inputStream); String text = new String(data, TestUtil.CHARSET); assertEquals(expectedResponseBody, text); inputStream.close(); connection.disconnect(); } @Test void jumboOriginResponseShouldBeChunked() throws Exception { final String expectedResponseBody = TestUtil.JUMBO_RESPONSE_BODY; wireMock.register(get(anyUrl()) .willReturn(aResponse() .withStatus(200) .withBody(expectedResponseBody) .withHeader("Content-Type", TestUtil.COMPRESSIBLE_CONTENT_TYPE))); URL url = new URL(zuulBaseUri); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setAllowUserInteraction(false); connection.setRequestProperty("Accept-Encoding", ""); // no compression InputStream inputStream = connection.getInputStream(); assertEquals(200, connection.getResponseCode()); assertEquals("text/plain", connection.getHeaderField("Content-Type")); assertNull(connection.getHeaderField("Content-Encoding")); assertEquals("chunked", connection.getHeaderField("Transfer-Encoding")); byte[] data = IOUtils.toByteArray(inputStream); String text = new String(data, TestUtil.CHARSET); assertEquals(expectedResponseBody, text); inputStream.close(); connection.disconnect(); } @Test @EnabledOnOs(value = {OS.LINUX}) void epollIsAvailableOnLinux() { if (Epoll.unavailabilityCause() != null) { Epoll.unavailabilityCause().printStackTrace(); } assertThat(Epoll.isAvailable()).isTrue(); } private static String randomPathSegment() { return UUID.randomUUID().toString(); } private static int findAvailableTcpPort() { try (ServerSocket sock = new ServerSocket(0)) { return sock.getLocalPort(); } catch (IOException e) { return -1; } } private static void verifyResponseHeaders(final Response response) { assertThat(response.header(HeaderNames.REQUEST_ID)).startsWith("RQ-"); } }
6,457
0
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/Bootstrap.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.integration.server; import com.google.inject.Guice; import com.google.inject.Injector; import com.netflix.zuul.netty.server.BaseServerStartup; import com.netflix.zuul.netty.server.Server; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.TimeUnit; public class Bootstrap { private static final Logger logger = LoggerFactory.getLogger(Bootstrap.class); private Server server; private int exitCode = 0; public void start() { long startNanos = System.nanoTime(); logger.info("Zuul: starting up."); try { Injector injector = Guice.createInjector(new ServerModule()); BaseServerStartup serverStartup = injector.getInstance(BaseServerStartup.class); server = serverStartup.server(); server.start(); long startupDuration = System.nanoTime() - startNanos; logger.info("Zuul: finished startup. Duration = {}ms", TimeUnit.NANOSECONDS.toMillis(startupDuration)); // server.awaitTermination(); } catch (Throwable t) { exitCode = 1; throw new RuntimeException(t); } } public Server getServer() { return this.server; } public boolean isRunning() { return (server != null) && (server.getListeningAddresses().size() > 0); } public void stop() { if (server != null) { server.stop(); } } }
6,458
0
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/OriginServerList.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.integration.server; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.netflix.loadbalancer.ConfigurationBasedServerList; import com.netflix.loadbalancer.Server; import java.util.List; public class OriginServerList extends ConfigurationBasedServerList { @Override protected List<Server> derive(String value) { List<Server> list = Lists.newArrayList(); if (!Strings.isNullOrEmpty(value)) { for (String s : value.split(",")) { String[] hostAndPort = s.split(":"); String host = hostAndPort[0]; int port = Integer.parseInt(hostAndPort[1]); list.add(TestUtil.makeDiscoveryEnabledServer("", host, port)); } } return list; } }
6,459
0
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/ServerModule.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.integration.server; import com.google.inject.AbstractModule; import com.netflix.config.ConfigurationManager; import com.netflix.discovery.guice.EurekaModule; import com.netflix.netty.common.accesslog.AccessLogPublisher; import com.netflix.netty.common.status.ServerStatusManager; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Registry; import com.netflix.zuul.BasicRequestCompleteHandler; import com.netflix.zuul.FilterLoader; import com.netflix.zuul.RequestCompleteHandler; import com.netflix.zuul.context.SessionContextDecorator; import com.netflix.zuul.context.ZuulSessionContextDecorator; import com.netflix.zuul.filters.FilterRegistry; import com.netflix.zuul.filters.MutableFilterRegistry; import com.netflix.zuul.init.ZuulFiltersModule; import com.netflix.zuul.netty.server.BaseServerStartup; import com.netflix.zuul.netty.server.ClientRequestReceiver; import com.netflix.zuul.origins.BasicNettyOriginManager; import com.netflix.zuul.origins.OriginManager; import com.netflix.zuul.stats.BasicRequestMetricsPublisher; import com.netflix.zuul.stats.RequestMetricsPublisher; import org.apache.commons.configuration.AbstractConfiguration; import java.io.FilenameFilter; public class ServerModule extends AbstractModule { @Override protected void configure() { try { ConfigurationManager.loadCascadedPropertiesFromResources("application"); } catch (Exception ex) { throw new RuntimeException("Error loading configuration: " + ex.getMessage(), ex); } bind(FilenameFilter.class).to(NoFilenameFilter.class); bind(AbstractConfiguration.class).toInstance(ConfigurationManager.getConfigInstance()); install(new EurekaModule()); // sample specific bindings bind(BaseServerStartup.class).to(ServerStartup.class); // use provided basic netty origin manager bind(OriginManager.class).to(BasicNettyOriginManager.class); // zuul filter loading install(new ZuulFiltersModule()); bind(FilterLoader.class).toProvider(FilterLoaderProvider.class); bind(FilterRegistry.class).to(MutableFilterRegistry.class); // general server bindings bind(ServerStatusManager.class); // health/discovery status bind(SessionContextDecorator.class) .to(ZuulSessionContextDecorator.class); // decorate new sessions when requests come in bind(Registry.class).to(DefaultRegistry.class); // atlas metrics registry bind(RequestCompleteHandler.class).to(BasicRequestCompleteHandler.class); // metrics post-request completion bind(RequestMetricsPublisher.class).to(BasicRequestMetricsPublisher.class); // timings publisher // access logger, including request ID generator bind(AccessLogPublisher.class) .toInstance(new AccessLogPublisher( "ACCESS", (channel, httpRequest) -> ClientRequestReceiver.getRequestFromChannel(channel) .getContext() .getUUID())); } }
6,460
0
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/ServerStartup.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.integration.server; import com.netflix.appinfo.ApplicationInfoManager; 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.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.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.BaseServerStartup; import com.netflix.zuul.netty.server.DefaultEventLoopConfig; import com.netflix.zuul.netty.server.DirectMemoryMonitor; import com.netflix.zuul.netty.server.Http1MutualSslChannelInitializer; import com.netflix.zuul.netty.server.NamedSocketAddress; import com.netflix.zuul.netty.server.SocketAddressProperty; import com.netflix.zuul.netty.server.ZuulDependencyKeys; import com.netflix.zuul.netty.server.ZuulServerChannelInitializer; import com.netflix.zuul.netty.server.http2.Http2SslChannelInitializer; import com.netflix.zuul.netty.server.push.PushConnectionRegistry; import com.netflix.zuul.netty.ssl.BaseSslContextFactory; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.group.ChannelGroup; import io.netty.handler.codec.compression.CompressionOptions; import io.netty.handler.codec.http.HttpContentCompressor; import io.netty.handler.ssl.ClientAuth; import javax.inject.Inject; import javax.inject.Singleton; import java.io.File; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Collections; import java.util.HashMap; import java.util.Map; @Singleton public class ServerStartup extends BaseServerStartup { enum ServerType { HTTP, HTTP2, HTTP_MUTUAL_TLS, WEBSOCKET, SSE } private static final String[] WWW_PROTOCOLS = new String[] {"TLSv1.3", "TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3"}; private static final ServerType SERVER_TYPE = ServerType.HTTP; private final PushConnectionRegistry pushConnectionRegistry; // private final SamplePushMessageSenderInitializer pushSenderInitializer; @Inject public ServerStartup( ServerStatusManager serverStatusManager, FilterLoader filterLoader, SessionContextDecorator sessionCtxDecorator, FilterUsageNotifier usageNotifier, RequestCompleteHandler reqCompleteHandler, Registry registry, DirectMemoryMonitor directMemoryMonitor, EventLoopGroupMetrics eventLoopGroupMetrics, EurekaClient discoveryClient, ApplicationInfoManager applicationInfoManager, AccessLogPublisher accessLogPublisher, PushConnectionRegistry pushConnectionRegistry) { super( serverStatusManager, filterLoader, sessionCtxDecorator, usageNotifier, reqCompleteHandler, registry, directMemoryMonitor, eventLoopGroupMetrics, new DefaultEventLoopConfig(), discoveryClient, applicationInfoManager, accessLogPublisher); this.pushConnectionRegistry = pushConnectionRegistry; // this.pushSenderInitializer = pushSenderInitializer; } @Override protected Map<NamedSocketAddress, ChannelInitializer<?>> chooseAddrsAndChannels(ChannelGroup clientChannels) { Map<NamedSocketAddress, ChannelInitializer<?>> addrsToChannels = new HashMap<>(); SocketAddress sockAddr; String metricId; { @Deprecated int port = new DynamicIntProperty("zuul.server.port.main", 7001).get(); sockAddr = new SocketAddressProperty("zuul.server.addr.main", "=" + port).getValue(); if (sockAddr instanceof InetSocketAddress) { metricId = String.valueOf(((InetSocketAddress) sockAddr).getPort()); } else { // Just pick something. This would likely be a UDS addr or a LocalChannel addr. metricId = sockAddr.toString(); } } SocketAddress pushSockAddr; { int pushPort = new DynamicIntProperty("zuul.server.port.http.push", 7008).get(); pushSockAddr = new SocketAddressProperty("zuul.server.addr.http.push", "=" + pushPort).getValue(); } String mainListenAddressName = "main"; ServerSslConfig sslConfig; ChannelConfig channelConfig = defaultChannelConfig(mainListenAddressName); ChannelConfig channelDependencies = defaultChannelDependencies(mainListenAddressName); /* These settings may need to be tweaked depending if you're running behind an ELB HTTP listener, TCP listener, * or directly on the internet. */ switch (SERVER_TYPE) { /* The below settings can be used when running behind an ELB HTTP listener that terminates SSL for you * and passes XFF headers. */ case HTTP: channelConfig.set( CommonChannelConfigKeys.allowProxyHeadersWhen, StripUntrustedProxyHeadersHandler.AllowWhen.ALWAYS); channelConfig.set(CommonChannelConfigKeys.preferProxyProtocolForClientIp, false); channelConfig.set(CommonChannelConfigKeys.isSSlFromIntermediary, false); channelConfig.set(CommonChannelConfigKeys.withProxyProtocol, false); addrsToChannels.put( new NamedSocketAddress("http", sockAddr), new ZuulServerChannelInitializer(metricId, channelConfig, channelDependencies, clientChannels) { @Override protected void addHttp1Handlers(ChannelPipeline pipeline) { super.addHttp1Handlers(pipeline); pipeline.addLast(new HttpContentCompressor((CompressionOptions[]) null)); } }); logAddrConfigured(sockAddr); break; /* The below settings can be used when running behind an ELB TCP listener with proxy protocol, terminating * SSL in Zuul. */ case HTTP2: sslConfig = ServerSslConfig.withDefaultCiphers( loadFromResources("server.cert"), loadFromResources("server.key"), WWW_PROTOCOLS); channelConfig.set( CommonChannelConfigKeys.allowProxyHeadersWhen, StripUntrustedProxyHeadersHandler.AllowWhen.NEVER); channelConfig.set(CommonChannelConfigKeys.preferProxyProtocolForClientIp, true); channelConfig.set(CommonChannelConfigKeys.isSSlFromIntermediary, false); channelConfig.set(CommonChannelConfigKeys.serverSslConfig, sslConfig); channelConfig.set( CommonChannelConfigKeys.sslContextFactory, new BaseSslContextFactory(registry, sslConfig)); addHttp2DefaultConfig(channelConfig, mainListenAddressName); addrsToChannels.put( new NamedSocketAddress("http2", sockAddr), new Http2SslChannelInitializer(metricId, channelConfig, channelDependencies, clientChannels)); logAddrConfigured(sockAddr, sslConfig); break; /* The below settings can be used when running behind an ELB TCP listener with proxy protocol, terminating * SSL in Zuul. * * Can be tested using certs in resources directory: * curl https://localhost:7001/test -vk --cert src/main/resources/ssl/client.cert:zuul123 --key src/main/resources/ssl/client.key */ case HTTP_MUTUAL_TLS: sslConfig = new ServerSslConfig( WWW_PROTOCOLS, ServerSslConfig.getDefaultCiphers(), loadFromResources("server.cert"), loadFromResources("server.key"), ClientAuth.REQUIRE, loadFromResources("truststore.jks"), loadFromResources("truststore.key"), false); channelConfig.set( CommonChannelConfigKeys.allowProxyHeadersWhen, StripUntrustedProxyHeadersHandler.AllowWhen.NEVER); channelConfig.set(CommonChannelConfigKeys.preferProxyProtocolForClientIp, true); channelConfig.set(CommonChannelConfigKeys.isSSlFromIntermediary, false); channelConfig.set(CommonChannelConfigKeys.withProxyProtocol, true); channelConfig.set(CommonChannelConfigKeys.serverSslConfig, sslConfig); channelConfig.set( CommonChannelConfigKeys.sslContextFactory, new BaseSslContextFactory(registry, sslConfig)); addrsToChannels.put( new NamedSocketAddress("http_mtls", sockAddr), new Http1MutualSslChannelInitializer( metricId, channelConfig, channelDependencies, clientChannels)); logAddrConfigured(sockAddr, sslConfig); break; /* Settings to be used when running behind an ELB TCP listener with proxy protocol as a Push notification * server using WebSockets */ case WEBSOCKET: channelConfig.set( CommonChannelConfigKeys.allowProxyHeadersWhen, StripUntrustedProxyHeadersHandler.AllowWhen.NEVER); channelConfig.set(CommonChannelConfigKeys.preferProxyProtocolForClientIp, true); channelConfig.set(CommonChannelConfigKeys.isSSlFromIntermediary, false); channelConfig.set(CommonChannelConfigKeys.withProxyProtocol, true); channelDependencies.set(ZuulDependencyKeys.pushConnectionRegistry, pushConnectionRegistry); /* addrsToChannels.put( new NamedSocketAddress("websocket", sockAddr), new SampleWebSocketPushChannelInitializer( metricId, channelConfig, channelDependencies, clientChannels)); */ logAddrConfigured(sockAddr); // port to accept push message from the backend, should be accessible on internal network only. // TODO ? addrsToChannels.put(new NamedSocketAddress("http.push", pushSockAddr), pushSenderInitializer); logAddrConfigured(pushSockAddr); break; /* Settings to be used when running behind an ELB TCP listener with proxy protocol as a Push notification * server using Server Sent Events (SSE) */ case SSE: channelConfig.set( CommonChannelConfigKeys.allowProxyHeadersWhen, StripUntrustedProxyHeadersHandler.AllowWhen.NEVER); channelConfig.set(CommonChannelConfigKeys.preferProxyProtocolForClientIp, true); channelConfig.set(CommonChannelConfigKeys.isSSlFromIntermediary, false); channelConfig.set(CommonChannelConfigKeys.withProxyProtocol, true); channelDependencies.set(ZuulDependencyKeys.pushConnectionRegistry, pushConnectionRegistry); /* addrsToChannels.put( new NamedSocketAddress("sse", sockAddr), new SampleSSEPushChannelInitializer( metricId, channelConfig, channelDependencies, clientChannels)); */ logAddrConfigured(sockAddr); // port to accept push message from the backend, should be accessible on internal network only. // todo ? addrsToChannels.put(new NamedSocketAddress("http.push", pushSockAddr), pushSenderInitializer); logAddrConfigured(pushSockAddr); break; } return Collections.unmodifiableMap(addrsToChannels); } private File loadFromResources(String s) { return new File(ClassLoader.getSystemResource("ssl/" + s).getFile()); } }
6,461
0
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/NoFilenameFilter.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.integration.server; import java.io.File; import java.io.FilenameFilter; public class NoFilenameFilter implements FilenameFilter { @Override public boolean accept(File dir, String name) { return false; } }
6,462
0
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/TestUtil.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.integration.server; import com.netflix.appinfo.InstanceInfo; import com.netflix.niws.loadbalancer.DiscoveryEnabledServer; import org.apache.commons.lang3.StringUtils; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.UUID; public class TestUtil { private TestUtil() {} public static final Charset CHARSET = StandardCharsets.UTF_8; public static final String COMPRESSIBLE_CONTENT = "Hello Hello Hello Hello Hello"; public static final String COMPRESSIBLE_CONTENT_TYPE = "text/plain"; public static final String JUMBO_RESPONSE_BODY = StringUtils.repeat("abc", 1_000_000); public static DiscoveryEnabledServer makeDiscoveryEnabledServer( final String appName, final String ipAddress, final int port) { InstanceInfo instanceInfo = new InstanceInfo( UUID.randomUUID().toString(), appName, appName, ipAddress, "sid123", new InstanceInfo.PortWrapper(true, port), null, null, null, null, null, null, null, 1, null, null, null, null, null, null, null, null, null, null, null, null); return new DiscoveryEnabledServer(instanceInfo, false, true); } }
6,463
0
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/FilterLoaderProvider.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.integration.server; import com.google.inject.Provider; import com.netflix.zuul.DefaultFilterFactory; import com.netflix.zuul.FilterLoader; import com.netflix.zuul.StaticFilterLoader; import com.netflix.zuul.filters.ZuulFilter; import com.netflix.zuul.integration.server.filters.InboundRoutesFilter; import com.netflix.zuul.integration.server.filters.NeedsBodyBufferedInboundFilter; import com.netflix.zuul.integration.server.filters.NeedsBodyBufferedOutboundFilter; import com.netflix.zuul.integration.server.filters.RequestHeaderFilter; import com.netflix.zuul.integration.server.filters.ResponseHeaderFilter; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; public class FilterLoaderProvider implements Provider<FilterLoader> { private static final Set<? extends Class<? extends ZuulFilter<?, ?>>> FILTER_TYPES; static { Set<Class<? extends ZuulFilter<?, ?>>> classes = new LinkedHashSet<>(); classes.add(InboundRoutesFilter.class); classes.add(NeedsBodyBufferedInboundFilter.class); classes.add(RequestHeaderFilter.class); classes.add(ResponseHeaderFilter.class); classes.add(NeedsBodyBufferedOutboundFilter.class); FILTER_TYPES = Collections.unmodifiableSet(classes); } @Override public FilterLoader get() { StaticFilterLoader loader = new StaticFilterLoader(new DefaultFilterFactory(), FILTER_TYPES); return loader; } }
6,464
0
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/HeaderNames.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.integration.server; public class HeaderNames { private HeaderNames() {} public static final String REQUEST_ID = "request-id"; }
6,465
0
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/filters/RequestHeaderFilter.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.integration.server.filters; import com.netflix.zuul.Filter; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.filters.http.HttpInboundFilter; import com.netflix.zuul.integration.server.HeaderNames; import com.netflix.zuul.message.http.HttpRequestMessage; import rx.Observable; import java.util.UUID; @Filter(order = 10, type = FilterType.INBOUND) public class RequestHeaderFilter extends HttpInboundFilter { @Override public boolean shouldFilter(HttpRequestMessage msg) { return true; } @Override public Observable<HttpRequestMessage> applyAsync(HttpRequestMessage request) { request.getHeaders().set(HeaderNames.REQUEST_ID, "RQ-" + UUID.randomUUID()); request.storeInboundRequest(); return Observable.just(request); } }
6,466
0
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/filters/NeedsBodyBufferedInboundFilter.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.integration.server.filters; import com.netflix.zuul.Filter; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.filters.http.HttpInboundFilter; import com.netflix.zuul.message.http.HttpRequestMessage; import rx.Observable; @Filter(order = 20, type = FilterType.INBOUND) public class NeedsBodyBufferedInboundFilter extends HttpInboundFilter { @Override public boolean shouldFilter(HttpRequestMessage msg) { return msg.hasBody(); } @Override public boolean needsBodyBuffered(final HttpRequestMessage message) { return BodyUtil.needsRequestBodyBuffering(message); } @Override public Observable<HttpRequestMessage> applyAsync(final HttpRequestMessage input) { return Observable.just(input); } }
6,467
0
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/filters/NeedsBodyBufferedOutboundFilter.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.integration.server.filters; import com.netflix.zuul.Filter; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.filters.http.HttpOutboundFilter; import com.netflix.zuul.message.http.HttpResponseMessage; import rx.Observable; @Filter(order = 450, type = FilterType.OUTBOUND) public class NeedsBodyBufferedOutboundFilter extends HttpOutboundFilter { @Override public boolean shouldFilter(HttpResponseMessage msg) { return msg.hasBody(); } @Override public boolean needsBodyBuffered(final HttpResponseMessage message) { return BodyUtil.needsResponseBodyBuffering(message.getOutboundRequest()); } @Override public Observable<HttpResponseMessage> applyAsync(final HttpResponseMessage response) { return Observable.just(response); } }
6,468
0
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/filters/BodyUtil.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.integration.server.filters; import com.netflix.zuul.message.http.HttpRequestMessage; public class BodyUtil { public static boolean needsRequestBodyBuffering(final HttpRequestMessage request) { return request.getQueryParams().contains("bufferRequestBody", "true"); } public static boolean needsResponseBodyBuffering(final HttpRequestMessage request) { return request.getQueryParams().contains("bufferResponseBody", "true"); } }
6,469
0
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/filters/InboundRoutesFilter.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.integration.server.filters; import com.netflix.zuul.Filter; import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.filters.endpoint.ProxyEndpoint; import com.netflix.zuul.filters.http.HttpInboundSyncFilter; import com.netflix.zuul.message.http.HttpRequestMessage; @Filter(order = 0, type = FilterType.INBOUND) public class InboundRoutesFilter extends HttpInboundSyncFilter { @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter(HttpRequestMessage msg) { return true; } @Override public HttpRequestMessage apply(HttpRequestMessage input) { // uncomment this line to trigger a resource leak // ByteBuf buffer = UnpooledByteBufAllocator.DEFAULT.buffer(); SessionContext context = input.getContext(); context.setEndpoint(ProxyEndpoint.class.getCanonicalName()); context.setRouteVIP("api"); return input; } }
6,470
0
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server
Create_ds/zuul/zuul-integration-test/src/test/java/com/netflix/zuul/integration/server/filters/ResponseHeaderFilter.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.integration.server.filters; import com.netflix.zuul.Filter; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.filters.http.HttpOutboundFilter; import com.netflix.zuul.integration.server.HeaderNames; import com.netflix.zuul.message.http.HttpResponseMessage; import rx.Observable; @Filter(order = 400, type = FilterType.OUTBOUND) public class ResponseHeaderFilter extends HttpOutboundFilter { @Override public boolean shouldFilter(HttpResponseMessage msg) { return true; } @Override public Observable<HttpResponseMessage> applyAsync(HttpResponseMessage response) { final String requestId = response.getInboundRequest().getHeaders().getFirst(HeaderNames.REQUEST_ID); if (requestId != null) { response.getHeaders().set(HeaderNames.REQUEST_ID, requestId); response.storeInboundResponse(); } return Observable.just(response); } }
6,471
0
Create_ds/zuul/zuul-groovy/src/test/java/com/netflix/zuul
Create_ds/zuul/zuul-groovy/src/test/java/com/netflix/zuul/groovy/GroovyCompilerTest.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.groovy; import groovy.lang.GroovyObject; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Unit tests for {@link GroovyCompiler}. */ @ExtendWith(MockitoExtension.class) class GroovyCompilerTest { @Test void testLoadGroovyFromString() { GroovyCompiler compiler = Mockito.spy(new GroovyCompiler()); try { String code = "class test { public String hello(){return \"hello\" } } "; Class clazz = compiler.compile(code, "test"); assertNotNull(clazz); assertEquals("test", clazz.getName()); GroovyObject groovyObject = (GroovyObject) clazz.newInstance(); Object[] args = {}; String s = (String) groovyObject.invokeMethod("hello", args); assertEquals("hello", s); } catch (Exception e) { assertFalse(true); } } }
6,472
0
Create_ds/zuul/zuul-groovy/src/test/java/com/netflix/zuul
Create_ds/zuul/zuul-groovy/src/test/java/com/netflix/zuul/groovy/GroovyFileFilterTest.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.groovy; import org.junit.jupiter.api.Test; import java.io.File; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Unit tests for {@link GroovyFileFilter}. */ class GroovyFileFilterTest { @Test void testGroovyFileFilter() { GroovyFileFilter filter = new GroovyFileFilter(); assertFalse(filter.accept(new File("/"), "file.mikey")); assertTrue(filter.accept(new File("/"), "file.groovy")); } }
6,473
0
Create_ds/zuul/zuul-groovy/src/test/java/com/netflix/zuul
Create_ds/zuul/zuul-groovy/src/test/java/com/netflix/zuul/scriptManager/FilterVerifierTest.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.scriptManager; import com.netflix.zuul.filters.FilterType; import org.codehaus.groovy.control.CompilationFailedException; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; /** * Unit tests for {@link FilterVerifier}. */ class FilterVerifierTest { private final String sGoodGroovyScriptFilter = "import com.netflix.zuul.filters.*\n" + "import com.netflix.zuul.context.*\n" + "import com.netflix.zuul.message.*\n" + "import com.netflix.zuul.message.http.*\n" + "\n" + "class filter extends BaseSyncFilter<HttpRequestMessage, HttpRequestMessage> {\n" + "\n" + " FilterType filterType() {\n" + " return FilterType.INBOUND\n" + " }\n" + "\n" + " int filterOrder() {\n" + " return 1\n" + " }\n" + "\n" + " boolean shouldFilter(HttpRequestMessage req) {\n" + " return true\n" + " }\n" + "\n" + " HttpRequestMessage apply(HttpRequestMessage req) {\n" + " return null\n" + " }\n" + "\n" + "\n" + "}"; private final String sNotZuulFilterGroovy = "import com.netflix.zuul.filters.*\n" + "import com.netflix.zuul.context.*\n" + "import com.netflix.zuul.message.*\n" + "import com.netflix.zuul.message.http.*\n" + "\n" + "class filter {\n" + "\n" + " FilterType filterType() {\n" + " return FilterType.INBOUND\n" + " }\n" + "\n" + " int filterOrder() {\n" + " return 1\n" + " }\n" + "\n" + " boolean shouldFilter(SessionContext ctx) {\n" + " return true\n" + " }\n" + "\n" + " SessionContext apply(SessionContext ctx) {\n" + " return null\n" + " }\n" + "\n" + "\n" + "}"; private final String sCompileFailCode = "import com.netflix.zuul.filters.*\n" + "import com.netflix.zuul.context.*\n" + "import com.netflix.zuul.message.*\n" + "import com.netflix.zuul.message.http.*\n" + "\n" + "ccclass filter extends BaseSyncFilter<HttpRequestMessage, HttpRequestMessage> {\n" + "\n" + " FilterType filterType() {\n" + " return FilterType.INBOUND\n" + " }\n" + "\n" + " int filterOrder() {\n" + " return 1\n" + " }\n" + "\n" + " boolean shouldFilter(HttpRequestMessage req) {\n" + " return true\n" + " }\n" + "\n" + " HttpRequestMessage apply(HttpRequestMessage req) {\n" + " return null\n" + " }\n" + "\n" + "\n" + "}"; @Test void testCompile() { Class<?> filterClass = FilterVerifier.INSTANCE.compileGroovy(sGoodGroovyScriptFilter); assertNotNull(filterClass); filterClass = FilterVerifier.INSTANCE.compileGroovy(sNotZuulFilterGroovy); assertNotNull(filterClass); assertThrows(CompilationFailedException.class, () -> FilterVerifier.INSTANCE.compileGroovy(sCompileFailCode)); } @Test void testZuulFilterInstance() throws Exception { Class<?> filterClass = FilterVerifier.INSTANCE.compileGroovy(sGoodGroovyScriptFilter); assertNotNull(filterClass); Object filter1 = FilterVerifier.INSTANCE.instantiateClass(filterClass); FilterVerifier.INSTANCE.checkZuulFilterInstance(filter1); filterClass = FilterVerifier.INSTANCE.compileGroovy(sNotZuulFilterGroovy); assertNotNull(filterClass); Object filter2 = FilterVerifier.INSTANCE.instantiateClass(filterClass); assertThrows(InstantiationException.class, () -> FilterVerifier.INSTANCE.checkZuulFilterInstance(filter2)); } @Test void testVerify() throws Exception { FilterInfo filterInfo1 = FilterVerifier.INSTANCE.verifyFilter(sGoodGroovyScriptFilter); assertNotNull(filterInfo1); assertEquals("null:filter:in", filterInfo1.getFilterID()); assertEquals(FilterType.INBOUND, filterInfo1.getFilterType()); assertEquals("filter", filterInfo1.getFilterName()); assertFalse(filterInfo1.isActive()); assertFalse(filterInfo1.isCanary()); assertThrows(InstantiationException.class, () -> FilterVerifier.INSTANCE.verifyFilter(sNotZuulFilterGroovy)); assertThrows(CompilationFailedException.class, () -> FilterVerifier.INSTANCE.verifyFilter(sCompileFailCode)); } }
6,474
0
Create_ds/zuul/zuul-groovy/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-groovy/src/main/java/com/netflix/zuul/groovy/GroovyFileFilter.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.groovy; import java.io.File; import java.io.FilenameFilter; /** * Filters only .groovy files */ public class GroovyFileFilter implements FilenameFilter { @Override public boolean accept(File dir, String name) { return name.endsWith(".groovy"); } }
6,475
0
Create_ds/zuul/zuul-groovy/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-groovy/src/main/java/com/netflix/zuul/groovy/GroovyCompiler.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.groovy; import com.netflix.zuul.DynamicCodeCompiler; import groovy.lang.GroovyClassLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; /** * Groovy code compiler * User: mcohen * Date: 5/30/13 * Time: 11:38 AM * To change this template use File | Settings | File Templates. */ public class GroovyCompiler implements DynamicCodeCompiler { private static final Logger LOG = LoggerFactory.getLogger(GroovyCompiler.class); /** * Compiles Groovy code and returns the Class of the compiles code. * */ @Override public Class<?> compile(String sCode, String sName) { GroovyClassLoader loader = getGroovyClassLoader(); LOG.warn("Compiling filter: {}", sName); Class<?> groovyClass = loader.parseClass(sCode, sName); return groovyClass; } /** * @return a new GroovyClassLoader */ GroovyClassLoader getGroovyClassLoader() { return new GroovyClassLoader(); } /** * Compiles groovy class from a file * */ @Override public Class<?> compile(File file) throws IOException { GroovyClassLoader loader = getGroovyClassLoader(); Class<?> groovyClass = loader.parseClass(file); return groovyClass; } }
6,476
0
Create_ds/zuul/zuul-groovy/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-groovy/src/main/java/com/netflix/zuul/scriptManager/FilterVerifier.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.scriptManager; import com.google.common.annotations.VisibleForTesting; import com.netflix.zuul.ZuulApplicationInfo; import com.netflix.zuul.filters.BaseFilter; import groovy.lang.GroovyClassLoader; import org.codehaus.groovy.control.CompilationFailedException; /** * verifies that the given source code is compilable in Groovy, can be instantiated, and is a ZuulFilter type * * @author Mikey Cohen * Date: 6/12/12 * Time: 7:12 PM */ public class FilterVerifier { @VisibleForTesting static final FilterVerifier INSTANCE = new FilterVerifier(); /** * @return Singleton */ public static FilterVerifier getInstance() { return INSTANCE; } /** * verifies compilation, instanciation and that it is a ZuulFilter * * @return a FilterInfo object representing that code */ public FilterInfo verifyFilter(String sFilterCode) throws CompilationFailedException, IllegalAccessException, InstantiationException { Class<?> groovyClass = compileGroovy(sFilterCode); Object instance = instantiateClass(groovyClass); checkZuulFilterInstance(instance); BaseFilter filter = (BaseFilter) instance; String filter_id = FilterInfo.buildFilterID( ZuulApplicationInfo.getApplicationName(), filter.filterType(), groovyClass.getSimpleName()); return new FilterInfo( filter_id, sFilterCode, filter.filterType(), groovyClass.getSimpleName(), filter.disablePropertyName(), "" + filter.filterOrder(), ZuulApplicationInfo.getApplicationName()); } Object instantiateClass(Class<?> groovyClass) throws InstantiationException, IllegalAccessException { return groovyClass.newInstance(); } void checkZuulFilterInstance(Object zuulFilter) throws InstantiationException { if (!(zuulFilter instanceof BaseFilter)) { throw new InstantiationException("Code is not a ZuulFilter Class "); } } /** * compiles the Groovy source code * */ public Class<?> compileGroovy(String sFilterCode) throws CompilationFailedException { GroovyClassLoader loader = new GroovyClassLoader(); return loader.parseClass(sFilterCode); } }
6,477
0
Create_ds/zuul/zuul-groovy/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-groovy/src/main/java/com/netflix/zuul/scriptManager/FilterInfo.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.scriptManager; import com.netflix.zuul.filters.FilterType; import javax.annotation.concurrent.ThreadSafe; import java.util.Date; import java.util.concurrent.atomic.AtomicBoolean; /** * Representation of a ZuulFilter for representing and storing in a database */ @ThreadSafe public class FilterInfo implements Comparable<FilterInfo> { private final String filter_id; private final String filter_name; private final String filter_code; private final FilterType filter_type; private final String filter_disablePropertyName; private final String filter_order; private final String application_name; private int revision; private Date creationDate; /* using AtomicBoolean so we can pass it into EndpointScriptMonitor */ private final AtomicBoolean isActive = new AtomicBoolean(); private final AtomicBoolean isCanary = new AtomicBoolean(); /** * Constructor */ public FilterInfo( String filter_id, String filter_code, FilterType filter_type, String filter_name, String disablePropertyName, String filter_order, String application_name) { this.filter_id = filter_id; this.filter_code = filter_code; this.filter_type = filter_type; this.filter_name = filter_name; this.filter_disablePropertyName = disablePropertyName; this.filter_order = filter_order; this.application_name = application_name; isActive.set(false); isCanary.set(false); } /** * * @return the filter name; the class name of the filter */ public String getFilterName() { return filter_name; } /** * the Source code for the filter * @return the Source code for the filter */ public String getFilterCode() { return filter_code; } /** * @return the name of the property to disable the filter. */ public String getFilterDisablePropertyName() { return filter_disablePropertyName; } /** * @return the filter_type */ public FilterType getFilterType() { return filter_type; } @Override public String toString() { return "FilterInfo{" + "filter_id='" + filter_id + '\'' + ", filter_name='" + filter_name + '\'' + ", filter_type='" + filter_type + '\'' + ", revision=" + revision + ", creationDate=" + creationDate + ", isActive=" + isActive + ", isCanary=" + isCanary + ", application_name=" + application_name + '}'; } /** * the application name context of the filter. This is for if Zuul is applied to different applications in the same * datastore. */ public String getApplication_name() { return application_name; } public FilterInfo( String filter_id, int revision, Date creationDate, boolean isActive, boolean isCanary, String filter_code, FilterType filter_type, String filter_name, String disablePropertyName, String filter_order, String application_name) { this.filter_id = filter_id; this.revision = revision; this.creationDate = creationDate; this.isActive.set(isActive); this.isCanary.set(isCanary); this.filter_code = filter_code; this.filter_name = filter_name; this.filter_type = filter_type; this.filter_order = filter_order; this.filter_disablePropertyName = disablePropertyName; this.application_name = application_name; } /** * * @return the revision of this filter */ public int getRevision() { return revision; } /** * * @return creation date */ public Date getCreationDate() { return creationDate; } /** * * @return true if this filter is active */ public boolean isActive() { return isActive.get(); } /** * * @return true if this filter should be active a "canary" cluster. A "canary" cluster is a separate cluster * where filters may be tested before going to the full production cluster. */ public boolean isCanary() { return isCanary.get(); } /** * * @return unique key for the filter */ public String getFilterID() { return filter_id; } /** * * @return the filter order */ public String getFilterOrder() { return filter_order; } /** * builds the unique filter_id key * @return key is application_name:filter_name:filter_type */ public static String buildFilterID(String application_name, FilterType filter_type, String filter_name) { return application_name + ":" + filter_name + ":" + filter_type.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FilterInfo that = (FilterInfo) o; if (revision != that.revision) { return false; } if (creationDate != null ? !creationDate.equals(that.creationDate) : that.creationDate != null) { return false; } if (filter_code != null ? !filter_code.equals(that.filter_code) : that.filter_code != null) { return false; } if (filter_id != null ? !filter_id.equals(that.filter_id) : that.filter_id != null) { return false; } if (filter_name != null ? !filter_name.equals(that.filter_name) : that.filter_name != null) { return false; } if (filter_type != null ? !filter_type.equals(that.filter_type) : that.filter_type != null) { return false; } if (isActive != null ? !(isActive.get() == that.isActive.get()) : that.isActive != null) { return false; } if (isCanary != null ? !(isCanary.get() == that.isCanary.get()) : that.isCanary != null) { return false; } return true; } @Override public int hashCode() { int result = filter_id != null ? filter_id.hashCode() : 0; result = 31 * result + (filter_name != null ? filter_name.hashCode() : 0); result = 31 * result + (filter_code != null ? filter_code.hashCode() : 0); result = 31 * result + (filter_type != null ? filter_type.hashCode() : 0); result = 31 * result + revision; result = 31 * result + (creationDate != null ? creationDate.hashCode() : 0); result = 31 * result + (isActive != null ? isActive.hashCode() : 0); result = 31 * result + (isCanary != null ? isCanary.hashCode() : 0); return result; } @Override public int compareTo(FilterInfo filterInfo) { if (filterInfo.getFilterName().equals(this.getFilterName())) { return filterInfo.creationDate.compareTo(getCreationDate()); } return filterInfo.getFilterName().compareTo(this.getFilterName()); } }
6,478
0
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul/sample/Bootstrap.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.sample; import com.google.inject.Guice; import com.google.inject.Injector; import com.netflix.zuul.netty.server.BaseServerStartup; import com.netflix.zuul.netty.server.Server; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.TimeUnit; /** * Bootstrap * * Author: Arthur Gonigberg * Date: November 20, 2017 */ public class Bootstrap { private static final Logger logger = LoggerFactory.getLogger(Bootstrap.class); public static void main(String[] args) { new Bootstrap().start(); } public void start() { long startNanos = System.nanoTime(); logger.info("Zuul Sample: starting up."); int exitCode = 0; Server server = null; try { Injector injector = Guice.createInjector(new ZuulSampleModule()); BaseServerStartup serverStartup = injector.getInstance(BaseServerStartup.class); server = serverStartup.server(); server.start(); long startupDuration = System.nanoTime() - startNanos; logger.info( "Zuul Sample: finished startup. Duration = {}ms", TimeUnit.NANOSECONDS.toMillis(startupDuration)); server.awaitTermination(); } catch (Throwable t) { // Don't use logger here, as we may be shutting down the JVM and the logs won't be printed. t.printStackTrace(); System.err.println("###############"); System.err.println("Zuul Sample: initialization failed. Forcing shutdown now."); System.err.println("###############"); exitCode = 1; } finally { // server shutdown if (server != null) { server.stop(); } System.exit(exitCode); } } }
6,479
0
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul/sample/ZuulSampleModule.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.sample; import com.google.inject.AbstractModule; import com.netflix.config.ConfigurationManager; import com.netflix.discovery.guice.EurekaModule; import com.netflix.netty.common.accesslog.AccessLogPublisher; import com.netflix.netty.common.status.ServerStatusManager; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Registry; import com.netflix.zuul.BasicRequestCompleteHandler; import com.netflix.zuul.DynamicCodeCompiler; import com.netflix.zuul.DynamicFilterLoader; import com.netflix.zuul.FilterFileManager; import com.netflix.zuul.FilterLoader; import com.netflix.zuul.RequestCompleteHandler; import com.netflix.zuul.context.SessionContextDecorator; import com.netflix.zuul.context.ZuulSessionContextDecorator; import com.netflix.zuul.filters.FilterRegistry; import com.netflix.zuul.filters.MutableFilterRegistry; import com.netflix.zuul.groovy.GroovyCompiler; import com.netflix.zuul.groovy.GroovyFileFilter; import com.netflix.zuul.init.ZuulFiltersModule; import com.netflix.zuul.netty.server.BaseServerStartup; import com.netflix.zuul.netty.server.ClientRequestReceiver; import com.netflix.zuul.origins.BasicNettyOriginManager; import com.netflix.zuul.origins.OriginManager; import com.netflix.zuul.stats.BasicRequestMetricsPublisher; import com.netflix.zuul.stats.RequestMetricsPublisher; import org.apache.commons.configuration.AbstractConfiguration; import java.io.FilenameFilter; /** * Zuul Sample Module * * Author: Arthur Gonigberg * Date: November 20, 2017 */ public class ZuulSampleModule extends AbstractModule { @Override protected void configure() { try { ConfigurationManager.loadCascadedPropertiesFromResources("application"); } catch (Exception ex) { throw new RuntimeException("Error loading configuration: " + ex.getMessage(), ex); } bind(AbstractConfiguration.class).toInstance(ConfigurationManager.getConfigInstance()); bind(DynamicCodeCompiler.class).to(GroovyCompiler.class); bind(FilenameFilter.class).to(GroovyFileFilter.class); install(new EurekaModule()); // sample specific bindings bind(BaseServerStartup.class).to(SampleServerStartup.class); // use provided basic netty origin manager bind(OriginManager.class).to(BasicNettyOriginManager.class); // zuul filter loading install(new ZuulFiltersModule()); bind(FilterLoader.class).to(DynamicFilterLoader.class); bind(FilterRegistry.class).to(MutableFilterRegistry.class); bind(FilterFileManager.class).asEagerSingleton(); // general server bindings bind(ServerStatusManager.class); // health/discovery status bind(SessionContextDecorator.class) .to(ZuulSessionContextDecorator.class); // decorate new sessions when requests come in bind(Registry.class).to(DefaultRegistry.class); // atlas metrics registry bind(RequestCompleteHandler.class).to(BasicRequestCompleteHandler.class); // metrics post-request completion bind(RequestMetricsPublisher.class).to(BasicRequestMetricsPublisher.class); // timings publisher // access logger, including request ID generator bind(AccessLogPublisher.class) .toInstance(new AccessLogPublisher( "ACCESS", (channel, httpRequest) -> ClientRequestReceiver.getRequestFromChannel(channel) .getContext() .getUUID())); } }
6,480
0
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul/sample/SampleServerStartup.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.sample; import com.netflix.appinfo.ApplicationInfoManager; 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.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.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.BaseServerStartup; import com.netflix.zuul.netty.server.DefaultEventLoopConfig; import com.netflix.zuul.netty.server.DirectMemoryMonitor; import com.netflix.zuul.netty.server.Http1MutualSslChannelInitializer; import com.netflix.zuul.netty.server.NamedSocketAddress; import com.netflix.zuul.netty.server.SocketAddressProperty; import com.netflix.zuul.netty.server.ZuulDependencyKeys; import com.netflix.zuul.netty.server.ZuulServerChannelInitializer; import com.netflix.zuul.netty.server.http2.Http2SslChannelInitializer; import com.netflix.zuul.netty.server.push.PushConnectionRegistry; import com.netflix.zuul.netty.ssl.BaseSslContextFactory; import com.netflix.zuul.sample.push.SamplePushMessageSenderInitializer; import com.netflix.zuul.sample.push.SampleSSEPushChannelInitializer; import com.netflix.zuul.sample.push.SampleWebSocketPushChannelInitializer; import io.netty.channel.ChannelInitializer; import io.netty.channel.group.ChannelGroup; import io.netty.handler.ssl.ClientAuth; import javax.inject.Inject; import javax.inject.Singleton; import java.io.File; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Sample Server Startup - class that configures the Netty server startup settings * * Author: Arthur Gonigberg * Date: November 20, 2017 */ @Singleton public class SampleServerStartup extends BaseServerStartup { enum ServerType { HTTP, HTTP2, HTTP_MUTUAL_TLS, WEBSOCKET, SSE } private static final String[] WWW_PROTOCOLS = new String[] {"TLSv1.3", "TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3"}; private static final ServerType SERVER_TYPE = ServerType.HTTP; private final PushConnectionRegistry pushConnectionRegistry; private final SamplePushMessageSenderInitializer pushSenderInitializer; @Inject public SampleServerStartup( ServerStatusManager serverStatusManager, FilterLoader filterLoader, SessionContextDecorator sessionCtxDecorator, FilterUsageNotifier usageNotifier, RequestCompleteHandler reqCompleteHandler, Registry registry, DirectMemoryMonitor directMemoryMonitor, EventLoopGroupMetrics eventLoopGroupMetrics, EurekaClient discoveryClient, ApplicationInfoManager applicationInfoManager, AccessLogPublisher accessLogPublisher, PushConnectionRegistry pushConnectionRegistry, SamplePushMessageSenderInitializer pushSenderInitializer) { super( serverStatusManager, filterLoader, sessionCtxDecorator, usageNotifier, reqCompleteHandler, registry, directMemoryMonitor, eventLoopGroupMetrics, new DefaultEventLoopConfig(), discoveryClient, applicationInfoManager, accessLogPublisher); this.pushConnectionRegistry = pushConnectionRegistry; this.pushSenderInitializer = pushSenderInitializer; } @Override protected Map<NamedSocketAddress, ChannelInitializer<?>> chooseAddrsAndChannels(ChannelGroup clientChannels) { Map<NamedSocketAddress, ChannelInitializer<?>> addrsToChannels = new HashMap<>(); SocketAddress sockAddr; String metricId; { @Deprecated int port = new DynamicIntProperty("zuul.server.port.main", 7001).get(); sockAddr = new SocketAddressProperty("zuul.server.addr.main", "=" + port).getValue(); if (sockAddr instanceof InetSocketAddress) { metricId = String.valueOf(((InetSocketAddress) sockAddr).getPort()); } else { // Just pick something. This would likely be a UDS addr or a LocalChannel addr. metricId = sockAddr.toString(); } } SocketAddress pushSockAddr; { int pushPort = new DynamicIntProperty("zuul.server.port.http.push", 7008).get(); pushSockAddr = new SocketAddressProperty("zuul.server.addr.http.push", "=" + pushPort).getValue(); } String mainListenAddressName = "main"; ServerSslConfig sslConfig; ChannelConfig channelConfig = defaultChannelConfig(mainListenAddressName); ChannelConfig channelDependencies = defaultChannelDependencies(mainListenAddressName); /* These settings may need to be tweaked depending if you're running behind an ELB HTTP listener, TCP listener, * or directly on the internet. */ switch (SERVER_TYPE) { /* The below settings can be used when running behind an ELB HTTP listener that terminates SSL for you * and passes XFF headers. */ case HTTP: channelConfig.set( CommonChannelConfigKeys.allowProxyHeadersWhen, StripUntrustedProxyHeadersHandler.AllowWhen.ALWAYS); channelConfig.set(CommonChannelConfigKeys.preferProxyProtocolForClientIp, false); channelConfig.set(CommonChannelConfigKeys.isSSlFromIntermediary, false); channelConfig.set(CommonChannelConfigKeys.withProxyProtocol, false); addrsToChannels.put( new NamedSocketAddress("http", sockAddr), new ZuulServerChannelInitializer(metricId, channelConfig, channelDependencies, clientChannels)); logAddrConfigured(sockAddr); break; /* The below settings can be used when running behind an ELB TCP listener with proxy protocol, terminating * SSL in Zuul. */ case HTTP2: sslConfig = ServerSslConfig.withDefaultCiphers( loadFromResources("server.cert"), loadFromResources("server.key"), WWW_PROTOCOLS); channelConfig.set( CommonChannelConfigKeys.allowProxyHeadersWhen, StripUntrustedProxyHeadersHandler.AllowWhen.NEVER); channelConfig.set(CommonChannelConfigKeys.preferProxyProtocolForClientIp, true); channelConfig.set(CommonChannelConfigKeys.isSSlFromIntermediary, false); channelConfig.set(CommonChannelConfigKeys.serverSslConfig, sslConfig); channelConfig.set( CommonChannelConfigKeys.sslContextFactory, new BaseSslContextFactory(registry, sslConfig)); addHttp2DefaultConfig(channelConfig, mainListenAddressName); addrsToChannels.put( new NamedSocketAddress("http2", sockAddr), new Http2SslChannelInitializer(metricId, channelConfig, channelDependencies, clientChannels)); logAddrConfigured(sockAddr, sslConfig); break; /* The below settings can be used when running behind an ELB TCP listener with proxy protocol, terminating * SSL in Zuul. * * Can be tested using certs in resources directory: * curl https://localhost:7001/test -vk --cert src/main/resources/ssl/client.cert:zuul123 --key src/main/resources/ssl/client.key */ case HTTP_MUTUAL_TLS: sslConfig = new ServerSslConfig( WWW_PROTOCOLS, ServerSslConfig.getDefaultCiphers(), loadFromResources("server.cert"), loadFromResources("server.key"), ClientAuth.REQUIRE, loadFromResources("truststore.jks"), loadFromResources("truststore.key"), false); channelConfig.set( CommonChannelConfigKeys.allowProxyHeadersWhen, StripUntrustedProxyHeadersHandler.AllowWhen.NEVER); channelConfig.set(CommonChannelConfigKeys.preferProxyProtocolForClientIp, true); channelConfig.set(CommonChannelConfigKeys.isSSlFromIntermediary, false); channelConfig.set(CommonChannelConfigKeys.withProxyProtocol, true); channelConfig.set(CommonChannelConfigKeys.serverSslConfig, sslConfig); channelConfig.set( CommonChannelConfigKeys.sslContextFactory, new BaseSslContextFactory(registry, sslConfig)); addrsToChannels.put( new NamedSocketAddress("http_mtls", sockAddr), new Http1MutualSslChannelInitializer( metricId, channelConfig, channelDependencies, clientChannels)); logAddrConfigured(sockAddr, sslConfig); break; /* Settings to be used when running behind an ELB TCP listener with proxy protocol as a Push notification * server using WebSockets */ case WEBSOCKET: channelConfig.set( CommonChannelConfigKeys.allowProxyHeadersWhen, StripUntrustedProxyHeadersHandler.AllowWhen.NEVER); channelConfig.set(CommonChannelConfigKeys.preferProxyProtocolForClientIp, true); channelConfig.set(CommonChannelConfigKeys.isSSlFromIntermediary, false); channelConfig.set(CommonChannelConfigKeys.withProxyProtocol, true); channelDependencies.set(ZuulDependencyKeys.pushConnectionRegistry, pushConnectionRegistry); addrsToChannels.put( new NamedSocketAddress("websocket", sockAddr), new SampleWebSocketPushChannelInitializer( metricId, channelConfig, channelDependencies, clientChannels)); logAddrConfigured(sockAddr); // port to accept push message from the backend, should be accessible on internal network only. addrsToChannels.put(new NamedSocketAddress("http.push", pushSockAddr), pushSenderInitializer); logAddrConfigured(pushSockAddr); break; /* Settings to be used when running behind an ELB TCP listener with proxy protocol as a Push notification * server using Server Sent Events (SSE) */ case SSE: channelConfig.set( CommonChannelConfigKeys.allowProxyHeadersWhen, StripUntrustedProxyHeadersHandler.AllowWhen.NEVER); channelConfig.set(CommonChannelConfigKeys.preferProxyProtocolForClientIp, true); channelConfig.set(CommonChannelConfigKeys.isSSlFromIntermediary, false); channelConfig.set(CommonChannelConfigKeys.withProxyProtocol, true); channelDependencies.set(ZuulDependencyKeys.pushConnectionRegistry, pushConnectionRegistry); addrsToChannels.put( new NamedSocketAddress("sse", sockAddr), new SampleSSEPushChannelInitializer( metricId, channelConfig, channelDependencies, clientChannels)); logAddrConfigured(sockAddr); // port to accept push message from the backend, should be accessible on internal network only. addrsToChannels.put(new NamedSocketAddress("http.push", pushSockAddr), pushSenderInitializer); logAddrConfigured(pushSockAddr); break; } return Collections.unmodifiableMap(addrsToChannels); } private File loadFromResources(String s) { return new File(ClassLoader.getSystemResource("ssl/" + s).getFile()); } }
6,481
0
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul/sample/SampleService.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.sample; import rx.Observable; import javax.inject.Singleton; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * Sample Service for demonstration in SampleServiceFilter. * * Author: Arthur Gonigberg * Date: January 04, 2018 */ @Singleton public class SampleService { private final AtomicBoolean status; public SampleService() { // change to true for demo this.status = new AtomicBoolean(false); } public boolean isHealthy() { return status.get(); } public Observable<String> makeSlowRequest() { return Observable.just("test").delay(500, TimeUnit.MILLISECONDS); } }
6,482
0
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul/sample
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul/sample/filters/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.sample.filters; import com.netflix.zuul.Filter; import com.netflix.zuul.filters.http.HttpInboundSyncFilter; import com.netflix.zuul.message.http.HttpRequestMessage; /** * Determine if requests need to be debugged. * * In order to test this, set query parameter "debugRequest=true" * * Author: Arthur Gonigberg * Date: December 22, 2017 */ @Filter(order = 20) public class Debug extends HttpInboundSyncFilter { @Override public int filterOrder() { return 20; } @Override public boolean shouldFilter(HttpRequestMessage request) { return "true".equalsIgnoreCase(request.getQueryParams().getFirst("debugRequest")); } @Override public HttpRequestMessage apply(HttpRequestMessage request) { request.getContext().setDebugRequest(true); request.getContext().setDebugRouting(true); return request; } }
6,483
0
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul/sample
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SamplePushAuthHandler.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.sample.push; import com.google.common.base.Strings; import com.netflix.zuul.message.http.Cookies; import com.netflix.zuul.netty.server.push.PushAuthHandler; import com.netflix.zuul.netty.server.push.PushUserAuth; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.Cookie; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpResponseStatus; /** * Takes cookie value of the cookie "userAuthCookie" as a customerId WITHOUT ANY actual validation. * For sample puprose only. In real life the cookies at minimum should be HMAC signed to prevent tampering/spoofing, * probably encrypted too if it can be exchanged on plain HTTP. * * Author: Susheel Aroskar * Date: 5/16/18 */ @ChannelHandler.Sharable public class SamplePushAuthHandler extends PushAuthHandler { public SamplePushAuthHandler(String path) { super(path, ".sample.netflix.com"); } /** * We support only cookie based auth in this sample */ @Override protected boolean isDelayedAuth(FullHttpRequest req, ChannelHandlerContext ctx) { return false; } @Override protected PushUserAuth doAuth(FullHttpRequest req) { final Cookies cookies = parseCookies(req); for (final Cookie c : cookies.getAll()) { if (c.getName().equals("userAuthCookie")) { final String customerId = c.getValue(); if (!Strings.isNullOrEmpty(customerId)) { return new SamplePushUserAuth(customerId); } } } return new SamplePushUserAuth(HttpResponseStatus.UNAUTHORIZED.code()); } }
6,484
0
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul/sample
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SampleSSEPushChannelInitializer.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.sample.push; import com.netflix.netty.common.channel.config.ChannelConfig; import com.netflix.zuul.netty.server.ZuulDependencyKeys; import com.netflix.zuul.netty.server.push.PushAuthHandler; import com.netflix.zuul.netty.server.push.PushChannelInitializer; import com.netflix.zuul.netty.server.push.PushConnectionRegistry; import com.netflix.zuul.netty.server.push.PushProtocol; import com.netflix.zuul.netty.server.push.PushRegistrationHandler; import io.netty.channel.ChannelPipeline; import io.netty.channel.group.ChannelGroup; /** * Author: Susheel Aroskar * Date: 6/8/18 */ public class SampleSSEPushChannelInitializer extends PushChannelInitializer { private final PushConnectionRegistry pushConnectionRegistry; private final PushAuthHandler pushAuthHandler; public SampleSSEPushChannelInitializer( String metricId, ChannelConfig channelConfig, ChannelConfig channelDependencies, ChannelGroup channels) { super(metricId, channelConfig, channelDependencies, channels); pushConnectionRegistry = channelDependencies.get(ZuulDependencyKeys.pushConnectionRegistry); pushAuthHandler = new SamplePushAuthHandler(PushProtocol.SSE.getPath()); } @Override protected void addPushHandlers(final ChannelPipeline pipeline) { pipeline.addLast(PushAuthHandler.NAME, pushAuthHandler); pipeline.addLast(new PushRegistrationHandler(pushConnectionRegistry, PushProtocol.SSE)); pipeline.addLast(new SampleSSEPushClientProtocolHandler()); } }
6,485
0
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul/sample
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SampleSSEPushClientProtocolHandler.java
/* * Copyright 2016 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.sample.push; import com.netflix.config.CachedDynamicIntProperty; import com.netflix.zuul.netty.server.push.PushClientProtocolHandler; import com.netflix.zuul.netty.server.push.PushProtocol; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpContentCompressor; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; /** * Created by saroskar on 10/10/16. */ public class SampleSSEPushClientProtocolHandler extends PushClientProtocolHandler { public static final CachedDynamicIntProperty SSE_RETRY_BASE_INTERVAL = new CachedDynamicIntProperty("zuul.push.sse.retry.base", 5000); @Override public void channelRead(final ChannelHandlerContext ctx, final Object mesg) throws Exception { if (mesg instanceof FullHttpRequest) { final FullHttpRequest req = (FullHttpRequest) mesg; if ((req.method() == HttpMethod.GET) && (PushProtocol.SSE.getPath().equals(req.uri()))) { ctx.pipeline().fireUserEventTriggered(PushProtocol.SSE.getHandshakeCompleteEvent()); final DefaultHttpResponse resp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); final HttpHeaders headers = resp.headers(); headers.add("Connection", "keep-alive"); headers.add("Content-Type", "text/event-stream"); headers.add("Transfer-Encoding", "chunked"); final ChannelFuture cf = ctx.channel().writeAndFlush(resp); cf.addListener(future -> { if (future.isSuccess()) { ChannelPipeline pipeline = ctx.pipeline(); if (pipeline.get(HttpObjectAggregator.class) != null) { pipeline.remove(HttpObjectAggregator.class); } if (pipeline.get(HttpContentCompressor.class) != null) { pipeline.remove(HttpContentCompressor.class); } final String reconnetInterval = "retry: " + SSE_RETRY_BASE_INTERVAL.get() + "\r\n\r\n"; ctx.writeAndFlush(reconnetInterval); } }); } } } }
6,486
0
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul/sample
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SamplePushMessageSenderInitializer.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.sample.push; import com.netflix.zuul.netty.server.push.PushConnectionRegistry; import com.netflix.zuul.netty.server.push.PushMessageSender; import com.netflix.zuul.netty.server.push.PushMessageSenderInitializer; import io.netty.channel.ChannelPipeline; import javax.inject.Inject; import javax.inject.Singleton; /** * Author: Susheel Aroskar * Date: 5/16/18 */ @Singleton public class SamplePushMessageSenderInitializer extends PushMessageSenderInitializer { private final PushMessageSender pushMessageSender; @Inject public SamplePushMessageSenderInitializer(PushConnectionRegistry pushConnectionRegistry) { super(); pushMessageSender = new SamplePushMessageSender(pushConnectionRegistry); } @Override protected void addPushMessageHandlers(ChannelPipeline pipeline) { pipeline.addLast(pushMessageSender); } }
6,487
0
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul/sample
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SamplePushUserAuth.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.sample.push; import com.netflix.zuul.netty.server.push.PushUserAuth; /** * Author: Susheel Aroskar * Date: 5/16/18 */ public class SamplePushUserAuth implements PushUserAuth { private String customerId; private int statusCode; private SamplePushUserAuth(String customerId, int statusCode) { this.customerId = customerId; this.statusCode = statusCode; } // Successful auth public SamplePushUserAuth(String customerId) { this(customerId, 200); } // Failed auth public SamplePushUserAuth(int statusCode) { this("", statusCode); } @Override public boolean isSuccess() { return statusCode == 200; } @Override public int statusCode() { return statusCode; } @Override public String getClientIdentity() { return customerId; } }
6,488
0
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul/sample
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SamplePushMessageSender.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.sample.push; import com.google.common.base.Strings; import com.netflix.zuul.netty.server.push.PushConnectionRegistry; import com.netflix.zuul.netty.server.push.PushMessageSender; import com.netflix.zuul.netty.server.push.PushUserAuth; import io.netty.channel.ChannelHandler; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpResponseStatus; import javax.inject.Singleton; /** * Author: Susheel Aroskar * Date: 5/16/18 */ @Singleton @ChannelHandler.Sharable public class SamplePushMessageSender extends PushMessageSender { public SamplePushMessageSender(PushConnectionRegistry pushConnectionRegistry) { super(pushConnectionRegistry); } @Override protected PushUserAuth getPushUserAuth(FullHttpRequest request) { final String cid = request.headers().get("X-CUSTOMER_ID"); if (Strings.isNullOrEmpty(cid)) { return new SamplePushUserAuth(HttpResponseStatus.UNAUTHORIZED.code()); } return new SamplePushUserAuth(cid); } }
6,489
0
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul/sample
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SampleWebSocketPushChannelInitializer.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.sample.push; import com.netflix.netty.common.channel.config.ChannelConfig; import com.netflix.zuul.netty.server.ZuulDependencyKeys; import com.netflix.zuul.netty.server.push.PushAuthHandler; import com.netflix.zuul.netty.server.push.PushChannelInitializer; import com.netflix.zuul.netty.server.push.PushConnectionRegistry; import com.netflix.zuul.netty.server.push.PushProtocol; import com.netflix.zuul.netty.server.push.PushRegistrationHandler; import io.netty.channel.ChannelPipeline; import io.netty.channel.group.ChannelGroup; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler; /** * Author: Susheel Aroskar * Date: 5/16/18 */ public class SampleWebSocketPushChannelInitializer extends PushChannelInitializer { private final PushConnectionRegistry pushConnectionRegistry; private final PushAuthHandler pushAuthHandler; public SampleWebSocketPushChannelInitializer( String metricId, ChannelConfig channelConfig, ChannelConfig channelDependencies, ChannelGroup channels) { super(metricId, channelConfig, channelDependencies, channels); pushConnectionRegistry = channelDependencies.get(ZuulDependencyKeys.pushConnectionRegistry); pushAuthHandler = new SamplePushAuthHandler(PushProtocol.WEBSOCKET.getPath()); } @Override protected void addPushHandlers(final ChannelPipeline pipeline) { pipeline.addLast(PushAuthHandler.NAME, pushAuthHandler); pipeline.addLast(new WebSocketServerCompressionHandler()); pipeline.addLast(new WebSocketServerProtocolHandler(PushProtocol.WEBSOCKET.getPath(), null, true)); pipeline.addLast(new PushRegistrationHandler(pushConnectionRegistry, PushProtocol.WEBSOCKET)); pipeline.addLast(new SampleWebSocketPushClientProtocolHandler()); } }
6,490
0
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul/sample
Create_ds/zuul/zuul-sample/src/main/java/com/netflix/zuul/sample/push/SampleWebSocketPushClientProtocolHandler.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.sample.push; import com.netflix.zuul.netty.server.push.PushClientProtocolHandler; import com.netflix.zuul.netty.server.push.PushProtocol; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame; import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; import io.netty.handler.codec.http.websocketx.PingWebSocketFrame; import io.netty.handler.codec.http.websocketx.PongWebSocketFrame; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.util.ReferenceCountUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Author: Susheel Aroskar * Date: 5/16/18 */ public class SampleWebSocketPushClientProtocolHandler extends PushClientProtocolHandler { private static Logger logger = LoggerFactory.getLogger(SampleWebSocketPushClientProtocolHandler.class); @Override public final void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { try { if (!isAuthenticated()) { // Do not entertain ANY message from unauthenticated client PushProtocol.WEBSOCKET.sendErrorAndClose(ctx, 1007, "Missing authentication"); } else if (msg instanceof PingWebSocketFrame) { logger.debug("received ping frame"); ctx.writeAndFlush(new PongWebSocketFrame()); } else if (msg instanceof CloseWebSocketFrame) { logger.debug("received close frame"); ctx.close(); } else if (msg instanceof TextWebSocketFrame) { final TextWebSocketFrame tf = (TextWebSocketFrame) msg; final String text = tf.text(); logger.debug("received test frame: {}", text); if (text != null && text.startsWith("ECHO ")) { // echo protocol ctx.channel().writeAndFlush(tf.copy()); } } else if (msg instanceof BinaryWebSocketFrame) { logger.debug("received binary frame"); PushProtocol.WEBSOCKET.sendErrorAndClose(ctx, 1003, "Binary WebSocket frames not supported"); } } finally { ReferenceCountUtil.release(msg); } } }
6,491
0
Create_ds/zuul/zuul-processor/src/test/java/com/netflix/zuul/filters
Create_ds/zuul/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/TopLevelFilter.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.filters.processor; import com.netflix.zuul.Filter; import com.netflix.zuul.filters.FilterType; /** * Used to test generated code. */ @Filter(order = 20, type = FilterType.INBOUND) final class TopLevelFilter extends TestFilter { @Filter(order = 21, type = FilterType.INBOUND) static final class StaticSubclassFilter extends TestFilter {} @SuppressWarnings("unused") // This should be ignored by the processor, since it is abstract @Filter(order = 22, type = FilterType.INBOUND) abstract static class AbstractSubclassFilter extends TestFilter {} @SuppressWarnings("InnerClassMayBeStatic") // The purpose of this test @Filter(order = 23, type = FilterType.INBOUND) final class SubclassFilter extends TestFilter {} static { // This should be ignored by the processor, since it is private. // See https://bugs.openjdk.java.net/browse/JDK-6587158 @SuppressWarnings("unused") @Filter(order = 23, type = FilterType.INBOUND) final class MethodClassFilter {} } } @Filter(order = 24, type = FilterType.INBOUND) final class OuterClassFilter extends TestFilter {}
6,492
0
Create_ds/zuul/zuul-processor/src/test/java/com/netflix/zuul/filters
Create_ds/zuul/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/FilterProcessorTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.filters.processor; import com.google.common.truth.Truth; import com.netflix.zuul.StaticFilterLoader; import com.netflix.zuul.filters.ZuulFilter; import com.netflix.zuul.filters.processor.override.SubpackageFilter; import com.netflix.zuul.filters.processor.subpackage.OverrideFilter; import org.junit.jupiter.api.Test; import java.util.Collection; /** * Tests for {@link FilterProcessor}. */ class FilterProcessorTest { @Test void allFilterClassedRecorded() throws Exception { Collection<Class<ZuulFilter<?, ?>>> filters = StaticFilterLoader.loadFilterTypesFromResources(getClass().getClassLoader()); Truth.assertThat(filters) .containsExactly( OuterClassFilter.class, TopLevelFilter.class, TopLevelFilter.StaticSubclassFilter.class, TopLevelFilter.SubclassFilter.class, OverrideFilter.class, SubpackageFilter.class); } }
6,493
0
Create_ds/zuul/zuul-processor/src/test/java/com/netflix/zuul/filters
Create_ds/zuul/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/TestFilter.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.filters.processor; import com.netflix.zuul.exception.ZuulFilterConcurrencyExceededException; import com.netflix.zuul.filters.FilterSyncType; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.filters.ZuulFilter; import com.netflix.zuul.message.ZuulMessage; import io.netty.handler.codec.http.HttpContent; import rx.Observable; /** * A dummy filter which is used for testing. */ public abstract class TestFilter implements ZuulFilter<ZuulMessage, ZuulMessage> { @Override public boolean isDisabled() { throw new UnsupportedOperationException(); } @Override public String filterName() { throw new UnsupportedOperationException(); } @Override public int filterOrder() { throw new UnsupportedOperationException(); } @Override public FilterType filterType() { throw new UnsupportedOperationException(); } @Override public boolean overrideStopFilterProcessing() { throw new UnsupportedOperationException(); } @Override public void incrementConcurrency() throws ZuulFilterConcurrencyExceededException { throw new UnsupportedOperationException(); } @Override public Observable<ZuulMessage> applyAsync(ZuulMessage input) { throw new UnsupportedOperationException(); } @Override public void decrementConcurrency() { throw new UnsupportedOperationException(); } @Override public FilterSyncType getSyncType() { throw new UnsupportedOperationException(); } @Override public ZuulMessage getDefaultOutput(ZuulMessage input) { throw new UnsupportedOperationException(); } @Override public boolean needsBodyBuffered(ZuulMessage input) { throw new UnsupportedOperationException(); } @Override public HttpContent processContentChunk(ZuulMessage zuulMessage, HttpContent chunk) { throw new UnsupportedOperationException(); } @Override public boolean shouldFilter(ZuulMessage msg) { throw new UnsupportedOperationException(); } }
6,494
0
Create_ds/zuul/zuul-processor/src/test/java/com/netflix/zuul/filters/processor
Create_ds/zuul/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/override/SubpackageFilter.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.filters.processor.override; import com.netflix.zuul.Filter; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.filters.processor.TestFilter; @Filter(order = 30, type = FilterType.INBOUND) public final class SubpackageFilter extends TestFilter {}
6,495
0
Create_ds/zuul/zuul-processor/src/test/java/com/netflix/zuul/filters/processor
Create_ds/zuul/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/override/package-info.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @com.netflix.zuul.Filter.FilterPackageName("MySubpackage") package com.netflix.zuul.filters.processor.override;
6,496
0
Create_ds/zuul/zuul-processor/src/test/java/com/netflix/zuul/filters/processor
Create_ds/zuul/zuul-processor/src/test/java/com/netflix/zuul/filters/processor/subpackage/OverrideFilter.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.filters.processor.subpackage; import com.netflix.zuul.Filter; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.filters.processor.TestFilter; @Filter(order = 30, type = FilterType.INBOUND) public final class OverrideFilter extends TestFilter {}
6,497
0
Create_ds/zuul/zuul-processor/src/main/java/com/netflix/zuul/filters
Create_ds/zuul/zuul-processor/src/main/java/com/netflix/zuul/filters/processor/FilterProcessor.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.filters.processor; import com.google.common.annotations.VisibleForTesting; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Filer; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.tools.FileObject; import javax.tools.StandardLocation; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.nio.file.NoSuchFileException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; @SupportedAnnotationTypes(FilterProcessor.FILTER_TYPE) @SupportedSourceVersion(SourceVersion.RELEASE_8) public final class FilterProcessor extends AbstractProcessor { static final String FILTER_TYPE = "com.netflix.zuul.Filter"; private final Set<String> annotatedElements = new HashSet<>(); @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { Set<? extends Element> annotated = roundEnv.getElementsAnnotatedWith( processingEnv.getElementUtils().getTypeElement(FILTER_TYPE)); for (Element el : annotated) { if (el.getModifiers().contains(Modifier.ABSTRACT)) { continue; } annotatedElements.add(processingEnv .getElementUtils() .getBinaryName((TypeElement) el) .toString()); } if (roundEnv.processingOver()) { try { addNewClasses(processingEnv.getFiler(), annotatedElements); } catch (IOException e) { throw new RuntimeException(e); } finally { annotatedElements.clear(); } } return true; } static void addNewClasses(Filer filer, Collection<String> elements) throws IOException { String resourceName = "META-INF/zuul/allfilters"; List<String> existing = Collections.emptyList(); try { FileObject existingFilters = filer.getResource(StandardLocation.CLASS_OUTPUT, "", resourceName); try (InputStream is = existingFilters.openInputStream(); InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) { existing = readResourceFile(reader); } } catch (FileNotFoundException | NoSuchFileException e) { // Perhaps log this. } catch (IOException e) { throw new RuntimeException(e); } int sizeBefore = existing.size(); Set<String> existingSet = new LinkedHashSet<>(existing); List<String> newElements = new ArrayList<>(existingSet); for (String element : elements) { if (existingSet.add(element)) { newElements.add(element); } } if (newElements.size() == sizeBefore) { // nothing to do. return; } newElements.sort(String::compareTo); FileObject dest = filer.createResource(StandardLocation.CLASS_OUTPUT, "", resourceName); try (OutputStream os = dest.openOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8)) { writeResourceFile(osw, newElements); } } @VisibleForTesting static List<String> readResourceFile(Reader reader) throws IOException { BufferedReader br = new BufferedReader(reader); String line; List<String> lines = new ArrayList<>(); while ((line = br.readLine()) != null) { if (line.trim().isEmpty()) { continue; } lines.add(line); } return Collections.unmodifiableList(lines); } @VisibleForTesting static void writeResourceFile(Writer writer, Collection<?> elements) throws IOException { BufferedWriter bw = new BufferedWriter(writer); for (Object element : elements) { bw.write(String.valueOf(element)); bw.newLine(); } bw.flush(); } }
6,498
0
Create_ds/zuul/zuul-discovery/src/test/java/com/netflix/zuul
Create_ds/zuul/zuul-discovery/src/test/java/com/netflix/zuul/discovery/DiscoveryResultTest.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.discovery; import com.google.common.truth.Truth; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.Builder; import com.netflix.appinfo.InstanceInfo.PortType; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.loadbalancer.DynamicServerListLoadBalancer; import com.netflix.loadbalancer.Server; import com.netflix.niws.loadbalancer.DiscoveryEnabledServer; import org.junit.jupiter.api.Test; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; class DiscoveryResultTest { @Test void hashCodeForNull() { final DiscoveryResult discoveryResult = new DiscoveryResult(null); assertNotNull(discoveryResult.hashCode()); assertEquals(0, discoveryResult.hashCode()); } @Test void serverStatsForEmptySentinel() { Truth.assertThat(DiscoveryResult.EMPTY.getServerStats().toString()).isEqualTo("no stats configured for server"); } @Test void hostAndPortForNullServer() { final DiscoveryResult discoveryResult = new DiscoveryResult(null); assertEquals("undefined", discoveryResult.getHost()); assertEquals(-1, discoveryResult.getPort()); } @Test void serverStatsCacheForSameServer() { final InstanceInfo instanceInfo = Builder.newBuilder() .setAppName("serverstats-cache") .setHostName("serverstats-cache") .setPort(7777) .build(); final DiscoveryEnabledServer server = new DiscoveryEnabledServer(instanceInfo, false); final DiscoveryEnabledServer serverSecure = new DiscoveryEnabledServer(instanceInfo, true); final DynamicServerListLoadBalancer<Server> lb = new DynamicServerListLoadBalancer<>(new DefaultClientConfigImpl()); final DiscoveryResult result = new DiscoveryResult(server, lb.getLoadBalancerStats()); final DiscoveryResult result1 = new DiscoveryResult(serverSecure, lb.getLoadBalancerStats()); Truth.assertThat(result.getServerStats()).isSameInstanceAs(result1.getServerStats()); } @Test void serverStatsDifferForDifferentServer() { final InstanceInfo instanceInfo = Builder.newBuilder() .setAppName("serverstats-cache") .setHostName("serverstats-cache") .setPort(7777) .build(); final InstanceInfo otherInstance = Builder.newBuilder() .setAppName("serverstats-cache-2") .setHostName("serverstats-cache-2") .setPort(7777) .build(); final DiscoveryEnabledServer server = new DiscoveryEnabledServer(instanceInfo, false); final DiscoveryEnabledServer serverSecure = new DiscoveryEnabledServer(otherInstance, false); final DynamicServerListLoadBalancer<Server> lb = new DynamicServerListLoadBalancer<>(new DefaultClientConfigImpl()); final DiscoveryResult result = new DiscoveryResult(server, lb.getLoadBalancerStats()); final DiscoveryResult result1 = new DiscoveryResult(serverSecure, lb.getLoadBalancerStats()); Truth.assertThat(result.getServerStats()).isNotSameInstanceAs(result1.getServerStats()); } @Test void ipAddrV4FromInstanceInfo() { final String ipAddr = "100.1.0.1"; final InstanceInfo instanceInfo = Builder.newBuilder() .setAppName("ipAddrv4") .setHostName("ipAddrv4") .setIPAddr(ipAddr) .setPort(7777) .build(); final DiscoveryEnabledServer server = new DiscoveryEnabledServer(instanceInfo, false); final DynamicServerListLoadBalancer<Server> lb = new DynamicServerListLoadBalancer<>(new DefaultClientConfigImpl()); final DiscoveryResult result = new DiscoveryResult(server, lb.getLoadBalancerStats()); Truth.assertThat(result.getIPAddr()).isEqualTo(Optional.of(ipAddr)); } @Test void ipAddrEmptyForIncompleteInstanceInfo() { final InstanceInfo instanceInfo = Builder.newBuilder() .setAppName("ipAddrMissing") .setHostName("ipAddrMissing") .setPort(7777) .build(); final DiscoveryEnabledServer server = new DiscoveryEnabledServer(instanceInfo, false); final DynamicServerListLoadBalancer<Server> lb = new DynamicServerListLoadBalancer<>(new DefaultClientConfigImpl()); final DiscoveryResult result = new DiscoveryResult(server, lb.getLoadBalancerStats()); Truth.assertThat(result.getIPAddr()).isEqualTo(Optional.empty()); } @Test void sameUnderlyingInstanceInfoEqualsSameResult() { final InstanceInfo instanceInfo = Builder.newBuilder() .setAppName("server-equality") .setHostName("server-equality") .setPort(7777) .build(); final DiscoveryEnabledServer server = new DiscoveryEnabledServer(instanceInfo, false); final DiscoveryEnabledServer otherServer = new DiscoveryEnabledServer(instanceInfo, false); final DynamicServerListLoadBalancer<Server> lb = new DynamicServerListLoadBalancer<>(new DefaultClientConfigImpl()); final DiscoveryResult result = new DiscoveryResult(server, lb.getLoadBalancerStats()); final DiscoveryResult otherResult = new DiscoveryResult(otherServer, lb.getLoadBalancerStats()); Truth.assertThat(result).isEqualTo(otherResult); } @Test void serverInstancesExposingDiffPortsAreNotEqual() { final InstanceInfo instanceInfo = Builder.newBuilder() .setAppName("server-equality") .setHostName("server-equality") .setPort(7777) .build(); final InstanceInfo otherPort = Builder.newBuilder() .setAppName("server-equality") .setHostName("server-equality") .setPort(9999) .build(); final DiscoveryEnabledServer server = new DiscoveryEnabledServer(instanceInfo, false); final DiscoveryEnabledServer otherServer = new DiscoveryEnabledServer(otherPort, false); final DynamicServerListLoadBalancer<Server> lb = new DynamicServerListLoadBalancer<>(new DefaultClientConfigImpl()); final DiscoveryResult result = new DiscoveryResult(server, lb.getLoadBalancerStats()); final DiscoveryResult otherResult = new DiscoveryResult(otherServer, lb.getLoadBalancerStats()); Truth.assertThat(result).isNotEqualTo(otherResult); } @Test void securePortMustCheckInstanceInfo() { final InstanceInfo instanceInfo = Builder.newBuilder() .setAppName("secure-port") .setHostName("secure-port") .setPort(7777) .enablePort(PortType.SECURE, false) .build(); final InstanceInfo secureEnabled = Builder.newBuilder() .setAppName("secure-port") .setHostName("secure-port") .setPort(7777) .enablePort(PortType.SECURE, true) .build(); final DiscoveryEnabledServer server = new DiscoveryEnabledServer(instanceInfo, true); final DiscoveryEnabledServer secureServer = new DiscoveryEnabledServer(secureEnabled, true); final DynamicServerListLoadBalancer<Server> lb = new DynamicServerListLoadBalancer<>(new DefaultClientConfigImpl()); final DiscoveryResult result = new DiscoveryResult(server, lb.getLoadBalancerStats()); final DiscoveryResult secure = new DiscoveryResult(secureServer, lb.getLoadBalancerStats()); Truth.assertThat(result.isSecurePortEnabled()).isFalse(); Truth.assertThat(secure.isSecurePortEnabled()).isTrue(); } }
6,499