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/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/AbstractHystrixCommand.java | /**
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.javanica.command;
import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.cache.CacheInvocationContext;
import com.netflix.hystrix.contrib.javanica.cache.HystrixCacheKeyGenerator;
import com.netflix.hystrix.contrib.javanica.cache.HystrixGeneratedCacheKey;
import com.netflix.hystrix.contrib.javanica.cache.HystrixRequestCacheManager;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult;
import com.netflix.hystrix.contrib.javanica.exception.CommandActionExecutionException;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import javax.annotation.concurrent.ThreadSafe;
import java.util.Collection;
import java.util.List;
/**
* Base class for hystrix commands.
*
* @param <T> the return type
*/
@ThreadSafe
public abstract class AbstractHystrixCommand<T> extends com.netflix.hystrix.HystrixCommand<T> {
private final CommandActions commandActions;
private final CacheInvocationContext<CacheResult> cacheResultInvocationContext;
private final CacheInvocationContext<CacheRemove> cacheRemoveInvocationContext;
private final Collection<HystrixCollapser.CollapsedRequest<Object, Object>> collapsedRequests;
private final List<Class<? extends Throwable>> ignoreExceptions;
private final ExecutionType executionType;
private final HystrixCacheKeyGenerator defaultCacheKeyGenerator = HystrixCacheKeyGenerator.getInstance();
protected AbstractHystrixCommand(HystrixCommandBuilder builder) {
super(builder.getSetterBuilder().build());
this.commandActions = builder.getCommandActions();
this.collapsedRequests = builder.getCollapsedRequests();
this.cacheResultInvocationContext = builder.getCacheResultInvocationContext();
this.cacheRemoveInvocationContext = builder.getCacheRemoveInvocationContext();
this.ignoreExceptions = builder.getIgnoreExceptions();
this.executionType = builder.getExecutionType();
}
/**
* Gets command action.
*
* @return command action
*/
protected CommandAction getCommandAction() {
return commandActions.getCommandAction();
}
/**
* Gets fallback action.
*
* @return fallback action
*/
protected CommandAction getFallbackAction() {
return commandActions.getFallbackAction();
}
/**
* Gets collapsed requests.
*
* @return collapsed requests
*/
protected Collection<HystrixCollapser.CollapsedRequest<Object, Object>> getCollapsedRequests() {
return collapsedRequests;
}
/**
* Gets exceptions types which should be ignored.
*
* @return exceptions types
*/
protected List<Class<? extends Throwable>> getIgnoreExceptions() {
return ignoreExceptions;
}
protected ExecutionType getExecutionType() {
return executionType;
}
/**
* {@inheritDoc}.
*/
@Override
protected String getCacheKey() {
String key = null;
if (cacheResultInvocationContext != null) {
HystrixGeneratedCacheKey hystrixGeneratedCacheKey =
defaultCacheKeyGenerator.generateCacheKey(cacheResultInvocationContext);
key = hystrixGeneratedCacheKey.getCacheKey();
}
return key;
}
/**
* Check whether triggered exception is ignorable.
*
* @param throwable the exception occurred during a command execution
* @return true if exception is ignorable, otherwise - false
*/
boolean isIgnorable(Throwable throwable) {
if (ignoreExceptions == null || ignoreExceptions.isEmpty()) {
return false;
}
for (Class<? extends Throwable> ignoreException : ignoreExceptions) {
if (ignoreException.isAssignableFrom(throwable.getClass())) {
return true;
}
}
return false;
}
/**
* Executes an action. If an action has failed and an exception is ignorable then propagate it as HystrixBadRequestException
* otherwise propagate original exception to trigger fallback method.
* Note: If an exception occurred in a command directly extends {@link java.lang.Throwable} then this exception cannot be re-thrown
* as original exception because HystrixCommand.run() allows throw subclasses of {@link java.lang.Exception}.
* Thus we need to wrap cause in RuntimeException, anyway in this case the fallback logic will be triggered.
*
* @param action the action
* @return result of command action execution
*/
Object process(Action action) throws Exception {
Object result;
try {
result = action.execute();
flushCache();
} catch (CommandActionExecutionException throwable) {
Throwable cause = throwable.getCause();
if (isIgnorable(cause)) {
throw new HystrixBadRequestException(cause.getMessage(), cause);
}
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else if (cause instanceof Exception) {
throw (Exception) cause;
} else {
// instance of Throwable
throw new CommandActionExecutionException(cause);
}
}
return result;
}
/**
* {@inheritDoc}.
*/
@Override
protected abstract T run() throws Exception;
/**
* Clears cache for the specified hystrix command.
*/
protected void flushCache() {
if (cacheRemoveInvocationContext != null) {
HystrixRequestCacheManager.getInstance().clearCache(cacheRemoveInvocationContext);
}
}
/**
* Common action.
*/
abstract class Action {
/**
* Each implementation of this method should wrap any exceptions in CommandActionExecutionException.
*
* @return execution result
* @throws CommandActionExecutionException
*/
abstract Object execute() throws CommandActionExecutionException;
}
/**
* Builder to create error message for failed fallback operation.
*/
static class FallbackErrorMessageBuilder {
private StringBuilder builder = new StringBuilder("failed to process fallback");
static FallbackErrorMessageBuilder create() {
return new FallbackErrorMessageBuilder();
}
public FallbackErrorMessageBuilder append(CommandAction action, Throwable throwable) {
return commandAction(action).exception(throwable);
}
private FallbackErrorMessageBuilder commandAction(CommandAction action) {
if (action instanceof CommandExecutionAction || action instanceof LazyCommandExecutionAction) {
builder.append(": '").append(action.getActionName()).append("'. ")
.append(action.getActionName()).append(" fallback is a hystrix command. ");
} else if (action instanceof MethodExecutionAction) {
builder.append(" is the method: '").append(action.getActionName()).append("'. ");
}
return this;
}
private FallbackErrorMessageBuilder exception(Throwable throwable) {
if (throwable instanceof HystrixBadRequestException) {
builder.append("exception: '").append(throwable.getCause().getClass())
.append("' occurred in fallback was ignored and wrapped to HystrixBadRequestException.\n");
} else if (throwable instanceof HystrixRuntimeException) {
builder.append("exception: '").append(throwable.getCause().getClass())
.append("' occurred in fallback wasn't ignored.\n");
}
return this;
}
public String build() {
return builder.toString();
}
}
}
| 4,500 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/MethodExecutionAction.java | /**
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.javanica.command;
import com.netflix.hystrix.contrib.javanica.command.closure.AsyncClosureFactory;
import com.netflix.hystrix.contrib.javanica.command.closure.Closure;
import com.netflix.hystrix.contrib.javanica.exception.CommandActionExecutionException;
import com.netflix.hystrix.contrib.javanica.exception.ExceptionUtils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import static com.netflix.hystrix.contrib.javanica.utils.EnvUtils.isCompileWeaving;
import static com.netflix.hystrix.contrib.javanica.utils.ajc.AjcUtils.invokeAjcMethod;
/**
* This implementation invokes methods using java reflection.
* If {@link Method#invoke(Object, Object...)} throws exception then this exception is wrapped to {@link CommandActionExecutionException}
* for further unwrapping and processing.
*/
public class MethodExecutionAction implements CommandAction {
private static final Object[] EMPTY_ARGS = new Object[]{};
private final Object object;
private final Method method;
private final Object[] _args;
private final MetaHolder metaHolder;
public MethodExecutionAction(Object object, Method method, MetaHolder metaHolder) {
this.object = object;
this.method = method;
this._args = EMPTY_ARGS;
this.metaHolder = metaHolder;
}
public MethodExecutionAction(Object object, Method method, Object[] args, MetaHolder metaHolder){
this.object = object;
this.method = method;
this._args = args;
this.metaHolder = metaHolder;
}
public Object getObject() {
return object;
}
public Method getMethod() {
return method;
}
public Object[] getArgs() {
return _args;
}
@Override
public MetaHolder getMetaHolder() {
return metaHolder;
}
@Override
public Object execute(ExecutionType executionType) throws CommandActionExecutionException {
return executeWithArgs(executionType, _args);
}
/**
* Invokes the method. Also private method also can be invoked.
*
* @return result of execution
*/
@Override
public Object executeWithArgs(ExecutionType executionType, Object[] args) throws CommandActionExecutionException {
if(ExecutionType.ASYNCHRONOUS == executionType){
Closure closure = AsyncClosureFactory.getInstance().createClosure(metaHolder, method, object, args);
return executeClj(closure.getClosureObj(), closure.getClosureMethod());
}
return execute(object, method, args);
}
/**
* {@inheritDoc}
*/
@Override
public String getActionName() {
return method.getName();
}
/**
* Invokes the method.
*
* @return result of execution
*/
private Object execute(Object o, Method m, Object... args) throws CommandActionExecutionException {
Object result = null;
try {
m.setAccessible(true); // suppress Java language access
if (isCompileWeaving() && metaHolder.getAjcMethod() != null) {
result = invokeAjcMethod(metaHolder.getAjcMethod(), o, metaHolder, args);
} else {
result = m.invoke(o, args);
}
} catch (IllegalAccessException e) {
propagateCause(e);
} catch (InvocationTargetException e) {
propagateCause(e);
}
return result;
}
private Object executeClj(Object o, Method m, Object... args){
Object result = null;
try {
m.setAccessible(true); // suppress Java language access
result = m.invoke(o, args);
} catch (IllegalAccessException e) {
propagateCause(e);
} catch (InvocationTargetException e) {
propagateCause(e);
}
return result;
}
/**
* Retrieves cause exception and wraps to {@link CommandActionExecutionException}.
*
* @param throwable the throwable
*/
private void propagateCause(Throwable throwable) throws CommandActionExecutionException {
ExceptionUtils.propagateCause(throwable);
}
}
| 4,501 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/LazyCommandExecutionAction.java | /**
* Copyright 2012 Netflix, Inc.
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.javanica.command;
import com.netflix.hystrix.HystrixInvokable;
import com.netflix.hystrix.contrib.javanica.exception.CommandActionExecutionException;
import org.apache.commons.lang3.StringUtils;
/**
* This action creates related hystrix commands on demand when command creation can be postponed.
*/
public class LazyCommandExecutionAction implements CommandAction {
private MetaHolder originalMetaHolder;
public LazyCommandExecutionAction(MetaHolder metaHolder) {
this.originalMetaHolder = metaHolder;
}
@Override
public MetaHolder getMetaHolder() {
return originalMetaHolder;
}
/**
* {@inheritDoc}
*/
@Override
public Object execute(ExecutionType executionType) throws CommandActionExecutionException {
HystrixInvokable command = HystrixCommandFactory.getInstance().createDelayed(createCopy(originalMetaHolder, executionType));
return new CommandExecutionAction(command, originalMetaHolder).execute(executionType);
}
/**
* {@inheritDoc}
*/
@Override
public Object executeWithArgs(ExecutionType executionType, Object[] args) throws CommandActionExecutionException {
HystrixInvokable command = HystrixCommandFactory.getInstance().createDelayed(createCopy(originalMetaHolder, executionType, args));
return new CommandExecutionAction(command, originalMetaHolder).execute(executionType);
}
/**
* {@inheritDoc}
*/
@Override
public String getActionName() {
return StringUtils.isNotEmpty(originalMetaHolder.getHystrixCommand().commandKey()) ?
originalMetaHolder.getHystrixCommand().commandKey()
: originalMetaHolder.getDefaultCommandKey();
}
// todo dmgcodevil: move it to MetaHolder class ?
private MetaHolder createCopy(MetaHolder source, ExecutionType executionType) {
return MetaHolder.builder()
.obj(source.getObj())
.method(source.getMethod())
.ajcMethod(source.getAjcMethod())
.fallbackExecutionType(source.getFallbackExecutionType())
.extendedFallback(source.isExtendedFallback())
.extendedParentFallback(source.isExtendedParentFallback())
.executionType(executionType)
.args(source.getArgs())
.observable(source.isObservable())
.observableExecutionMode(source.getObservableExecutionMode())
.defaultCollapserKey(source.getDefaultCollapserKey())
.defaultCommandKey(source.getDefaultCommandKey())
.defaultGroupKey(source.getDefaultGroupKey())
.defaultThreadPoolKey(source.getDefaultThreadPoolKey())
.defaultProperties(source.getDefaultProperties().orNull())
.hystrixCollapser(source.getHystrixCollapser())
.hystrixCommand(source.getHystrixCommand()).build();
}
private MetaHolder createCopy(MetaHolder source, ExecutionType executionType, Object[] args) {
return MetaHolder.builder()
.obj(source.getObj())
.method(source.getMethod())
.executionType(executionType)
.ajcMethod(source.getAjcMethod())
.fallbackExecutionType(source.getFallbackExecutionType())
.extendedParentFallback(source.isExtendedParentFallback())
.extendedFallback(source.isExtendedFallback())
.args(args)
.observable(source.isObservable())
.observableExecutionMode(source.getObservableExecutionMode())
.defaultCollapserKey(source.getDefaultCollapserKey())
.defaultCommandKey(source.getDefaultCommandKey())
.defaultGroupKey(source.getDefaultGroupKey())
.defaultThreadPoolKey(source.getDefaultThreadPoolKey())
.defaultProperties(source.getDefaultProperties().orNull())
.hystrixCollapser(source.getHystrixCollapser())
.hystrixCommand(source.getHystrixCommand()).build();
}
}
| 4,502 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/ClosureCommand.java | /**
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.javanica.command;
/**
* This interface is used to perform command logic within an anonymous class and basically used as wrapper for some logic.
*
* @param <T> command result type
*/
public interface ClosureCommand<T> {
/**
* Process logic.
*
* @return result
*/
T invoke();
}
| 4,503 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/closure/Closure.java | /**
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.javanica.command.closure;
import java.lang.reflect.Method;
/**
* Contains method and instance of anonymous class which implements
* {@link com.netflix.hystrix.contrib.javanica.command.ClosureCommand} interface.
*/
public class Closure {
private final Method closureMethod;
private final Object closureObj;
public Closure() {
closureMethod = null;
closureObj = null;
}
public Closure(Method closureMethod, Object closureObj) {
this.closureMethod = closureMethod;
this.closureObj = closureObj;
}
public Method getClosureMethod() {
return closureMethod;
}
public Object getClosureObj() {
return closureObj;
}
}
| 4,504 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/closure/AbstractClosureFactory.java | /**
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.javanica.command.closure;
import com.google.common.base.Throwables;
import com.netflix.hystrix.contrib.javanica.command.ClosureCommand;
import com.netflix.hystrix.contrib.javanica.command.MetaHolder;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import static com.netflix.hystrix.contrib.javanica.utils.EnvUtils.isCompileWeaving;
import static com.netflix.hystrix.contrib.javanica.utils.ajc.AjcUtils.invokeAjcMethod;
import static org.slf4j.helpers.MessageFormatter.format;
/**
* Abstract implementation of {@link ClosureFactory}.
*/
public abstract class AbstractClosureFactory implements ClosureFactory {
static final String ERROR_TYPE_MESSAGE = "return type of '{}' method should be {}.";
static final String INVOKE_METHOD = "invoke";
@Override
public Closure createClosure(MetaHolder metaHolder, Method method, Object o, Object... args) {
try {
Object closureObj;
method.setAccessible(true);
if (isCompileWeaving()) {
closureObj = invokeAjcMethod(metaHolder.getAjcMethod(), o, metaHolder, args);
} else {
closureObj = method.invoke(o, args); // creates instance of an anonymous class
}
return createClosure(method.getName(), closureObj);
} catch (InvocationTargetException e) {
throw Throwables.propagate(e.getCause());
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
/**
* Creates closure.
*
* @param rootMethodName the name of external method within which closure is created.
* @param closureObj the instance of specific anonymous class
* @return new {@link Closure} instance
* @throws Exception
*/
Closure createClosure(String rootMethodName, final Object closureObj) throws Exception {
if (!isClosureCommand(closureObj)) {
throw new RuntimeException(format(ERROR_TYPE_MESSAGE, rootMethodName,
getClosureCommandType().getName()).getMessage());
}
Method closureMethod = closureObj.getClass().getMethod(INVOKE_METHOD);
return new Closure(closureMethod, closureObj);
}
/**
* Checks that closureObj is instance of necessary class.
*
* @param closureObj the instance of an anonymous class
* @return true of closureObj has expected type, otherwise - false
*/
abstract boolean isClosureCommand(final Object closureObj);
/**
* Gets type of expected closure type.
*
* @return closure (anonymous class) type
*/
abstract Class<? extends ClosureCommand> getClosureCommandType();
}
| 4,505 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/closure/AsyncClosureFactory.java | /**
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.javanica.command.closure;
import com.netflix.hystrix.contrib.javanica.command.AsyncResult;
import com.netflix.hystrix.contrib.javanica.command.ClosureCommand;
/**
* Specific implementation of {@link ClosureFactory}.
*/
public class AsyncClosureFactory extends AbstractClosureFactory {
private static final AsyncClosureFactory INSTANCE = new AsyncClosureFactory();
private AsyncClosureFactory() {
}
public static AsyncClosureFactory getInstance() {
return INSTANCE;
}
/**
* {@inheritDoc}.
*/
@Override
boolean isClosureCommand(Object closureObj) {
return closureObj instanceof AsyncResult;
}
/**
* {@inheritDoc}.
*/
@Override
Class<? extends ClosureCommand> getClosureCommandType() {
return AsyncResult.class;
}
}
| 4,506 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/closure/ClosureFactory.java | /**
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.javanica.command.closure;
import com.netflix.hystrix.contrib.javanica.command.MetaHolder;
import java.lang.reflect.Method;
/**
* Factory to create instances of {@link Closure} class.
*/
public interface ClosureFactory {
/**
* Creates closure in accordance with method return type.
*
* @param metaHolder the meta holder
* @param method the external method within which closure is created
* @param o the object the underlying method is invoked from
* @param args the arguments used for the method call
* @return new {@link Closure} instance
*/
Closure createClosure(final MetaHolder metaHolder, final Method method, final Object o, final Object... args);
}
| 4,507 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/conf/HystrixPropertiesManager.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.javanica.conf;
import com.google.common.collect.ImmutableMap;
import com.netflix.hystrix.HystrixCollapserProperties;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.apache.commons.lang3.Validate;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* This class provides methods to set hystrix properties.
*/
public final class HystrixPropertiesManager {
private HystrixPropertiesManager() {
}
/**
* Command execution properties.
*/
public static final String EXECUTION_ISOLATION_STRATEGY = "execution.isolation.strategy";
public static final String EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS = "execution.isolation.thread.timeoutInMilliseconds";
public static final String EXECUTION_TIMEOUT_ENABLED = "execution.timeout.enabled";
public static final String EXECUTION_ISOLATION_THREAD_INTERRUPT_ON_TIMEOUT = "execution.isolation.thread.interruptOnTimeout";
public static final String EXECUTION_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS = "execution.isolation.semaphore.maxConcurrentRequests";
/**
* Command fallback properties.
*/
public static final String FALLBACK_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS = "fallback.isolation.semaphore.maxConcurrentRequests";
public static final String FALLBACK_ENABLED = "fallback.enabled";
/**
* Command circuit breaker properties.
*/
public static final String CIRCUIT_BREAKER_ENABLED = "circuitBreaker.enabled";
public static final String CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD = "circuitBreaker.requestVolumeThreshold";
public static final String CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS = "circuitBreaker.sleepWindowInMilliseconds";
public static final String CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE = "circuitBreaker.errorThresholdPercentage";
public static final String CIRCUIT_BREAKER_FORCE_OPEN = "circuitBreaker.forceOpen";
public static final String CIRCUIT_BREAKER_FORCE_CLOSED = "circuitBreaker.forceClosed";
/**
* Command metrics properties.
*/
public static final String METRICS_ROLLING_PERCENTILE_ENABLED = "metrics.rollingPercentile.enabled";
public static final String METRICS_ROLLING_PERCENTILE_TIME_IN_MILLISECONDS = "metrics.rollingPercentile.timeInMilliseconds";
public static final String METRICS_ROLLING_PERCENTILE_NUM_BUCKETS = "metrics.rollingPercentile.numBuckets";
public static final String METRICS_ROLLING_PERCENTILE_BUCKET_SIZE = "metrics.rollingPercentile.bucketSize";
public static final String METRICS_HEALTH_SNAPSHOT_INTERVAL_IN_MILLISECONDS = "metrics.healthSnapshot.intervalInMilliseconds";
/**
* Command CommandRequest Context properties.
*/
public static final String REQUEST_CACHE_ENABLED = "requestCache.enabled";
public static final String REQUEST_LOG_ENABLED = "requestLog.enabled";
/**
* Thread pool properties.
*/
public static final String MAX_QUEUE_SIZE = "maxQueueSize";
public static final String CORE_SIZE = "coreSize";
public static final String MAXIMUM_SIZE = "maximumSize";
public static final String ALLOW_MAXIMUM_SIZE_TO_DIVERGE_FROM_CORE_SIZE = "allowMaximumSizeToDivergeFromCoreSize";
public static final String KEEP_ALIVE_TIME_MINUTES = "keepAliveTimeMinutes";
public static final String QUEUE_SIZE_REJECTION_THRESHOLD = "queueSizeRejectionThreshold";
public static final String METRICS_ROLLING_STATS_NUM_BUCKETS = "metrics.rollingStats.numBuckets";
public static final String METRICS_ROLLING_STATS_TIME_IN_MILLISECONDS = "metrics.rollingStats.timeInMilliseconds";
/**
* Collapser properties.
*/
public static final String MAX_REQUESTS_IN_BATCH = "maxRequestsInBatch";
public static final String TIMER_DELAY_IN_MILLISECONDS = "timerDelayInMilliseconds";
/**
* Creates and sets Hystrix command properties.
*
* @param properties the collapser properties
*/
public static HystrixCommandProperties.Setter initializeCommandProperties(List<HystrixProperty> properties) throws IllegalArgumentException {
return initializeProperties(HystrixCommandProperties.Setter(), properties, CMD_PROP_MAP, "command");
}
/**
* Creates and sets Hystrix thread pool properties.
*
* @param properties the collapser properties
*/
public static HystrixThreadPoolProperties.Setter initializeThreadPoolProperties(List<HystrixProperty> properties) throws IllegalArgumentException {
return initializeProperties(HystrixThreadPoolProperties.Setter(), properties, TP_PROP_MAP, "thread pool");
}
/**
* Creates and sets Hystrix collapser properties.
*
* @param properties the collapser properties
*/
public static HystrixCollapserProperties.Setter initializeCollapserProperties(List<HystrixProperty> properties) {
return initializeProperties(HystrixCollapserProperties.Setter(), properties, COLLAPSER_PROP_MAP, "collapser");
}
private static <S> S initializeProperties(S setter, List<HystrixProperty> properties, Map<String, PropSetter<S, String>> propMap, String type) {
if (properties != null && properties.size() > 0) {
for (HystrixProperty property : properties) {
validate(property);
if (!propMap.containsKey(property.name())) {
throw new IllegalArgumentException("unknown " + type + " property: " + property.name());
}
propMap.get(property.name()).set(setter, property.value());
}
}
return setter;
}
private static void validate(HystrixProperty hystrixProperty) throws IllegalArgumentException {
Validate.notBlank(hystrixProperty.name(), "hystrix property name cannot be null or blank");
}
private static final Map<String, PropSetter<HystrixCommandProperties.Setter, String>> CMD_PROP_MAP =
ImmutableMap.<String, PropSetter<HystrixCommandProperties.Setter, String>>builder()
.put(EXECUTION_ISOLATION_STRATEGY, new PropSetter<HystrixCommandProperties.Setter, String>() {
@Override
public void set(HystrixCommandProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withExecutionIsolationStrategy(toEnum(EXECUTION_ISOLATION_STRATEGY, value, HystrixCommandProperties.ExecutionIsolationStrategy.class,
HystrixCommandProperties.ExecutionIsolationStrategy.values()));
}
})
.put(EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS, new PropSetter<HystrixCommandProperties.Setter, String>() {
@Override
public void set(HystrixCommandProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withExecutionTimeoutInMilliseconds(toInt(EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS, value));
}
})
.put(EXECUTION_TIMEOUT_ENABLED, new PropSetter<HystrixCommandProperties.Setter, String>() {
@Override
public void set(HystrixCommandProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withExecutionTimeoutEnabled(toBoolean(value));
}
})
.put(EXECUTION_ISOLATION_THREAD_INTERRUPT_ON_TIMEOUT, new PropSetter<HystrixCommandProperties.Setter, String>() {
@Override
public void set(HystrixCommandProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withExecutionIsolationThreadInterruptOnTimeout(toBoolean(value));
}
})
.put(EXECUTION_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS, new PropSetter<HystrixCommandProperties.Setter, String>() {
@Override
public void set(HystrixCommandProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withExecutionIsolationSemaphoreMaxConcurrentRequests(toInt(EXECUTION_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS, value));
}
})
.put(FALLBACK_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS, new PropSetter<HystrixCommandProperties.Setter, String>() {
@Override
public void set(HystrixCommandProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withFallbackIsolationSemaphoreMaxConcurrentRequests(toInt(FALLBACK_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS, value));
}
})
.put(FALLBACK_ENABLED, new PropSetter<HystrixCommandProperties.Setter, String>() {
@Override
public void set(HystrixCommandProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withFallbackEnabled(toBoolean(value));
}
})
.put(CIRCUIT_BREAKER_ENABLED, new PropSetter<HystrixCommandProperties.Setter, String>() {
@Override
public void set(HystrixCommandProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withCircuitBreakerEnabled(toBoolean(value));
}
})
.put(CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD, new PropSetter<HystrixCommandProperties.Setter, String>() {
@Override
public void set(HystrixCommandProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withCircuitBreakerRequestVolumeThreshold(toInt(CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD, value));
}
})
.put(CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS, new PropSetter<HystrixCommandProperties.Setter, String>() {
@Override
public void set(HystrixCommandProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withCircuitBreakerSleepWindowInMilliseconds(toInt(CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS, value));
}
})
.put(CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE, new PropSetter<HystrixCommandProperties.Setter, String>() {
@Override
public void set(HystrixCommandProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withCircuitBreakerErrorThresholdPercentage(toInt(CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE, value));
}
})
.put(CIRCUIT_BREAKER_FORCE_OPEN, new PropSetter<HystrixCommandProperties.Setter, String>() {
@Override
public void set(HystrixCommandProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withCircuitBreakerForceOpen(toBoolean(value));
}
})
.put(CIRCUIT_BREAKER_FORCE_CLOSED, new PropSetter<HystrixCommandProperties.Setter, String>() {
@Override
public void set(HystrixCommandProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withCircuitBreakerForceClosed(toBoolean(value));
}
})
.put(METRICS_ROLLING_STATS_TIME_IN_MILLISECONDS, new PropSetter<HystrixCommandProperties.Setter, String>() {
@Override
public void set(HystrixCommandProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withMetricsRollingStatisticalWindowInMilliseconds(toInt(METRICS_ROLLING_STATS_TIME_IN_MILLISECONDS, value));
}
})
.put(METRICS_ROLLING_STATS_NUM_BUCKETS, new PropSetter<HystrixCommandProperties.Setter, String>() {
@Override
public void set(HystrixCommandProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withMetricsRollingStatisticalWindowBuckets(toInt(METRICS_ROLLING_STATS_NUM_BUCKETS, value));
}
})
.put(METRICS_ROLLING_PERCENTILE_ENABLED, new PropSetter<HystrixCommandProperties.Setter, String>() {
@Override
public void set(HystrixCommandProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withMetricsRollingPercentileEnabled(toBoolean(value));
}
})
.put(METRICS_ROLLING_PERCENTILE_TIME_IN_MILLISECONDS, new PropSetter<HystrixCommandProperties.Setter, String>() {
@Override
public void set(HystrixCommandProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withMetricsRollingPercentileWindowInMilliseconds(toInt(METRICS_ROLLING_PERCENTILE_TIME_IN_MILLISECONDS, value));
}
})
.put(METRICS_ROLLING_PERCENTILE_NUM_BUCKETS, new PropSetter<HystrixCommandProperties.Setter, String>() {
@Override
public void set(HystrixCommandProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withMetricsRollingPercentileWindowBuckets(toInt(METRICS_ROLLING_PERCENTILE_NUM_BUCKETS, value));
}
})
.put(METRICS_ROLLING_PERCENTILE_BUCKET_SIZE, new PropSetter<HystrixCommandProperties.Setter, String>() {
@Override
public void set(HystrixCommandProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withMetricsRollingPercentileBucketSize(toInt(METRICS_ROLLING_PERCENTILE_BUCKET_SIZE, value));
}
})
.put(METRICS_HEALTH_SNAPSHOT_INTERVAL_IN_MILLISECONDS, new PropSetter<HystrixCommandProperties.Setter, String>() {
@Override
public void set(HystrixCommandProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withMetricsHealthSnapshotIntervalInMilliseconds(toInt(METRICS_HEALTH_SNAPSHOT_INTERVAL_IN_MILLISECONDS, value));
}
})
.put(REQUEST_CACHE_ENABLED, new PropSetter<HystrixCommandProperties.Setter, String>() {
@Override
public void set(HystrixCommandProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withRequestCacheEnabled(toBoolean(value));
}
})
.put(REQUEST_LOG_ENABLED, new PropSetter<HystrixCommandProperties.Setter, String>() {
@Override
public void set(HystrixCommandProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withRequestLogEnabled(toBoolean(value));
}
})
.build();
private static final Map<String, PropSetter<HystrixThreadPoolProperties.Setter, String>> TP_PROP_MAP =
ImmutableMap.<String, PropSetter<HystrixThreadPoolProperties.Setter, String>>builder()
.put(MAX_QUEUE_SIZE, new PropSetter<HystrixThreadPoolProperties.Setter, String>() {
@Override
public void set(HystrixThreadPoolProperties.Setter setter, String value) {
setter.withMaxQueueSize(toInt(MAX_QUEUE_SIZE, value));
}
})
.put(CORE_SIZE, new PropSetter<HystrixThreadPoolProperties.Setter, String>() {
@Override
public void set(HystrixThreadPoolProperties.Setter setter, String value) {
setter.withCoreSize(toInt(CORE_SIZE, value));
}
}
)
.put(MAXIMUM_SIZE, new PropSetter<HystrixThreadPoolProperties.Setter, String>() {
@Override
public void set(HystrixThreadPoolProperties.Setter setter, String value) {
setter.withMaximumSize(toInt(MAXIMUM_SIZE, value));
}
}
)
.put(ALLOW_MAXIMUM_SIZE_TO_DIVERGE_FROM_CORE_SIZE, new PropSetter<HystrixThreadPoolProperties.Setter, String>() {
@Override
public void set(HystrixThreadPoolProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withAllowMaximumSizeToDivergeFromCoreSize(toBoolean(value));
}
})
.put(KEEP_ALIVE_TIME_MINUTES, new PropSetter<HystrixThreadPoolProperties.Setter, String>() {
@Override
public void set(HystrixThreadPoolProperties.Setter setter, String value) {
setter.withKeepAliveTimeMinutes(toInt(KEEP_ALIVE_TIME_MINUTES, value));
}
}
)
.put(QUEUE_SIZE_REJECTION_THRESHOLD, new PropSetter<HystrixThreadPoolProperties.Setter, String>() {
@Override
public void set(HystrixThreadPoolProperties.Setter setter, String value) {
setter.withQueueSizeRejectionThreshold(toInt(QUEUE_SIZE_REJECTION_THRESHOLD, value));
}
}
)
.put(METRICS_ROLLING_STATS_NUM_BUCKETS, new PropSetter<HystrixThreadPoolProperties.Setter, String>() {
@Override
public void set(HystrixThreadPoolProperties.Setter setter, String value) {
setter.withMetricsRollingStatisticalWindowBuckets(toInt(METRICS_ROLLING_STATS_NUM_BUCKETS, value));
}
}
)
.put(METRICS_ROLLING_STATS_TIME_IN_MILLISECONDS, new PropSetter<HystrixThreadPoolProperties.Setter, String>() {
@Override
public void set(HystrixThreadPoolProperties.Setter setter, String value) {
setter.withMetricsRollingStatisticalWindowInMilliseconds(toInt(METRICS_ROLLING_STATS_TIME_IN_MILLISECONDS, value));
}
}
)
.build();
private static final Map<String, PropSetter<HystrixCollapserProperties.Setter, String>> COLLAPSER_PROP_MAP =
ImmutableMap.<String, PropSetter<HystrixCollapserProperties.Setter, String>>builder()
.put(TIMER_DELAY_IN_MILLISECONDS, new PropSetter<HystrixCollapserProperties.Setter, String>() {
@Override
public void set(HystrixCollapserProperties.Setter setter, String value) {
setter.withTimerDelayInMilliseconds(toInt(TIMER_DELAY_IN_MILLISECONDS, value));
}
})
.put(MAX_REQUESTS_IN_BATCH, new PropSetter<HystrixCollapserProperties.Setter, String>() {
@Override
public void set(HystrixCollapserProperties.Setter setter, String value) {
setter.withMaxRequestsInBatch(toInt(MAX_REQUESTS_IN_BATCH, value));
}
}
)
.put(METRICS_ROLLING_STATS_TIME_IN_MILLISECONDS, new PropSetter<HystrixCollapserProperties.Setter, String>() {
@Override
public void set(HystrixCollapserProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withMetricsRollingStatisticalWindowInMilliseconds(toInt(METRICS_ROLLING_STATS_TIME_IN_MILLISECONDS, value));
}
})
.put(METRICS_ROLLING_STATS_NUM_BUCKETS, new PropSetter<HystrixCollapserProperties.Setter, String>() {
@Override
public void set(HystrixCollapserProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withMetricsRollingStatisticalWindowBuckets(toInt(METRICS_ROLLING_STATS_NUM_BUCKETS, value));
}
})
.put(METRICS_ROLLING_PERCENTILE_ENABLED, new PropSetter<HystrixCollapserProperties.Setter, String>() {
@Override
public void set(HystrixCollapserProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withMetricsRollingPercentileEnabled(toBoolean(value));
}
})
.put(METRICS_ROLLING_PERCENTILE_TIME_IN_MILLISECONDS, new PropSetter<HystrixCollapserProperties.Setter, String>() {
@Override
public void set(HystrixCollapserProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withMetricsRollingPercentileWindowInMilliseconds(toInt(METRICS_ROLLING_PERCENTILE_TIME_IN_MILLISECONDS, value));
}
})
.put(METRICS_ROLLING_PERCENTILE_NUM_BUCKETS, new PropSetter<HystrixCollapserProperties.Setter, String>() {
@Override
public void set(HystrixCollapserProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withMetricsRollingPercentileWindowBuckets(toInt(METRICS_ROLLING_PERCENTILE_NUM_BUCKETS, value));
}
})
.put(METRICS_ROLLING_PERCENTILE_BUCKET_SIZE, new PropSetter<HystrixCollapserProperties.Setter, String>() {
@Override
public void set(HystrixCollapserProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withMetricsRollingPercentileBucketSize(toInt(METRICS_ROLLING_PERCENTILE_BUCKET_SIZE, value));
}
})
.put(REQUEST_CACHE_ENABLED, new PropSetter<HystrixCollapserProperties.Setter, String>() {
@Override
public void set(HystrixCollapserProperties.Setter setter, String value) throws IllegalArgumentException {
setter.withRequestCacheEnabled(toBoolean(value));
}
})
.build();
private interface PropSetter<S, V> {
void set(S setter, V value) throws IllegalArgumentException;
}
private static <E extends Enum<E>> E toEnum(String propName, String propValue, Class<E> enumType, E... values) throws IllegalArgumentException {
try {
return Enum.valueOf(enumType, propValue);
} catch (NullPointerException npe) {
throw createBadEnumError(propName, propValue, values);
} catch (IllegalArgumentException e) {
throw createBadEnumError(propName, propValue, values);
}
}
private static int toInt(String propName, String propValue) throws IllegalArgumentException {
try {
return Integer.parseInt(propValue);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("bad property value. property name '" + propName + "'. Expected int value, actual = " + propValue);
}
}
private static boolean toBoolean(String propValue) {
return Boolean.valueOf(propValue);
}
private static IllegalArgumentException createBadEnumError(String propName, String propValue, Enum... values) {
throw new IllegalArgumentException("bad property value. property name '" + propName + "'. Expected correct enum value, one of the [" + Arrays.toString(values) + "] , actual = " + propValue);
}
}
| 4,508 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/exception/HystrixCachingException.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.javanica.exception;
/**
* Indicates that something is going wrong with caching logic.
*
* @author dmgcodevil
*/
public class HystrixCachingException extends RuntimeException {
public HystrixCachingException() {
}
public HystrixCachingException(String message) {
super(message);
}
public HystrixCachingException(String message, Throwable cause) {
super(message, cause);
}
public HystrixCachingException(Throwable cause) {
super(cause);
}
}
| 4,509 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/exception/HystrixCacheKeyGenerationException.java | /**
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.javanica.exception;
/**
* Indicates that something is going wrong with cache key generation logic.
*
* @author dmgcodevil
*/
public class HystrixCacheKeyGenerationException extends RuntimeException {
public HystrixCacheKeyGenerationException() {
}
public HystrixCacheKeyGenerationException(String message) {
super(message);
}
public HystrixCacheKeyGenerationException(String message, Throwable cause) {
super(message, cause);
}
public HystrixCacheKeyGenerationException(Throwable cause) {
super(cause);
}
}
| 4,510 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/exception/FallbackDefinitionException.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.javanica.exception;
public class FallbackDefinitionException extends RuntimeException {
public FallbackDefinitionException() {
}
public FallbackDefinitionException(String message, Throwable cause) {
super(message, cause);
}
public FallbackDefinitionException(Throwable cause) {
super(cause);
}
public FallbackDefinitionException(String message) {
super(message);
}
}
| 4,511 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/exception/HystrixPropertyException.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.javanica.exception;
/**
* Created by dmgcodevil.
*/
public class HystrixPropertyException extends RuntimeException {
public HystrixPropertyException() {
}
public HystrixPropertyException(String message, Throwable cause) {
super(message, cause);
}
public HystrixPropertyException(Throwable cause) {
super(cause);
}
}
| 4,512 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/exception/FallbackInvocationException.java | /**
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.javanica.exception;
/**
* Exception specifies error occurred in fallback method.
*/
public class FallbackInvocationException extends RuntimeException {
public FallbackInvocationException() {
}
public FallbackInvocationException(String message, Throwable cause) {
super(message, cause);
}
public FallbackInvocationException(Throwable cause) {
super(cause);
}
}
| 4,513 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/exception/ExceptionUtils.java | /**
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.javanica.exception;
import com.netflix.hystrix.exception.HystrixBadRequestException;
/**
* Util class to work with exceptions.
*/
public class ExceptionUtils {
/**
* Retrieves cause exception and wraps to {@link CommandActionExecutionException}.
*
* @param throwable the throwable
*/
public static void propagateCause(Throwable throwable) throws CommandActionExecutionException {
throw new CommandActionExecutionException(throwable.getCause());
}
/**
* Wraps cause exception to {@link CommandActionExecutionException}.
*
* @param throwable the throwable
*/
public static CommandActionExecutionException wrapCause(Throwable throwable) {
return new CommandActionExecutionException(throwable.getCause());
}
/**
* Gets actual exception if it's wrapped in {@link CommandActionExecutionException} or {@link HystrixBadRequestException}.
*
* @param e the exception
* @return unwrapped
*/
public static Throwable unwrapCause(Throwable e) {
if (e instanceof CommandActionExecutionException) {
return e.getCause();
}
if (e instanceof HystrixBadRequestException) {
return e.getCause();
}
return e;
}
}
| 4,514 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica | Create_ds/Hystrix/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/exception/CommandActionExecutionException.java | /**
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.javanica.exception;
/**
* This exception is used to wrap original exceptions to push through javanica infrastructure.
*/
public class CommandActionExecutionException extends RuntimeException {
/**
* Creates exceptions instance with cause is original exception.
*
* @param cause the original exception
*/
public CommandActionExecutionException(Throwable cause) {
super(cause);
}
/**
* Default constructor.
*/
public CommandActionExecutionException() {
}
}
| 4,515 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-request-servlet/src/main/java/com/netflix/hystrix/contrib | Create_ds/Hystrix/hystrix-contrib/hystrix-request-servlet/src/main/java/com/netflix/hystrix/contrib/requestservlet/HystrixRequestContextServletFilter.java | /**
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.requestservlet;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
/**
* Initializes the {@link HystrixRequestContext} at the beginning of each HTTP request and then cleans it up at the end.
* <p>
* Install by adding the following lines to your project web.xml:
* <p>
*
* <pre>
* {@code
* <filter>
* <display-name>HystrixRequestContextServletFilter</display-name>
* <filter-name>HystrixRequestContextServletFilter</filter-name>
* <filter-class>com.netflix.hystrix.contrib.requestservlet.HystrixRequestContextServletFilter</filter-class>
* </filter>
* <filter-mapping>
* <filter-name>HystrixRequestContextServletFilter</filter-name>
* <url-pattern>/*</url-pattern>
* </filter-mapping>
* }
* </pre>
*/
public class HystrixRequestContextServletFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HystrixRequestContext context = HystrixRequestContext.initializeContext();
try {
chain.doFilter(request, response);
} finally {
context.shutdown();
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}
| 4,516 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-request-servlet/src/main/java/com/netflix/hystrix/contrib | Create_ds/Hystrix/hystrix-contrib/hystrix-request-servlet/src/main/java/com/netflix/hystrix/contrib/requestservlet/HystrixRequestLogViaLoggerServletFilter.java | /**
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.requestservlet;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.hystrix.HystrixRequestLog;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
/**
* Log an INFO message with the output from <code>HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()</code> at the end of each requet.
* <p>
* A pre-requisite is that {@link HystrixRequestContext} is initialized, such as by using {@link HystrixRequestContextServletFilter}.
* <p>
* Install by adding the following lines to your project web.xml:
* <p>
*
* <pre>
* {@code
* <filter>
* <display-name>HystrixRequestLogViaLoggerServletFilter</display-name>
* <filter-name>HystrixRequestLogViaLoggerServletFilter</filter-name>
* <filter-class>com.netflix.hystrix.contrib.requestservlet.HystrixRequestLogViaLoggerServletFilter</filter-class>
* </filter>
* <filter-mapping>
* <filter-name>HystrixRequestLogViaLoggerServletFilter</filter-name>
* <url-pattern>/*</url-pattern>
* </filter-mapping>
* }
* </pre>
* <p>
* NOTE: This filter must complete before {@link HystrixRequestContext} is shutdown otherwise the {@link HystrixRequestLog} will already be cleared.
* <p>
* This will output a log line similar to this:
*
* <pre>
* Hystrix Executions [POST /order] => CreditCardCommand[SUCCESS][1122ms]
* </pre>
*/
public class HystrixRequestLogViaLoggerServletFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(HystrixRequestLogViaLoggerServletFilter.class);
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
StringBuilder requestURL = new StringBuilder();
try {
// get the requested URL for our logging so it can be associated to a particular request
String uri = ((HttpServletRequest) request).getRequestURI();
String queryString = ((HttpServletRequest) request).getQueryString();
String method = ((HttpServletRequest) request).getMethod();
requestURL.append(method).append(" ").append(uri);
if (queryString != null) {
requestURL.append("?").append(queryString);
}
chain.doFilter(request, response);
} finally {
try {
if (HystrixRequestContext.isCurrentThreadInitialized()) {
HystrixRequestLog log = HystrixRequestLog.getCurrentRequest();
logger.info("Hystrix Executions [{}] => {}", requestURL.toString(), log.getExecutedCommandsAsString());
}
} catch (Exception e) {
logger.warn("Unable to append HystrixRequestLog", e);
}
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}
| 4,517 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-request-servlet/src/main/java/com/netflix/hystrix/contrib | Create_ds/Hystrix/hystrix-contrib/hystrix-request-servlet/src/main/java/com/netflix/hystrix/contrib/requestservlet/HystrixRequestLogViaResponseHeaderServletFilter.java | /**
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.requestservlet;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.hystrix.HystrixRequestLog;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
/**
* Add <code>HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()</code> to response as header "X-HystrixLog".
* <p>
* This will not work if the response has been flushed already.
* <p>
* A pre-requisite is that {@link HystrixRequestContext} is initialized, such as by using {@link HystrixRequestContextServletFilter}.
* <p>
* Install by adding the following lines to your project web.xml:
* <p>
*
* <pre>
* {@code
* <filter>
* <display-name>HystrixRequestLogViaResponseHeaderServletFilter</display-name>
* <filter-name>HystrixRequestLogViaResponseHeaderServletFilter</filter-name>
* <filter-class>com.netflix.hystrix.contrib.requestservlet.HystrixRequestLogViaResponseHeaderServletFilter</filter-class>
* </filter>
* <filter-mapping>
* <filter-name>HystrixRequestLogServletFilter</filter-name>
* <url-pattern>/*</url-pattern>
* </filter-mapping>
* }
* </pre>
*/
public class HystrixRequestLogViaResponseHeaderServletFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(HystrixRequestLogViaResponseHeaderServletFilter.class);
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
chain.doFilter(request, response);
} finally {
try {
if (HystrixRequestContext.isCurrentThreadInitialized()) {
HystrixRequestLog log = HystrixRequestLog.getCurrentRequest();
if (log != null) {
((HttpServletResponse) response).addHeader("X-HystrixLog", log.getExecutedCommandsAsString());
}
}
} catch (Exception e) {
logger.warn("Unable to append HystrixRequestLog", e);
}
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}
| 4,518 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-rx-netty-metrics-stream/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-contrib/hystrix-rx-netty-metrics-stream/src/test/java/com/netflix/hystrix/HystrixCommandMetricsSamples.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix;
import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifierDefault;
/**
* Not very elegant, but there is no other way to create this data directly for testing
* purposes, as {@link com.netflix.hystrix.HystrixCommandMetrics} has no public constructors,
* only package private.
*
* @author Tomasz Bak
*/
public class HystrixCommandMetricsSamples {
public static final HystrixCommandMetrics SAMPLE_1;
private static class MyHystrixCommandKey implements HystrixCommandKey {
@Override
public String name() {
return "hystrixKey";
}
}
private static class MyHystrixCommandGroupKey implements HystrixCommandGroupKey {
@Override
public String name() {
return "hystrixCommandGroupKey";
}
}
private static class MyHystrixThreadPoolKey implements HystrixThreadPoolKey {
@Override
public String name() {
return "hystrixThreadPoolKey";
}
}
private static class MyHystrixCommandProperties extends HystrixCommandProperties {
protected MyHystrixCommandProperties(HystrixCommandKey key) {
super(key);
}
}
static {
HystrixCommandKey key = new MyHystrixCommandKey();
SAMPLE_1 = new HystrixCommandMetrics(key, new MyHystrixCommandGroupKey(), new MyHystrixThreadPoolKey(),
new MyHystrixCommandProperties(key), HystrixEventNotifierDefault.getInstance());
}
}
| 4,519 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-rx-netty-metrics-stream/src/test/java/com/netflix/hystrix/contrib/rxnetty | Create_ds/Hystrix/hystrix-contrib/hystrix-rx-netty-metrics-stream/src/test/java/com/netflix/hystrix/contrib/rxnetty/metricsstream/HystrixMetricsStreamHandlerTest.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.rxnetty.metricsstream;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.hystrix.HystrixCommandMetrics;
import com.netflix.hystrix.HystrixCommandMetricsSamples;
import io.netty.buffer.ByteBuf;
import io.reactivex.netty.RxNetty;
import io.reactivex.netty.pipeline.PipelineConfigurators;
import io.reactivex.netty.protocol.http.client.HttpClient;
import io.reactivex.netty.protocol.http.client.HttpClientRequest;
import io.reactivex.netty.protocol.http.client.HttpClientResponse;
import io.reactivex.netty.protocol.http.server.HttpServer;
import io.reactivex.netty.protocol.http.server.HttpServerRequest;
import io.reactivex.netty.protocol.http.server.HttpServerResponse;
import io.reactivex.netty.protocol.http.server.RequestHandler;
import io.reactivex.netty.protocol.http.sse.ServerSentEvent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import rx.Observable;
import rx.functions.Func1;
import java.util.Collection;
import java.util.Collections;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import static com.netflix.hystrix.contrib.rxnetty.metricsstream.HystrixMetricsStreamHandler.*;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import static org.powermock.api.easymock.PowerMock.*;
/**
* @author Tomasz Bak
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest(HystrixCommandMetrics.class)
public class HystrixMetricsStreamHandlerTest {
private static final ObjectMapper mapper = new ObjectMapper();
private static Collection<HystrixCommandMetrics> SAMPLE_HYSTRIX_COMMAND_METRICS =
Collections.singleton(HystrixCommandMetricsSamples.SAMPLE_1);
private int port;
private HttpServer<ByteBuf, ByteBuf> server;
private HttpClient<ByteBuf, ServerSentEvent> client;
@Before
public void setUp() throws Exception {
server = createServer();
client = RxNetty.<ByteBuf, ServerSentEvent>newHttpClientBuilder("localhost", port)
.withNoConnectionPooling()
.pipelineConfigurator(PipelineConfigurators.<ByteBuf>clientSseConfigurator())
.build();
mockStatic(HystrixCommandMetrics.class);
expect(HystrixCommandMetrics.getInstances()).andReturn(SAMPLE_HYSTRIX_COMMAND_METRICS).anyTimes();
}
@After
public void tearDown() throws Exception {
if (server != null) {
server.shutdown();
}
if (client != null) {
client.shutdown();
}
}
@Test
public void testMetricsAreDeliveredAsSseStream() throws Exception {
replayAll();
Observable<ServerSentEvent> objectObservable = client.submit(HttpClientRequest.createGet(DEFAULT_HYSTRIX_PREFIX))
.flatMap(new Func1<HttpClientResponse<ServerSentEvent>, Observable<? extends ServerSentEvent>>() {
@Override
public Observable<? extends ServerSentEvent> call(HttpClientResponse<ServerSentEvent> httpClientResponse) {
return httpClientResponse.getContent().take(1);
}
});
Object first = Observable.amb(objectObservable, Observable.timer(5000, TimeUnit.MILLISECONDS)).toBlocking().first();
assertTrue("Expected SSE message", first instanceof ServerSentEvent);
ServerSentEvent sse = (ServerSentEvent) first;
JsonNode jsonNode = mapper.readTree(sse.contentAsString());
assertEquals("Expected hystrix key name", HystrixCommandMetricsSamples.SAMPLE_1.getCommandKey().name(), jsonNode.get("name").asText());
}
// We try a few times in case we hit into used port.
private HttpServer<ByteBuf, ByteBuf> createServer() {
Random random = new Random();
Exception error = null;
for (int i = 0; i < 3 && server == null; i++) {
port = 10000 + random.nextInt(50000);
try {
return RxNetty.newHttpServerBuilder(port, new HystrixMetricsStreamHandler<ByteBuf, ByteBuf>(
DEFAULT_HYSTRIX_PREFIX,
DEFAULT_INTERVAL,
new RequestHandler<ByteBuf, ByteBuf>() { // Application handler
@Override
public Observable<Void> handle(HttpServerRequest<ByteBuf> request, HttpServerResponse<ByteBuf> response) {
return Observable.empty();
}
}
)).build().start();
} catch (Exception e) {
error = e;
}
}
throw new RuntimeException("Cannot initialize RxNetty server", error);
}
}
| 4,520 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-rx-netty-metrics-stream/src/main/java/com/netflix/hystrix/contrib/rxnetty | Create_ds/Hystrix/hystrix-contrib/hystrix-rx-netty-metrics-stream/src/main/java/com/netflix/hystrix/contrib/rxnetty/metricsstream/HystrixMetricsStreamHandler.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.rxnetty.metricsstream;
import com.netflix.hystrix.HystrixCollapserMetrics;
import com.netflix.hystrix.HystrixCommandMetrics;
import com.netflix.hystrix.HystrixThreadPoolMetrics;
import com.netflix.hystrix.serial.SerialHystrixDashboardData;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.reactivex.netty.protocol.http.server.HttpServerRequest;
import io.reactivex.netty.protocol.http.server.HttpServerResponse;
import io.reactivex.netty.protocol.http.server.RequestHandler;
import rx.Observable;
import rx.Subscription;
import rx.functions.Action1;
import rx.subjects.PublishSubject;
import rx.subjects.Subject;
import rx.subscriptions.MultipleAssignmentSubscription;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
/**
* Streams Hystrix metrics in Server Sent Event (SSE) format. RxNetty application handlers shall
* be wrapped by this handler. It transparently intercepts HTTP requests at a configurable path
* (default "/hystrix.stream"), and sends unbounded SSE streams back to the client. All other requests
* are transparently forwarded to the application handlers.
* <p/>
* For RxNetty client tapping into SSE stream: remember to use unpooled HTTP connections. If not, the pooled HTTP
* connection will not be closed on unsubscribe event and the event stream will continue to flow towards the client
* (unless the client is shutdown).
*
* @author Tomasz Bak
* @author Christian Schmitt <c.schmitt@envisia.de>
*/
public class HystrixMetricsStreamHandler<I, O> implements RequestHandler<I, O> {
public static final String DEFAULT_HYSTRIX_PREFIX = "/hystrix.stream";
public static final int DEFAULT_INTERVAL = 2000;
private static final byte[] HEADER = "data: ".getBytes(Charset.defaultCharset());
private static final byte[] FOOTER = {10, 10};
private static final int EXTRA_SPACE = HEADER.length + FOOTER.length;
private final String hystrixPrefix;
private final long interval;
private final RequestHandler<I, O> appHandler;
public HystrixMetricsStreamHandler(RequestHandler<I, O> appHandler) {
this(DEFAULT_HYSTRIX_PREFIX, DEFAULT_INTERVAL, appHandler);
}
HystrixMetricsStreamHandler(String hystrixPrefix, long interval, RequestHandler<I, O> appHandler) {
this.hystrixPrefix = hystrixPrefix;
this.interval = interval;
this.appHandler = appHandler;
}
@Override
public Observable<Void> handle(HttpServerRequest<I> request, HttpServerResponse<O> response) {
if (request.getPath().startsWith(hystrixPrefix)) {
return handleHystrixRequest(response);
}
return appHandler.handle(request, response);
}
private Observable<Void> handleHystrixRequest(final HttpServerResponse<O> response) {
writeHeaders(response);
final Subject<Void, Void> subject = PublishSubject.create();
final MultipleAssignmentSubscription subscription = new MultipleAssignmentSubscription();
Subscription actionSubscription = Observable.interval(interval, TimeUnit.MILLISECONDS)
.subscribe(new Action1<Long>() {
@Override
public void call(Long tick) {
if (!response.getChannel().isOpen()) {
subscription.unsubscribe();
return;
}
try {
for (HystrixCommandMetrics commandMetrics : HystrixCommandMetrics.getInstances()) {
writeMetric(SerialHystrixDashboardData.toJsonString(commandMetrics), response);
}
for (HystrixThreadPoolMetrics threadPoolMetrics : HystrixThreadPoolMetrics.getInstances()) {
writeMetric(SerialHystrixDashboardData.toJsonString(threadPoolMetrics), response);
}
for (HystrixCollapserMetrics collapserMetrics : HystrixCollapserMetrics.getInstances()) {
writeMetric(SerialHystrixDashboardData.toJsonString(collapserMetrics), response);
}
} catch (Exception e) {
subject.onError(e);
}
}
});
subscription.set(actionSubscription);
return subject;
}
private void writeHeaders(HttpServerResponse<O> response) {
response.getHeaders().add("Content-Type", "text/event-stream;charset=UTF-8");
response.getHeaders().add("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
response.getHeaders().add("Pragma", "no-cache");
}
@SuppressWarnings("unchecked")
private void writeMetric(String json, HttpServerResponse<O> response) {
byte[] bytes = json.getBytes(Charset.defaultCharset());
ByteBuf byteBuf = UnpooledByteBufAllocator.DEFAULT.buffer(bytes.length + EXTRA_SPACE);
byteBuf.writeBytes(HEADER);
byteBuf.writeBytes(bytes);
byteBuf.writeBytes(FOOTER);
response.writeAndFlush((O) byteBuf);
}
}
| 4,521 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/test/java/com/netflix/hystrix/contrib/metrics | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/test/java/com/netflix/hystrix/contrib/metrics/eventstream/HystrixMetricsStreamServletUnitTest.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.metrics.eventstream;
import com.netflix.hystrix.metric.consumer.HystrixDashboardStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import rx.Observable;
import rx.functions.Func1;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class HystrixMetricsStreamServletUnitTest {
@Mock HttpServletRequest mockReq;
@Mock HttpServletResponse mockResp;
@Mock HystrixDashboardStream.DashboardData mockDashboard;
@Mock PrintWriter mockPrintWriter;
HystrixMetricsStreamServlet servlet;
private final Observable<HystrixDashboardStream.DashboardData> streamOfOnNexts =
Observable.interval(100, TimeUnit.MILLISECONDS).map(new Func1<Long, HystrixDashboardStream.DashboardData>() {
@Override
public HystrixDashboardStream.DashboardData call(Long timestamp) {
return mockDashboard;
}
});
@Before
public void init() {
MockitoAnnotations.initMocks(this);
when(mockReq.getMethod()).thenReturn("GET");
}
@After
public void tearDown() {
servlet.destroy();
servlet.shutdown();
}
@Test
public void shutdownServletShouldRejectRequests() throws ServletException, IOException {
servlet = new HystrixMetricsStreamServlet(streamOfOnNexts, 10);
try {
servlet.init();
} catch (ServletException ex) {
}
servlet.shutdown();
servlet.service(mockReq, mockResp);
verify(mockResp).sendError(503, "Service has been shut down.");
}
} | 4,522 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/test/java/com/netflix/hystrix/contrib/metrics | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/test/java/com/netflix/hystrix/contrib/metrics/eventstream/HystrixMetricsPollerTest.java | /**
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.metrics.eventstream;
import static org.junit.Assert.*;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
/**
* Polls Hystrix metrics and output JSON strings for each metric to a MetricsPollerListener.
* <p>
* Polling can be stopped/started. Use shutdown() to permanently shutdown the poller.
*/
public class HystrixMetricsPollerTest {
@Test
public void testStartStopStart() {
final AtomicInteger metricsCount = new AtomicInteger();
HystrixMetricsPoller poller = new HystrixMetricsPoller(new HystrixMetricsPoller.MetricsAsJsonPollerListener() {
@Override
public void handleJsonMetric(String json) {
System.out.println("Received: " + json);
metricsCount.incrementAndGet();
}
}, 100);
try {
HystrixCommand<Boolean> test = new HystrixCommand<Boolean>(HystrixCommandGroupKey.Factory.asKey("HystrixMetricsPollerTest")) {
@Override
protected Boolean run() {
return true;
}
};
test.execute();
poller.start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
int v1 = metricsCount.get();
assertTrue(v1 > 0);
poller.pause();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
int v2 = metricsCount.get();
// they should be the same since we were paused
System.out.println("First poll got : " + v1 + ", second got : " + v2);
assertTrue(v2 == v1);
poller.start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
int v3 = metricsCount.get();
// we should have more metrics again
assertTrue(v3 > v1);
} finally {
poller.shutdown();
}
}
}
| 4,523 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/test/java/com/netflix/hystrix/contrib/sample | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/test/java/com/netflix/hystrix/contrib/sample/stream/HystrixSampleSseServletTest.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.hystrix.contrib.sample.stream;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.hystrix.config.HystrixConfiguration;
import com.netflix.hystrix.config.HystrixConfigurationStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.when;
public class HystrixSampleSseServletTest {
private static final String INTERJECTED_CHARACTER = "a";
@Mock HttpServletRequest mockReq;
@Mock HttpServletResponse mockResp;
@Mock HystrixConfiguration mockConfig;
@Mock PrintWriter mockPrintWriter;
TestHystrixConfigSseServlet servlet;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
@After
public void tearDown() {
servlet.destroy();
servlet.shutdown();
}
@Test
public void testNoConcurrentResponseWrites() throws IOException, InterruptedException {
final Observable<HystrixConfiguration> limitedOnNexts = Observable.create(new Observable.OnSubscribe<HystrixConfiguration>() {
@Override
public void call(Subscriber<? super HystrixConfiguration> subscriber) {
try {
for (int i = 0; i < 500; i++) {
Thread.sleep(10);
subscriber.onNext(mockConfig);
}
} catch (InterruptedException ex) {
ex.printStackTrace();
} catch (Exception e) {
subscriber.onCompleted();
}
}
}).subscribeOn(Schedulers.computation());
servlet = new TestHystrixConfigSseServlet(limitedOnNexts, 1);
try {
servlet.init();
} catch (ServletException ex) {
}
final StringBuilder buffer = new StringBuilder();
when(mockReq.getParameter("delay")).thenReturn("100");
when(mockResp.getWriter()).thenReturn(mockPrintWriter);
Mockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
String written = (String) invocation.getArguments()[0];
if (written.contains("ping")) {
buffer.append(INTERJECTED_CHARACTER);
} else {
// slow down the append to increase chances to interleave
for (int i = 0; i < written.length(); i++) {
Thread.sleep(5);
buffer.append(written.charAt(i));
}
}
return null;
}
}).when(mockPrintWriter).print(Mockito.anyString());
Runnable simulateClient = new Runnable() {
@Override
public void run() {
try {
servlet.doGet(mockReq, mockResp);
} catch (ServletException ex) {
fail(ex.getMessage());
} catch (IOException ex) {
fail(ex.getMessage());
}
}
};
Thread t = new Thread(simulateClient);
t.start();
try {
Thread.sleep(1000);
System.out.println(System.currentTimeMillis() + " Woke up from sleep : " + Thread.currentThread().getName());
} catch (InterruptedException ex) {
fail(ex.getMessage());
}
Pattern pattern = Pattern.compile("\\{[" + INTERJECTED_CHARACTER + "]+\\}");
boolean hasInterleaved = pattern.matcher(buffer).find();
assertFalse(hasInterleaved);
}
private static class TestHystrixConfigSseServlet extends HystrixSampleSseServlet {
private static AtomicInteger concurrentConnections = new AtomicInteger(0);
private static DynamicIntProperty maxConcurrentConnections = DynamicPropertyFactory.getInstance().getIntProperty("hystrix.config.stream.maxConcurrentConnections", 5);
public TestHystrixConfigSseServlet() {
this(HystrixConfigurationStream.getInstance().observe(), DEFAULT_PAUSE_POLLER_THREAD_DELAY_IN_MS);
}
TestHystrixConfigSseServlet(Observable<HystrixConfiguration> sampleStream, int pausePollerThreadDelayInMs) {
super(sampleStream.map(new Func1<HystrixConfiguration, String>() {
@Override
public String call(HystrixConfiguration hystrixConfiguration) {
return "{}";
}
}), pausePollerThreadDelayInMs);
}
@Override
protected int getMaxNumberConcurrentConnectionsAllowed() {
return maxConcurrentConnections.get();
}
@Override
protected int getNumberCurrentConnections() {
return concurrentConnections.get();
}
@Override
protected int incrementAndGetCurrentConcurrentConnections() {
return concurrentConnections.incrementAndGet();
}
@Override
protected void decrementCurrentConcurrentConnections() {
concurrentConnections.decrementAndGet();
}
}
}
| 4,524 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/test/java/com/netflix/hystrix/contrib/sample | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/test/java/com/netflix/hystrix/contrib/sample/stream/HystrixConfigSseServletTest.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.hystrix.contrib.sample.stream;
import com.netflix.hystrix.config.HystrixConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class HystrixConfigSseServletTest {
@Mock HttpServletRequest mockReq;
@Mock HttpServletResponse mockResp;
@Mock HystrixConfiguration mockConfig;
@Mock PrintWriter mockPrintWriter;
HystrixConfigSseServlet servlet;
private final Observable<HystrixConfiguration> streamOfOnNexts = Observable.interval(100, TimeUnit.MILLISECONDS).map(new Func1<Long, HystrixConfiguration>() {
@Override
public HystrixConfiguration call(Long timestamp) {
return mockConfig;
}
});
private final Observable<HystrixConfiguration> streamOfOnNextThenOnError = Observable.create(new Observable.OnSubscribe<HystrixConfiguration>() {
@Override
public void call(Subscriber<? super HystrixConfiguration> subscriber) {
try {
Thread.sleep(100);
subscriber.onNext(mockConfig);
Thread.sleep(100);
subscriber.onError(new RuntimeException("stream failure"));
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}).subscribeOn(Schedulers.computation());
private final Observable<HystrixConfiguration> streamOfOnNextThenOnCompleted = Observable.create(new Observable.OnSubscribe<HystrixConfiguration>() {
@Override
public void call(Subscriber<? super HystrixConfiguration> subscriber) {
try {
Thread.sleep(100);
subscriber.onNext(mockConfig);
Thread.sleep(100);
subscriber.onCompleted();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}).subscribeOn(Schedulers.computation());
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
@After
public void tearDown() {
servlet.destroy();
servlet.shutdown();
}
@Test
public void shutdownServletShouldRejectRequests() throws ServletException, IOException {
servlet = new HystrixConfigSseServlet(streamOfOnNexts, 10);
try {
servlet.init();
} catch (ServletException ex) {
}
servlet.shutdown();
servlet.doGet(mockReq, mockResp);
verify(mockResp).sendError(503, "Service has been shut down.");
}
@Test
public void testConfigDataWithInfiniteOnNextStream() throws IOException, InterruptedException {
servlet = new HystrixConfigSseServlet(streamOfOnNexts, 10);
try {
servlet.init();
} catch (ServletException ex) {
}
final AtomicInteger writes = new AtomicInteger(0);
when(mockReq.getParameter("delay")).thenReturn("100");
when(mockResp.getWriter()).thenReturn(mockPrintWriter);
Mockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
String written = (String) invocation.getArguments()[0];
System.out.println("ARG : " + written);
if (!written.contains("ping")) {
writes.incrementAndGet();
}
return null;
}
}).when(mockPrintWriter).print(Mockito.anyString());
Runnable simulateClient = new Runnable() {
@Override
public void run() {
try {
servlet.doGet(mockReq, mockResp);
} catch (ServletException ex) {
fail(ex.getMessage());
} catch (IOException ex) {
fail(ex.getMessage());
}
}
};
Thread t = new Thread(simulateClient);
System.out.println("Starting thread : " + t.getName());
t.start();
System.out.println("Started thread : " + t.getName());
try {
Thread.sleep(1000);
System.out.println("Woke up from sleep : " + Thread.currentThread().getName());
} catch (InterruptedException ex) {
fail(ex.getMessage());
}
System.out.println("About to interrupt");
t.interrupt();
System.out.println("Done interrupting");
Thread.sleep(100);
System.out.println("WRITES : " + writes.get());
assertTrue(writes.get() >= 9);
assertEquals(0, servlet.getNumberCurrentConnections());
}
@Test
public void testConfigDataWithStreamOnError() throws IOException, InterruptedException {
servlet = new HystrixConfigSseServlet(streamOfOnNextThenOnError, 10);
try {
servlet.init();
} catch (ServletException ex) {
}
final AtomicInteger writes = new AtomicInteger(0);
when(mockReq.getParameter("delay")).thenReturn("100");
when(mockResp.getWriter()).thenReturn(mockPrintWriter);
Mockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
String written = (String) invocation.getArguments()[0];
System.out.println("ARG : " + written);
if (!written.contains("ping")) {
writes.incrementAndGet();
}
return null;
}
}).when(mockPrintWriter).print(Mockito.anyString());
Runnable simulateClient = new Runnable() {
@Override
public void run() {
try {
servlet.doGet(mockReq, mockResp);
} catch (ServletException ex) {
fail(ex.getMessage());
} catch (IOException ex) {
fail(ex.getMessage());
}
}
};
Thread t = new Thread(simulateClient);
t.start();
try {
Thread.sleep(1000);
System.out.println(System.currentTimeMillis() + " Woke up from sleep : " + Thread.currentThread().getName());
} catch (InterruptedException ex) {
fail(ex.getMessage());
}
assertEquals(1, writes.get());
assertEquals(0, servlet.getNumberCurrentConnections());
}
@Test
public void testConfigDataWithStreamOnCompleted() throws IOException, InterruptedException {
servlet = new HystrixConfigSseServlet(streamOfOnNextThenOnCompleted, 10);
try {
servlet.init();
} catch (ServletException ex) {
}
final AtomicInteger writes = new AtomicInteger(0);
when(mockReq.getParameter("delay")).thenReturn("100");
when(mockResp.getWriter()).thenReturn(mockPrintWriter);
Mockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
String written = (String) invocation.getArguments()[0];
System.out.println("ARG : " + written);
if (!written.contains("ping")) {
writes.incrementAndGet();
}
return null;
}
}).when(mockPrintWriter).print(Mockito.anyString());
Runnable simulateClient = new Runnable() {
@Override
public void run() {
try {
servlet.doGet(mockReq, mockResp);
} catch (ServletException ex) {
fail(ex.getMessage());
} catch (IOException ex) {
fail(ex.getMessage());
}
}
};
Thread t = new Thread(simulateClient);
t.start();
try {
Thread.sleep(1000);
System.out.println(System.currentTimeMillis() + " Woke up from sleep : " + Thread.currentThread().getName());
} catch (InterruptedException ex) {
fail(ex.getMessage());
}
assertEquals(1, writes.get());
assertEquals(0, servlet.getNumberCurrentConnections());
}
@Test
public void testConfigDataWithIoExceptionOnWrite() throws IOException, InterruptedException {
servlet = new HystrixConfigSseServlet(streamOfOnNexts, 10);
try {
servlet.init();
} catch (ServletException ex) {
}
final AtomicInteger writes = new AtomicInteger(0);
when(mockResp.getWriter()).thenReturn(mockPrintWriter);
Mockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
String written = (String) invocation.getArguments()[0];
System.out.println("ARG : " + written);
if (!written.contains("ping")) {
writes.incrementAndGet();
}
throw new IOException("simulated IO Exception");
}
}).when(mockPrintWriter).print(Mockito.anyString());
Runnable simulateClient = new Runnable() {
@Override
public void run() {
try {
servlet.doGet(mockReq, mockResp);
} catch (ServletException ex) {
fail(ex.getMessage());
} catch (IOException ex) {
fail(ex.getMessage());
}
}
};
Thread t = new Thread(simulateClient);
t.start();
try {
Thread.sleep(1000);
System.out.println(System.currentTimeMillis() + " Woke up from sleep : " + Thread.currentThread().getName());
} catch (InterruptedException ex) {
fail(ex.getMessage());
}
assertTrue(writes.get() <= 2);
assertEquals(0, servlet.getNumberCurrentConnections());
}
}
| 4,525 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/main/java/com/netflix/hystrix/contrib/metrics | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/main/java/com/netflix/hystrix/contrib/metrics/eventstream/HystrixMetricsPoller.java | /**
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.metrics.eventstream;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.netflix.hystrix.HystrixCircuitBreaker;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserMetrics;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandMetrics;
import com.netflix.hystrix.HystrixCommandMetrics.HealthCounts;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolMetrics;
import com.netflix.hystrix.util.PlatformSpecific;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.functions.Func0;
import java.io.IOException;
import java.io.StringWriter;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Polls Hystrix metrics and output JSON strings for each metric to a MetricsPollerListener.
* <p>
* Polling can be stopped/started. Use shutdown() to permanently shutdown the poller.
*
* An implementation note. If there's a version mismatch between hystrix-core and hystrix-metrics-event-stream,
* the code below may reference a HystrixEventType that does not exist in hystrix-core. If this happens,
* a j.l.NoSuchFieldError occurs. Since this data is not being generated by hystrix-core, it's safe to count it as 0
* and we should log an error to get users to update their dependency set.
*
* @deprecated Prefer {@link com.netflix.hystrix.metric.consumer.HystrixDashboardStream}
*/
@Deprecated //since 1.5.4
public class HystrixMetricsPoller {
static final Logger logger = LoggerFactory.getLogger(HystrixMetricsPoller.class);
private final ScheduledExecutorService executor;
private final int delay;
private final AtomicBoolean running = new AtomicBoolean(false);
private volatile ScheduledFuture<?> scheduledTask = null;
private final MetricsAsJsonPollerListener listener;
/**
* Allocate resources to begin polling.
* <p>
* Use <code>start</code> to begin polling.
* <p>
* Use <code>shutdown</code> to cleanup resources and stop polling.
* <p>
* Use <code>pause</code> to temporarily stop polling that can be restarted again with <code>start</code>.
*
* @param listener for callbacks
* @param delay
*/
public HystrixMetricsPoller(MetricsAsJsonPollerListener listener, int delay) {
this.listener = listener;
ThreadFactory threadFactory = null;
if (!PlatformSpecific.isAppEngineStandardEnvironment()) {
threadFactory = new MetricsPollerThreadFactory();
} else {
threadFactory = PlatformSpecific.getAppEngineThreadFactory();
}
executor = new ScheduledThreadPoolExecutor(1, threadFactory);
this.delay = delay;
}
/**
* Start polling.
*/
public synchronized void start() {
// use compareAndSet to make sure it starts only once and when not running
if (running.compareAndSet(false, true)) {
logger.debug("Starting HystrixMetricsPoller");
try {
scheduledTask = executor.scheduleWithFixedDelay(new MetricsPoller(listener), 0, delay, TimeUnit.MILLISECONDS);
} catch (Throwable ex) {
logger.error("Exception while creating the MetricsPoller task");
ex.printStackTrace();
running.set(false);
}
}
}
/**
* Pause (stop) polling. Polling can be started again with <code>start</code> as long as <code>shutdown</code> is not called.
*/
public synchronized void pause() {
// use compareAndSet to make sure it stops only once and when running
if (running.compareAndSet(true, false)) {
logger.debug("Stopping the HystrixMetricsPoller");
scheduledTask.cancel(true);
} else {
logger.debug("Attempted to pause a stopped poller");
}
}
/**
* Stops polling and shuts down the ExecutorService.
* <p>
* This instance can no longer be used after calling shutdown.
*/
public synchronized void shutdown() {
pause();
executor.shutdown();
}
public boolean isRunning() {
return running.get();
}
/**
* Used to protect against leaking ExecutorServices and threads if this class is abandoned for GC without shutting down.
*/
@SuppressWarnings("unused")
private final Object finalizerGuardian = new Object() {
protected void finalize() throws Throwable {
if (!executor.isShutdown()) {
logger.warn("{} was not shutdown. Caught in Finalize Guardian and shutting down.", HystrixMetricsPoller.class.getSimpleName());
try {
shutdown();
} catch (Exception e) {
logger.error("Failed to shutdown {}", HystrixMetricsPoller.class.getSimpleName(), e);
}
}
};
};
public static interface MetricsAsJsonPollerListener {
public void handleJsonMetric(String json);
}
private class MetricsPoller implements Runnable {
private final MetricsAsJsonPollerListener listener;
private final JsonFactory jsonFactory = new JsonFactory();
public MetricsPoller(MetricsAsJsonPollerListener listener) {
this.listener = listener;
}
@Override
public void run() {
try {
for (HystrixCommandMetrics commandMetrics : HystrixCommandMetrics.getInstances()) {
String jsonString = getCommandJson(commandMetrics);
listener.handleJsonMetric(jsonString);
}
for (HystrixThreadPoolMetrics threadPoolMetrics : HystrixThreadPoolMetrics.getInstances()) {
if (hasExecutedCommandsOnThread(threadPoolMetrics)) {
String jsonString = getThreadPoolJson(threadPoolMetrics);
listener.handleJsonMetric(jsonString);
}
}
for (HystrixCollapserMetrics collapserMetrics : HystrixCollapserMetrics.getInstances()) {
String jsonString = getCollapserJson(collapserMetrics);
listener.handleJsonMetric(jsonString);
}
} catch (Exception e) {
logger.warn("Failed to output metrics as JSON", e);
// shutdown
pause();
return;
}
}
private void safelyWriteNumberField(JsonGenerator json, String name, Func0<Long> metricGenerator) throws IOException {
try {
json.writeNumberField(name, metricGenerator.call());
} catch (NoSuchFieldError error) {
logger.error("While publishing Hystrix metrics stream, error looking up eventType for : {}. Please check that all Hystrix versions are the same!", name);
json.writeNumberField(name, 0L);
}
}
private String getCommandJson(final HystrixCommandMetrics commandMetrics) throws IOException {
HystrixCommandKey key = commandMetrics.getCommandKey();
HystrixCircuitBreaker circuitBreaker = HystrixCircuitBreaker.Factory.getInstance(key);
StringWriter jsonString = new StringWriter();
JsonGenerator json = jsonFactory.createGenerator(jsonString);
json.writeStartObject();
json.writeStringField("type", "HystrixCommand");
json.writeStringField("name", key.name());
json.writeStringField("group", commandMetrics.getCommandGroup().name());
json.writeNumberField("currentTime", System.currentTimeMillis());
// circuit breaker
if (circuitBreaker == null) {
// circuit breaker is disabled and thus never open
json.writeBooleanField("isCircuitBreakerOpen", false);
} else {
json.writeBooleanField("isCircuitBreakerOpen", circuitBreaker.isOpen());
}
HealthCounts healthCounts = commandMetrics.getHealthCounts();
json.writeNumberField("errorPercentage", healthCounts.getErrorPercentage());
json.writeNumberField("errorCount", healthCounts.getErrorCount());
json.writeNumberField("requestCount", healthCounts.getTotalRequests());
// rolling counters
safelyWriteNumberField(json, "rollingCountBadRequests", new Func0<Long>() {
@Override
public Long call() {
return commandMetrics.getRollingCount(HystrixEventType.BAD_REQUEST);
}
});
safelyWriteNumberField(json, "rollingCountCollapsedRequests", new Func0<Long>() {
@Override
public Long call() {
return commandMetrics.getRollingCount(HystrixEventType.COLLAPSED);
}
});
safelyWriteNumberField(json, "rollingCountEmit", new Func0<Long>() {
@Override
public Long call() {
return commandMetrics.getRollingCount(HystrixEventType.EMIT);
}
});
safelyWriteNumberField(json, "rollingCountExceptionsThrown", new Func0<Long>() {
@Override
public Long call() {
return commandMetrics.getRollingCount(HystrixEventType.EXCEPTION_THROWN);
}
});
safelyWriteNumberField(json, "rollingCountFailure", new Func0<Long>() {
@Override
public Long call() {
return commandMetrics.getRollingCount(HystrixEventType.FAILURE);
}
});
safelyWriteNumberField(json, "rollingCountFallbackEmit", new Func0<Long>() {
@Override
public Long call() {
return commandMetrics.getRollingCount(HystrixEventType.FALLBACK_EMIT);
}
});
safelyWriteNumberField(json, "rollingCountFallbackFailure", new Func0<Long>() {
@Override
public Long call() {
return commandMetrics.getRollingCount(HystrixEventType.FALLBACK_FAILURE);
}
});
safelyWriteNumberField(json, "rollingCountFallbackMissing", new Func0<Long>() {
@Override
public Long call() {
return commandMetrics.getRollingCount(HystrixEventType.FALLBACK_MISSING);
}
});
safelyWriteNumberField(json, "rollingCountFallbackRejection", new Func0<Long>() {
@Override
public Long call() {
return commandMetrics.getRollingCount(HystrixEventType.FALLBACK_REJECTION);
}
});
safelyWriteNumberField(json, "rollingCountFallbackSuccess", new Func0<Long>() {
@Override
public Long call() {
return commandMetrics.getRollingCount(HystrixEventType.FALLBACK_SUCCESS);
}
});
safelyWriteNumberField(json, "rollingCountResponsesFromCache", new Func0<Long>() {
@Override
public Long call() {
return commandMetrics.getRollingCount(HystrixEventType.RESPONSE_FROM_CACHE);
}
});
safelyWriteNumberField(json, "rollingCountSemaphoreRejected", new Func0<Long>() {
@Override
public Long call() {
return commandMetrics.getRollingCount(HystrixEventType.SEMAPHORE_REJECTED);
}
});
safelyWriteNumberField(json, "rollingCountShortCircuited", new Func0<Long>() {
@Override
public Long call() {
return commandMetrics.getRollingCount(HystrixEventType.SHORT_CIRCUITED);
}
});
safelyWriteNumberField(json, "rollingCountSuccess", new Func0<Long>() {
@Override
public Long call() {
return commandMetrics.getRollingCount(HystrixEventType.SUCCESS);
}
});
safelyWriteNumberField(json, "rollingCountThreadPoolRejected", new Func0<Long>() {
@Override
public Long call() {
return commandMetrics.getRollingCount(HystrixEventType.THREAD_POOL_REJECTED);
}
});
safelyWriteNumberField(json, "rollingCountTimeout", new Func0<Long>() {
@Override
public Long call() {
return commandMetrics.getRollingCount(HystrixEventType.TIMEOUT);
}
});
json.writeNumberField("currentConcurrentExecutionCount", commandMetrics.getCurrentConcurrentExecutionCount());
json.writeNumberField("rollingMaxConcurrentExecutionCount", commandMetrics.getRollingMaxConcurrentExecutions());
// latency percentiles
json.writeNumberField("latencyExecute_mean", commandMetrics.getExecutionTimeMean());
json.writeObjectFieldStart("latencyExecute");
json.writeNumberField("0", commandMetrics.getExecutionTimePercentile(0));
json.writeNumberField("25", commandMetrics.getExecutionTimePercentile(25));
json.writeNumberField("50", commandMetrics.getExecutionTimePercentile(50));
json.writeNumberField("75", commandMetrics.getExecutionTimePercentile(75));
json.writeNumberField("90", commandMetrics.getExecutionTimePercentile(90));
json.writeNumberField("95", commandMetrics.getExecutionTimePercentile(95));
json.writeNumberField("99", commandMetrics.getExecutionTimePercentile(99));
json.writeNumberField("99.5", commandMetrics.getExecutionTimePercentile(99.5));
json.writeNumberField("100", commandMetrics.getExecutionTimePercentile(100));
json.writeEndObject();
//
json.writeNumberField("latencyTotal_mean", commandMetrics.getTotalTimeMean());
json.writeObjectFieldStart("latencyTotal");
json.writeNumberField("0", commandMetrics.getTotalTimePercentile(0));
json.writeNumberField("25", commandMetrics.getTotalTimePercentile(25));
json.writeNumberField("50", commandMetrics.getTotalTimePercentile(50));
json.writeNumberField("75", commandMetrics.getTotalTimePercentile(75));
json.writeNumberField("90", commandMetrics.getTotalTimePercentile(90));
json.writeNumberField("95", commandMetrics.getTotalTimePercentile(95));
json.writeNumberField("99", commandMetrics.getTotalTimePercentile(99));
json.writeNumberField("99.5", commandMetrics.getTotalTimePercentile(99.5));
json.writeNumberField("100", commandMetrics.getTotalTimePercentile(100));
json.writeEndObject();
// property values for reporting what is actually seen by the command rather than what was set somewhere
HystrixCommandProperties commandProperties = commandMetrics.getProperties();
json.writeNumberField("propertyValue_circuitBreakerRequestVolumeThreshold", commandProperties.circuitBreakerRequestVolumeThreshold().get());
json.writeNumberField("propertyValue_circuitBreakerSleepWindowInMilliseconds", commandProperties.circuitBreakerSleepWindowInMilliseconds().get());
json.writeNumberField("propertyValue_circuitBreakerErrorThresholdPercentage", commandProperties.circuitBreakerErrorThresholdPercentage().get());
json.writeBooleanField("propertyValue_circuitBreakerForceOpen", commandProperties.circuitBreakerForceOpen().get());
json.writeBooleanField("propertyValue_circuitBreakerForceClosed", commandProperties.circuitBreakerForceClosed().get());
json.writeBooleanField("propertyValue_circuitBreakerEnabled", commandProperties.circuitBreakerEnabled().get());
json.writeStringField("propertyValue_executionIsolationStrategy", commandProperties.executionIsolationStrategy().get().name());
json.writeNumberField("propertyValue_executionIsolationThreadTimeoutInMilliseconds", commandProperties.executionTimeoutInMilliseconds().get());
json.writeNumberField("propertyValue_executionTimeoutInMilliseconds", commandProperties.executionTimeoutInMilliseconds().get());
json.writeBooleanField("propertyValue_executionIsolationThreadInterruptOnTimeout", commandProperties.executionIsolationThreadInterruptOnTimeout().get());
json.writeStringField("propertyValue_executionIsolationThreadPoolKeyOverride", commandProperties.executionIsolationThreadPoolKeyOverride().get());
json.writeNumberField("propertyValue_executionIsolationSemaphoreMaxConcurrentRequests", commandProperties.executionIsolationSemaphoreMaxConcurrentRequests().get());
json.writeNumberField("propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests", commandProperties.fallbackIsolationSemaphoreMaxConcurrentRequests().get());
/*
* The following are commented out as these rarely change and are verbose for streaming for something people don't change.
* We could perhaps allow a property or request argument to include these.
*/
// json.put("propertyValue_metricsRollingPercentileEnabled", commandProperties.metricsRollingPercentileEnabled().get());
// json.put("propertyValue_metricsRollingPercentileBucketSize", commandProperties.metricsRollingPercentileBucketSize().get());
// json.put("propertyValue_metricsRollingPercentileWindow", commandProperties.metricsRollingPercentileWindowInMilliseconds().get());
// json.put("propertyValue_metricsRollingPercentileWindowBuckets", commandProperties.metricsRollingPercentileWindowBuckets().get());
// json.put("propertyValue_metricsRollingStatisticalWindowBuckets", commandProperties.metricsRollingStatisticalWindowBuckets().get());
json.writeNumberField("propertyValue_metricsRollingStatisticalWindowInMilliseconds", commandProperties.metricsRollingStatisticalWindowInMilliseconds().get());
json.writeBooleanField("propertyValue_requestCacheEnabled", commandProperties.requestCacheEnabled().get());
json.writeBooleanField("propertyValue_requestLogEnabled", commandProperties.requestLogEnabled().get());
json.writeNumberField("reportingHosts", 1); // this will get summed across all instances in a cluster
json.writeStringField("threadPool", commandMetrics.getThreadPoolKey().name());
json.writeEndObject();
json.close();
return jsonString.getBuffer().toString();
}
private boolean hasExecutedCommandsOnThread(HystrixThreadPoolMetrics threadPoolMetrics) {
return threadPoolMetrics.getCurrentCompletedTaskCount().intValue() > 0;
}
private String getThreadPoolJson(final HystrixThreadPoolMetrics threadPoolMetrics) throws IOException {
HystrixThreadPoolKey key = threadPoolMetrics.getThreadPoolKey();
StringWriter jsonString = new StringWriter();
JsonGenerator json = jsonFactory.createJsonGenerator(jsonString);
json.writeStartObject();
json.writeStringField("type", "HystrixThreadPool");
json.writeStringField("name", key.name());
json.writeNumberField("currentTime", System.currentTimeMillis());
json.writeNumberField("currentActiveCount", threadPoolMetrics.getCurrentActiveCount().intValue());
json.writeNumberField("currentCompletedTaskCount", threadPoolMetrics.getCurrentCompletedTaskCount().longValue());
json.writeNumberField("currentCorePoolSize", threadPoolMetrics.getCurrentCorePoolSize().intValue());
json.writeNumberField("currentLargestPoolSize", threadPoolMetrics.getCurrentLargestPoolSize().intValue());
json.writeNumberField("currentMaximumPoolSize", threadPoolMetrics.getCurrentMaximumPoolSize().intValue());
json.writeNumberField("currentPoolSize", threadPoolMetrics.getCurrentPoolSize().intValue());
json.writeNumberField("currentQueueSize", threadPoolMetrics.getCurrentQueueSize().intValue());
json.writeNumberField("currentTaskCount", threadPoolMetrics.getCurrentTaskCount().longValue());
safelyWriteNumberField(json, "rollingCountThreadsExecuted", new Func0<Long>() {
@Override
public Long call() {
return threadPoolMetrics.getRollingCount(HystrixEventType.ThreadPool.EXECUTED);
}
});
json.writeNumberField("rollingMaxActiveThreads", threadPoolMetrics.getRollingMaxActiveThreads());
safelyWriteNumberField(json, "rollingCountCommandRejections", new Func0<Long>() {
@Override
public Long call() {
return threadPoolMetrics.getRollingCount(HystrixEventType.ThreadPool.REJECTED);
}
});
json.writeNumberField("propertyValue_queueSizeRejectionThreshold", threadPoolMetrics.getProperties().queueSizeRejectionThreshold().get());
json.writeNumberField("propertyValue_metricsRollingStatisticalWindowInMilliseconds", threadPoolMetrics.getProperties().metricsRollingStatisticalWindowInMilliseconds().get());
json.writeNumberField("reportingHosts", 1); // this will get summed across all instances in a cluster
json.writeEndObject();
json.close();
return jsonString.getBuffer().toString();
}
private String getCollapserJson(final HystrixCollapserMetrics collapserMetrics) throws IOException {
HystrixCollapserKey key = collapserMetrics.getCollapserKey();
StringWriter jsonString = new StringWriter();
JsonGenerator json = jsonFactory.createJsonGenerator(jsonString);
json.writeStartObject();
json.writeStringField("type", "HystrixCollapser");
json.writeStringField("name", key.name());
json.writeNumberField("currentTime", System.currentTimeMillis());
safelyWriteNumberField(json, "rollingCountRequestsBatched", new Func0<Long>() {
@Override
public Long call() {
return collapserMetrics.getRollingCount(HystrixEventType.Collapser.ADDED_TO_BATCH);
}
});
safelyWriteNumberField(json, "rollingCountBatches", new Func0<Long>() {
@Override
public Long call() {
return collapserMetrics.getRollingCount(HystrixEventType.Collapser.BATCH_EXECUTED);
}
});
safelyWriteNumberField(json, "rollingCountResponsesFromCache", new Func0<Long>() {
@Override
public Long call() {
return collapserMetrics.getRollingCount(HystrixEventType.Collapser.RESPONSE_FROM_CACHE);
}
});
// batch size percentiles
json.writeNumberField("batchSize_mean", collapserMetrics.getBatchSizeMean());
json.writeObjectFieldStart("batchSize");
json.writeNumberField("25", collapserMetrics.getBatchSizePercentile(25));
json.writeNumberField("50", collapserMetrics.getBatchSizePercentile(50));
json.writeNumberField("75", collapserMetrics.getBatchSizePercentile(75));
json.writeNumberField("90", collapserMetrics.getBatchSizePercentile(90));
json.writeNumberField("95", collapserMetrics.getBatchSizePercentile(95));
json.writeNumberField("99", collapserMetrics.getBatchSizePercentile(99));
json.writeNumberField("99.5", collapserMetrics.getBatchSizePercentile(99.5));
json.writeNumberField("100", collapserMetrics.getBatchSizePercentile(100));
json.writeEndObject();
// shard size percentiles (commented-out for now)
//json.writeNumberField("shardSize_mean", collapserMetrics.getShardSizeMean());
//json.writeObjectFieldStart("shardSize");
//json.writeNumberField("25", collapserMetrics.getShardSizePercentile(25));
//json.writeNumberField("50", collapserMetrics.getShardSizePercentile(50));
//json.writeNumberField("75", collapserMetrics.getShardSizePercentile(75));
//json.writeNumberField("90", collapserMetrics.getShardSizePercentile(90));
//json.writeNumberField("95", collapserMetrics.getShardSizePercentile(95));
//json.writeNumberField("99", collapserMetrics.getShardSizePercentile(99));
//json.writeNumberField("99.5", collapserMetrics.getShardSizePercentile(99.5));
//json.writeNumberField("100", collapserMetrics.getShardSizePercentile(100));
//json.writeEndObject();
//json.writeNumberField("propertyValue_metricsRollingStatisticalWindowInMilliseconds", collapserMetrics.getProperties().metricsRollingStatisticalWindowInMilliseconds().get());
json.writeBooleanField("propertyValue_requestCacheEnabled", collapserMetrics.getProperties().requestCacheEnabled().get());
json.writeNumberField("propertyValue_maxRequestsInBatch", collapserMetrics.getProperties().maxRequestsInBatch().get());
json.writeNumberField("propertyValue_timerDelayInMilliseconds", collapserMetrics.getProperties().timerDelayInMilliseconds().get());
json.writeNumberField("reportingHosts", 1); // this will get summed across all instances in a cluster
json.writeEndObject();
json.close();
return jsonString.getBuffer().toString();
}
}
private static class MetricsPollerThreadFactory implements ThreadFactory {
private static final String MetricsThreadName = "HystrixMetricPoller";
private final ThreadFactory defaultFactory = Executors.defaultThreadFactory();
public Thread newThread(Runnable r) {
Thread thread = defaultFactory.newThread(r);
thread.setName(MetricsThreadName);
thread.setDaemon(true);
return thread;
}
}
}
| 4,526 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/main/java/com/netflix/hystrix/contrib/metrics | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/main/java/com/netflix/hystrix/contrib/metrics/eventstream/HystrixMetricsStreamServlet.java | /**
* Copyright 2012 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.metrics.eventstream;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.hystrix.contrib.sample.stream.HystrixSampleSseServlet;
import com.netflix.hystrix.metric.consumer.HystrixDashboardStream;
import com.netflix.hystrix.serial.SerialHystrixDashboardData;
import rx.Observable;
import rx.functions.Func1;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Streams Hystrix metrics in text/event-stream format.
* <p>
* Install by:
* <p>
* 1) Including hystrix-metrics-event-stream-*.jar in your classpath.
* <p>
* 2) Adding the following to web.xml:
* <pre>{@code
* <servlet>
* <description></description>
* <display-name>HystrixMetricsStreamServlet</display-name>
* <servlet-name>HystrixMetricsStreamServlet</servlet-name>
* <servlet-class>com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet</servlet-class>
* </servlet>
* <servlet-mapping>
* <servlet-name>HystrixMetricsStreamServlet</servlet-name>
* <url-pattern>/hystrix.stream</url-pattern>
* </servlet-mapping>
* } </pre>
*/
public class HystrixMetricsStreamServlet extends HystrixSampleSseServlet {
private static final long serialVersionUID = -7548505095303313237L;
/* used to track number of connections and throttle */
private static AtomicInteger concurrentConnections = new AtomicInteger(0);
private static DynamicIntProperty maxConcurrentConnections =
DynamicPropertyFactory.getInstance().getIntProperty("hystrix.config.stream.maxConcurrentConnections", 5);
public HystrixMetricsStreamServlet() {
this(HystrixDashboardStream.getInstance().observe(), DEFAULT_PAUSE_POLLER_THREAD_DELAY_IN_MS);
}
/* package-private */ HystrixMetricsStreamServlet(Observable<HystrixDashboardStream.DashboardData> sampleStream, int pausePollerThreadDelayInMs) {
super(sampleStream.concatMap(new Func1<HystrixDashboardStream.DashboardData, Observable<String>>() {
@Override
public Observable<String> call(HystrixDashboardStream.DashboardData dashboardData) {
return Observable.from(SerialHystrixDashboardData.toMultipleJsonStrings(dashboardData));
}
}), pausePollerThreadDelayInMs);
}
@Override
protected int getMaxNumberConcurrentConnectionsAllowed() {
return maxConcurrentConnections.get();
}
@Override
protected int getNumberCurrentConnections() {
return concurrentConnections.get();
}
@Override
protected int incrementAndGetCurrentConcurrentConnections() {
return concurrentConnections.incrementAndGet();
}
@Override
protected void decrementCurrentConcurrentConnections() {
concurrentConnections.decrementAndGet();
}
}
| 4,527 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/main/java/com/netflix/hystrix/contrib/requests | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/main/java/com/netflix/hystrix/contrib/requests/stream/HystrixRequestEventsSseServlet.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.hystrix.contrib.requests.stream;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.hystrix.contrib.sample.stream.HystrixSampleSseServlet;
import com.netflix.hystrix.metric.HystrixRequestEvents;
import com.netflix.hystrix.metric.HystrixRequestEventsStream;
import com.netflix.hystrix.serial.SerialHystrixRequestEvents;
import rx.Observable;
import rx.functions.Func1;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Servlet that writes SSE JSON every time a request is made
*/
public class HystrixRequestEventsSseServlet extends HystrixSampleSseServlet {
private static final long serialVersionUID = 6389353893099737870L;
/* used to track number of connections and throttle */
private static AtomicInteger concurrentConnections = new AtomicInteger(0);
private static DynamicIntProperty maxConcurrentConnections =
DynamicPropertyFactory.getInstance().getIntProperty("hystrix.config.stream.maxConcurrentConnections", 5);
public HystrixRequestEventsSseServlet() {
this(HystrixRequestEventsStream.getInstance().observe(), DEFAULT_PAUSE_POLLER_THREAD_DELAY_IN_MS);
}
/* package-private */ HystrixRequestEventsSseServlet(Observable<HystrixRequestEvents> sampleStream, int pausePollerThreadDelayInMs) {
super(sampleStream.map(new Func1<HystrixRequestEvents, String>() {
@Override
public String call(HystrixRequestEvents requestEvents) {
return SerialHystrixRequestEvents.toJsonString(requestEvents);
}
}), pausePollerThreadDelayInMs);
}
@Override
protected int getMaxNumberConcurrentConnectionsAllowed() {
return maxConcurrentConnections.get();
}
@Override
protected int getNumberCurrentConnections() {
return concurrentConnections.get();
}
@Override
protected int incrementAndGetCurrentConcurrentConnections() {
return concurrentConnections.incrementAndGet();
}
@Override
protected void decrementCurrentConcurrentConnections() {
concurrentConnections.decrementAndGet();
}
}
| 4,528 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/main/java/com/netflix/hystrix/contrib/requests | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/main/java/com/netflix/hystrix/contrib/requests/stream/HystrixRequestEventsJsonStream.java | /**
* Copyright 2016 Netflix, Inc.
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.requests.stream;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.netflix.hystrix.ExecutionResult;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.metric.HystrixRequestEvents;
import com.netflix.hystrix.metric.HystrixRequestEventsStream;
import rx.Observable;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* Stream that converts HystrixRequestEvents into JSON. This isn't needed anymore, as it more straightforward
* to consider serialization completely separately from the domain object stream
*
* @deprecated Instead, prefer mapping your preferred serialization on top of {@link HystrixRequestEventsStream#observe()}.
*/
@Deprecated //since 1.5.4
public class HystrixRequestEventsJsonStream {
private static final JsonFactory jsonFactory = new JsonFactory();
public Observable<HystrixRequestEvents> getStream() {
return HystrixRequestEventsStream.getInstance()
.observe();
}
public static String convertRequestsToJson(Collection<HystrixRequestEvents> requests) throws IOException {
StringWriter jsonString = new StringWriter();
JsonGenerator json = jsonFactory.createGenerator(jsonString);
json.writeStartArray();
for (HystrixRequestEvents request : requests) {
writeRequestAsJson(json, request);
}
json.writeEndArray();
json.close();
return jsonString.getBuffer().toString();
}
public static String convertRequestToJson(HystrixRequestEvents request) throws IOException {
StringWriter jsonString = new StringWriter();
JsonGenerator json = jsonFactory.createGenerator(jsonString);
writeRequestAsJson(json, request);
json.close();
return jsonString.getBuffer().toString();
}
private static void writeRequestAsJson(JsonGenerator json, HystrixRequestEvents request) throws IOException {
json.writeStartArray();
for (Map.Entry<HystrixRequestEvents.ExecutionSignature, List<Integer>> entry: request.getExecutionsMappedToLatencies().entrySet()) {
convertExecutionToJson(json, entry.getKey(), entry.getValue());
}
json.writeEndArray();
}
private static void convertExecutionToJson(JsonGenerator json, HystrixRequestEvents.ExecutionSignature executionSignature, List<Integer> latencies) throws IOException {
json.writeStartObject();
json.writeStringField("name", executionSignature.getCommandName());
json.writeArrayFieldStart("events");
ExecutionResult.EventCounts eventCounts = executionSignature.getEventCounts();
for (HystrixEventType eventType: HystrixEventType.values()) {
if (eventType != HystrixEventType.COLLAPSED) {
if (eventCounts.contains(eventType)) {
int eventCount = eventCounts.getCount(eventType);
if (eventCount > 1) {
json.writeStartObject();
json.writeStringField("name", eventType.name());
json.writeNumberField("count", eventCount);
json.writeEndObject();
} else {
json.writeString(eventType.name());
}
}
}
}
json.writeEndArray();
json.writeArrayFieldStart("latencies");
for (int latency: latencies) {
json.writeNumber(latency);
}
json.writeEndArray();
if (executionSignature.getCachedCount() > 0) {
json.writeNumberField("cached", executionSignature.getCachedCount());
}
if (executionSignature.getEventCounts().contains(HystrixEventType.COLLAPSED)) {
json.writeObjectFieldStart("collapsed");
json.writeStringField("name", executionSignature.getCollapserKey().name());
json.writeNumberField("count", executionSignature.getCollapserBatchSize());
json.writeEndObject();
}
json.writeEndObject();
}
}
| 4,529 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/main/java/com/netflix/hystrix/contrib/sample | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/main/java/com/netflix/hystrix/contrib/sample/stream/HystrixUtilizationSseServlet.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.hystrix.contrib.sample.stream;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.hystrix.metric.sample.HystrixUtilization;
import com.netflix.hystrix.metric.sample.HystrixUtilizationStream;
import com.netflix.hystrix.serial.SerialHystrixUtilization;
import rx.Observable;
import rx.functions.Func1;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Streams Hystrix config in text/event-stream format.
* <p>
* Install by:
* <p>
* 1) Including hystrix-metrics-event-stream-*.jar in your classpath.
* <p>
* 2) Adding the following to web.xml:
* <pre>{@code
* <servlet>
* <description></description>
* <display-name>HystrixUtilizationSseServlet</display-name>
* <servlet-name>HystrixUtilizationSseServlet</servlet-name>
* <servlet-class>com.netflix.hystrix.contrib.sample.stream.HystrixUtilizationSseServlet</servlet-class>
* </servlet>
* <servlet-mapping>
* <servlet-name>HystrixUtilizationSseServlet</servlet-name>
* <url-pattern>/hystrix/utilization.stream</url-pattern>
* </servlet-mapping>
* } </pre>
*/
public class HystrixUtilizationSseServlet extends HystrixSampleSseServlet {
private static final long serialVersionUID = -7812908330777694972L;
/* used to track number of connections and throttle */
private static AtomicInteger concurrentConnections = new AtomicInteger(0);
private static DynamicIntProperty maxConcurrentConnections =
DynamicPropertyFactory.getInstance().getIntProperty("hystrix.config.stream.maxConcurrentConnections", 5);
public HystrixUtilizationSseServlet() {
this(HystrixUtilizationStream.getInstance().observe(), DEFAULT_PAUSE_POLLER_THREAD_DELAY_IN_MS);
}
/* package-private */ HystrixUtilizationSseServlet(Observable<HystrixUtilization> sampleStream, int pausePollerThreadDelayInMs) {
super(sampleStream.map(new Func1<HystrixUtilization, String>() {
@Override
public String call(HystrixUtilization hystrixUtilization) {
return SerialHystrixUtilization.toJsonString(hystrixUtilization);
}
}), pausePollerThreadDelayInMs);
}
@Override
protected int getMaxNumberConcurrentConnectionsAllowed() {
return maxConcurrentConnections.get();
}
@Override
protected int getNumberCurrentConnections() {
return concurrentConnections.get();
}
@Override
protected int incrementAndGetCurrentConcurrentConnections() {
return concurrentConnections.incrementAndGet();
}
@Override
protected void decrementCurrentConcurrentConnections() {
concurrentConnections.decrementAndGet();
}
}
| 4,530 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/main/java/com/netflix/hystrix/contrib/sample | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/main/java/com/netflix/hystrix/contrib/sample/stream/HystrixSampleSseServlet.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.hystrix.contrib.sample.stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.schedulers.Schedulers;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.atomic.AtomicBoolean;
/**
*/
public abstract class HystrixSampleSseServlet extends HttpServlet {
protected final Observable<String> sampleStream;
private static final Logger logger = LoggerFactory.getLogger(HystrixSampleSseServlet.class);
//wake up occasionally and check that poller is still alive. this value controls how often
protected static final int DEFAULT_PAUSE_POLLER_THREAD_DELAY_IN_MS = 500;
private final int pausePollerThreadDelayInMs;
/* response is not thread-safe */
private final Object responseWriteLock = new Object();
/* Set to true upon shutdown, so it's OK to be shared among all SampleSseServlets */
private static volatile boolean isDestroyed = false;
protected HystrixSampleSseServlet(Observable<String> sampleStream) {
this.sampleStream = sampleStream;
this.pausePollerThreadDelayInMs = DEFAULT_PAUSE_POLLER_THREAD_DELAY_IN_MS;
}
protected HystrixSampleSseServlet(Observable<String> sampleStream, int pausePollerThreadDelayInMs) {
this.sampleStream = sampleStream;
this.pausePollerThreadDelayInMs = pausePollerThreadDelayInMs;
}
protected abstract int getMaxNumberConcurrentConnectionsAllowed();
protected abstract int getNumberCurrentConnections();
protected abstract int incrementAndGetCurrentConcurrentConnections();
protected abstract void decrementCurrentConcurrentConnections();
/**
* Handle incoming GETs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (isDestroyed) {
response.sendError(503, "Service has been shut down.");
} else {
handleRequest(request, response);
}
}
/**
* WebSphere won't shutdown a servlet until after a 60 second timeout if there is an instance of the servlet executing
* a request. Add this method to enable a hook to notify Hystrix to shutdown. You must invoke this method at
* shutdown, perhaps from some other servlet's destroy() method.
*/
public static void shutdown() {
isDestroyed = true;
}
@Override
public void init() throws ServletException {
isDestroyed = false;
}
/**
* Handle servlet being undeployed by gracefully releasing connections so poller threads stop.
*/
@Override
public void destroy() {
/* set marker so the loops can break out */
isDestroyed = true;
super.destroy();
}
/**
* - maintain an open connection with the client
* - on initial connection send latest data of each requested event type
* - subsequently send all changes for each requested event type
*
* @param request incoming HTTP Request
* @param response outgoing HTTP Response (as a streaming response)
* @throws javax.servlet.ServletException
* @throws java.io.IOException
*/
private void handleRequest(HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
final AtomicBoolean moreDataWillBeSent = new AtomicBoolean(true);
Subscription sampleSubscription = null;
/* ensure we aren't allowing more connections than we want */
int numberConnections = incrementAndGetCurrentConcurrentConnections();
try {
int maxNumberConnectionsAllowed = getMaxNumberConcurrentConnectionsAllowed(); //may change at runtime, so look this up for each request
if (numberConnections > maxNumberConnectionsAllowed) {
response.sendError(503, "MaxConcurrentConnections reached: " + maxNumberConnectionsAllowed);
} else {
/* initialize response */
response.setHeader("Content-Type", "text/event-stream;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
response.setHeader("Pragma", "no-cache");
final PrintWriter writer = response.getWriter();
//since the sample stream is based on Observable.interval, events will get published on an RxComputation thread
//since writing to the servlet response is blocking, use the Rx IO thread for the write that occurs in the onNext
sampleSubscription = sampleStream
.observeOn(Schedulers.io())
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
logger.error("HystrixSampleSseServlet: ({}) received unexpected OnCompleted from sample stream", getClass().getSimpleName());
moreDataWillBeSent.set(false);
}
@Override
public void onError(Throwable e) {
moreDataWillBeSent.set(false);
}
@Override
public void onNext(String sampleDataAsString) {
if (sampleDataAsString != null) {
try {
// avoid concurrent writes with ping
synchronized (responseWriteLock) {
writer.print("data: " + sampleDataAsString + "\n\n");
// explicitly check for client disconnect - PrintWriter does not throw exceptions
if (writer.checkError()) {
moreDataWillBeSent.set(false);
}
writer.flush();
}
} catch (Exception ex) {
moreDataWillBeSent.set(false);
}
}
}
});
while (moreDataWillBeSent.get() && !isDestroyed) {
try {
Thread.sleep(pausePollerThreadDelayInMs);
//in case stream has not started emitting yet, catch any clients which connect/disconnect before emits start
// avoid concurrent writes with sample
synchronized (responseWriteLock) {
writer.print("ping: \n\n");
// explicitly check for client disconnect - PrintWriter does not throw exceptions
if (writer.checkError()) {
moreDataWillBeSent.set(false);
}
writer.flush();
}
} catch (Exception ex) {
moreDataWillBeSent.set(false);
}
}
}
} finally {
decrementCurrentConcurrentConnections();
if (sampleSubscription != null && !sampleSubscription.isUnsubscribed()) {
sampleSubscription.unsubscribe();
}
}
}
}
| 4,531 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/main/java/com/netflix/hystrix/contrib/sample | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/main/java/com/netflix/hystrix/contrib/sample/stream/HystrixConfigurationJsonStream.java | /**
* Copyright 2016 Netflix, Inc.
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.sample.stream;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.config.HystrixCollapserConfiguration;
import com.netflix.hystrix.config.HystrixCommandConfiguration;
import com.netflix.hystrix.config.HystrixConfiguration;
import com.netflix.hystrix.config.HystrixConfigurationStream;
import com.netflix.hystrix.config.HystrixThreadPoolConfiguration;
import com.netflix.hystrix.metric.HystrixRequestEventsStream;
import rx.Observable;
import rx.functions.Func1;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
/**
* Links HystrixConfigurationStream and JSON encoding. This may be consumed in a variety of ways:
* -such as-
* <ul>
* <li> {@link HystrixConfigSseServlet} for mapping a specific URL to this data as an SSE stream
* <li> Consumer of your choice that wants control over where to embed this stream
* </ul>
*
* @deprecated Instead, prefer mapping your preferred serialization on top of {@link HystrixConfigurationStream#observe()}.
*/
@Deprecated //since 1.5.4
public class HystrixConfigurationJsonStream {
private static final JsonFactory jsonFactory = new JsonFactory();
private final Func1<Integer, Observable<HystrixConfiguration>> streamGenerator;
@Deprecated //since 1.5.4
public HystrixConfigurationJsonStream() {
this.streamGenerator = new Func1<Integer, Observable<HystrixConfiguration>>() {
@Override
public Observable<HystrixConfiguration> call(Integer delay) {
return HystrixConfigurationStream.getInstance().observe();
}
};
}
@Deprecated //since 1.5.4
public HystrixConfigurationJsonStream(Func1<Integer, Observable<HystrixConfiguration>> streamGenerator) {
this.streamGenerator = streamGenerator;
}
private static final Func1<HystrixConfiguration, String> convertToJson = new Func1<HystrixConfiguration, String>() {
@Override
public String call(HystrixConfiguration hystrixConfiguration) {
try {
return convertToString(hystrixConfiguration);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
};
private static void writeCommandConfigJson(JsonGenerator json, HystrixCommandKey key, HystrixCommandConfiguration commandConfig) throws IOException {
json.writeObjectFieldStart(key.name());
json.writeStringField("threadPoolKey", commandConfig.getThreadPoolKey().name());
json.writeStringField("groupKey", commandConfig.getGroupKey().name());
json.writeObjectFieldStart("execution");
HystrixCommandConfiguration.HystrixCommandExecutionConfig executionConfig = commandConfig.getExecutionConfig();
json.writeStringField("isolationStrategy", executionConfig.getIsolationStrategy().name());
json.writeStringField("threadPoolKeyOverride", executionConfig.getThreadPoolKeyOverride());
json.writeBooleanField("requestCacheEnabled", executionConfig.isRequestCacheEnabled());
json.writeBooleanField("requestLogEnabled", executionConfig.isRequestLogEnabled());
json.writeBooleanField("timeoutEnabled", executionConfig.isTimeoutEnabled());
json.writeBooleanField("fallbackEnabled", executionConfig.isFallbackEnabled());
json.writeNumberField("timeoutInMilliseconds", executionConfig.getTimeoutInMilliseconds());
json.writeNumberField("semaphoreSize", executionConfig.getSemaphoreMaxConcurrentRequests());
json.writeNumberField("fallbackSemaphoreSize", executionConfig.getFallbackMaxConcurrentRequest());
json.writeBooleanField("threadInterruptOnTimeout", executionConfig.isThreadInterruptOnTimeout());
json.writeEndObject();
json.writeObjectFieldStart("metrics");
HystrixCommandConfiguration.HystrixCommandMetricsConfig metricsConfig = commandConfig.getMetricsConfig();
json.writeNumberField("healthBucketSizeInMs", metricsConfig.getHealthIntervalInMilliseconds());
json.writeNumberField("percentileBucketSizeInMilliseconds", metricsConfig.getRollingPercentileBucketSizeInMilliseconds());
json.writeNumberField("percentileBucketCount", metricsConfig.getRollingCounterNumberOfBuckets());
json.writeBooleanField("percentileEnabled", metricsConfig.isRollingPercentileEnabled());
json.writeNumberField("counterBucketSizeInMilliseconds", metricsConfig.getRollingCounterBucketSizeInMilliseconds());
json.writeNumberField("counterBucketCount", metricsConfig.getRollingCounterNumberOfBuckets());
json.writeEndObject();
json.writeObjectFieldStart("circuitBreaker");
HystrixCommandConfiguration.HystrixCommandCircuitBreakerConfig circuitBreakerConfig = commandConfig.getCircuitBreakerConfig();
json.writeBooleanField("enabled", circuitBreakerConfig.isEnabled());
json.writeBooleanField("isForcedOpen", circuitBreakerConfig.isForceOpen());
json.writeBooleanField("isForcedClosed", circuitBreakerConfig.isForceOpen());
json.writeNumberField("requestVolumeThreshold", circuitBreakerConfig.getRequestVolumeThreshold());
json.writeNumberField("errorPercentageThreshold", circuitBreakerConfig.getErrorThresholdPercentage());
json.writeNumberField("sleepInMilliseconds", circuitBreakerConfig.getSleepWindowInMilliseconds());
json.writeEndObject();
json.writeEndObject();
}
private static void writeThreadPoolConfigJson(JsonGenerator json, HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolConfiguration threadPoolConfig) throws IOException {
json.writeObjectFieldStart(threadPoolKey.name());
json.writeNumberField("coreSize", threadPoolConfig.getCoreSize());
json.writeNumberField("maximumSize", threadPoolConfig.getMaximumSize());
json.writeNumberField("actualMaximumSize", threadPoolConfig.getActualMaximumSize());
json.writeNumberField("maxQueueSize", threadPoolConfig.getMaxQueueSize());
json.writeNumberField("queueRejectionThreshold", threadPoolConfig.getQueueRejectionThreshold());
json.writeNumberField("keepAliveTimeInMinutes", threadPoolConfig.getKeepAliveTimeInMinutes());
json.writeBooleanField("allowMaximumSizeToDivergeFromCoreSize", threadPoolConfig.getAllowMaximumSizeToDivergeFromCoreSize());
json.writeNumberField("counterBucketSizeInMilliseconds", threadPoolConfig.getRollingCounterBucketSizeInMilliseconds());
json.writeNumberField("counterBucketCount", threadPoolConfig.getRollingCounterNumberOfBuckets());
json.writeEndObject();
}
private static void writeCollapserConfigJson(JsonGenerator json, HystrixCollapserKey collapserKey, HystrixCollapserConfiguration collapserConfig) throws IOException {
json.writeObjectFieldStart(collapserKey.name());
json.writeNumberField("maxRequestsInBatch", collapserConfig.getMaxRequestsInBatch());
json.writeNumberField("timerDelayInMilliseconds", collapserConfig.getTimerDelayInMilliseconds());
json.writeBooleanField("requestCacheEnabled", collapserConfig.isRequestCacheEnabled());
json.writeObjectFieldStart("metrics");
HystrixCollapserConfiguration.CollapserMetricsConfig metricsConfig = collapserConfig.getCollapserMetricsConfig();
json.writeNumberField("percentileBucketSizeInMilliseconds", metricsConfig.getRollingPercentileBucketSizeInMilliseconds());
json.writeNumberField("percentileBucketCount", metricsConfig.getRollingCounterNumberOfBuckets());
json.writeBooleanField("percentileEnabled", metricsConfig.isRollingPercentileEnabled());
json.writeNumberField("counterBucketSizeInMilliseconds", metricsConfig.getRollingCounterBucketSizeInMilliseconds());
json.writeNumberField("counterBucketCount", metricsConfig.getRollingCounterNumberOfBuckets());
json.writeEndObject();
json.writeEndObject();
}
public static String convertToString(HystrixConfiguration config) throws IOException {
StringWriter jsonString = new StringWriter();
JsonGenerator json = jsonFactory.createGenerator(jsonString);
json.writeStartObject();
json.writeStringField("type", "HystrixConfig");
json.writeObjectFieldStart("commands");
for (Map.Entry<HystrixCommandKey, HystrixCommandConfiguration> entry: config.getCommandConfig().entrySet()) {
final HystrixCommandKey key = entry.getKey();
final HystrixCommandConfiguration commandConfig = entry.getValue();
writeCommandConfigJson(json, key, commandConfig);
}
json.writeEndObject();
json.writeObjectFieldStart("threadpools");
for (Map.Entry<HystrixThreadPoolKey, HystrixThreadPoolConfiguration> entry: config.getThreadPoolConfig().entrySet()) {
final HystrixThreadPoolKey threadPoolKey = entry.getKey();
final HystrixThreadPoolConfiguration threadPoolConfig = entry.getValue();
writeThreadPoolConfigJson(json, threadPoolKey, threadPoolConfig);
}
json.writeEndObject();
json.writeObjectFieldStart("collapsers");
for (Map.Entry<HystrixCollapserKey, HystrixCollapserConfiguration> entry: config.getCollapserConfig().entrySet()) {
final HystrixCollapserKey collapserKey = entry.getKey();
final HystrixCollapserConfiguration collapserConfig = entry.getValue();
writeCollapserConfigJson(json, collapserKey, collapserConfig);
}
json.writeEndObject();
json.writeEndObject();
json.close();
return jsonString.getBuffer().toString();
}
/**
* @deprecated Not for public use. Using the delay param prevents streams from being efficiently shared.
* Please use {@link HystrixConfigurationStream#observe()}
* @param delay interval between data emissions
* @return sampled utilization as Java object, taken on a timer
*/
@Deprecated //deprecated in 1.5.4
public Observable<HystrixConfiguration> observe(int delay) {
return streamGenerator.call(delay);
}
/**
* @deprecated Not for public use. Using the delay param prevents streams from being efficiently shared.
* Please use {@link HystrixConfigurationStream#observe()}
* and you can map to JSON string via {@link HystrixConfigurationJsonStream#convertToString(HystrixConfiguration)}
* @param delay interval between data emissions
* @return sampled utilization as JSON string, taken on a timer
*/
@Deprecated //deprecated in 1.5.4
public Observable<String> observeJson(int delay) {
return streamGenerator.call(delay).map(convertToJson);
}
}
| 4,532 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/main/java/com/netflix/hystrix/contrib/sample | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/main/java/com/netflix/hystrix/contrib/sample/stream/HystrixUtilizationJsonStream.java | /**
* Copyright 2016 Netflix, Inc.
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.sample.stream;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.metric.sample.HystrixCommandUtilization;
import com.netflix.hystrix.metric.sample.HystrixThreadPoolUtilization;
import com.netflix.hystrix.metric.sample.HystrixUtilization;
import com.netflix.hystrix.metric.sample.HystrixUtilizationStream;
import rx.Observable;
import rx.functions.Func1;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
/**
* Links HystrixUtilizationStream and JSON encoding. This may be consumed in a variety of ways:
* -such as-
* <ul>
* <li> {@link HystrixUtilizationSseServlet} for mapping a specific URL to this data as an SSE stream
* <li> Consumer of your choice that wants control over where to embed this stream
* </ul>
* @deprecated Instead, prefer mapping your preferred serialization on top of {@link HystrixUtilizationStream#observe()}.
*/
@Deprecated //since 1.5.4
public class HystrixUtilizationJsonStream {
private final Func1<Integer, Observable<HystrixUtilization>> streamGenerator;
private static final JsonFactory jsonFactory = new JsonFactory();
private static final Func1<HystrixUtilization, String> convertToJsonFunc = new Func1<HystrixUtilization, String>() {
@Override
public String call(HystrixUtilization utilization) {
try {
return convertToJson(utilization);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
};
@Deprecated //since 1.5.4
public HystrixUtilizationJsonStream() {
this.streamGenerator = new Func1<Integer, Observable<HystrixUtilization>>() {
@Override
public Observable<HystrixUtilization> call(Integer delay) {
return HystrixUtilizationStream.getInstance().observe();
}
};
}
@Deprecated //since 1.5.4
public HystrixUtilizationJsonStream(Func1<Integer, Observable<HystrixUtilization>> streamGenerator) {
this.streamGenerator = streamGenerator;
}
private static void writeCommandUtilizationJson(JsonGenerator json, HystrixCommandKey key, HystrixCommandUtilization utilization) throws IOException {
json.writeObjectFieldStart(key.name());
json.writeNumberField("activeCount", utilization.getConcurrentCommandCount());
json.writeEndObject();
}
private static void writeThreadPoolUtilizationJson(JsonGenerator json, HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolUtilization utilization) throws IOException {
json.writeObjectFieldStart(threadPoolKey.name());
json.writeNumberField("activeCount", utilization.getCurrentActiveCount());
json.writeNumberField("queueSize", utilization.getCurrentQueueSize());
json.writeNumberField("corePoolSize", utilization.getCurrentCorePoolSize());
json.writeNumberField("poolSize", utilization.getCurrentPoolSize());
json.writeEndObject();
}
protected static String convertToJson(HystrixUtilization utilization) throws IOException {
StringWriter jsonString = new StringWriter();
JsonGenerator json = jsonFactory.createGenerator(jsonString);
json.writeStartObject();
json.writeStringField("type", "HystrixUtilization");
json.writeObjectFieldStart("commands");
for (Map.Entry<HystrixCommandKey, HystrixCommandUtilization> entry: utilization.getCommandUtilizationMap().entrySet()) {
final HystrixCommandKey key = entry.getKey();
final HystrixCommandUtilization commandUtilization = entry.getValue();
writeCommandUtilizationJson(json, key, commandUtilization);
}
json.writeEndObject();
json.writeObjectFieldStart("threadpools");
for (Map.Entry<HystrixThreadPoolKey, HystrixThreadPoolUtilization> entry: utilization.getThreadPoolUtilizationMap().entrySet()) {
final HystrixThreadPoolKey threadPoolKey = entry.getKey();
final HystrixThreadPoolUtilization threadPoolUtilization = entry.getValue();
writeThreadPoolUtilizationJson(json, threadPoolKey, threadPoolUtilization);
}
json.writeEndObject();
json.writeEndObject();
json.close();
return jsonString.getBuffer().toString();
}
/**
* @deprecated Not for public use. Using the delay param prevents streams from being efficiently shared.
* Please use {@link HystrixUtilizationStream#observe()}
* @param delay interval between data emissions
* @return sampled utilization as Java object, taken on a timer
*/
@Deprecated //deprecated as of 1.5.4
public Observable<HystrixUtilization> observe(int delay) {
return streamGenerator.call(delay);
}
/**
* @deprecated Not for public use. Using the delay param prevents streams from being efficiently shared.
* Please use {@link HystrixUtilizationStream#observe()}
* and the {@link #convertToJson(HystrixUtilization)} method
* @param delay interval between data emissions
* @return sampled utilization as JSON string, taken on a timer
*/
public Observable<String> observeJson(int delay) {
return streamGenerator.call(delay).map(convertToJsonFunc);
}
}
| 4,533 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/main/java/com/netflix/hystrix/contrib/sample | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream/src/main/java/com/netflix/hystrix/contrib/sample/stream/HystrixConfigSseServlet.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.hystrix.contrib.sample.stream;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.hystrix.config.HystrixConfiguration;
import com.netflix.hystrix.config.HystrixConfigurationStream;
import com.netflix.hystrix.serial.SerialHystrixConfiguration;
import rx.Observable;
import rx.functions.Func1;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Streams Hystrix config in text/event-stream format.
* <p>
* Install by:
* <p>
* 1) Including hystrix-metrics-event-stream-*.jar in your classpath.
* <p>
* 2) Adding the following to web.xml:
* <pre>{@code
* <servlet>
* <description></description>
* <display-name>HystrixConfigSseServlet</display-name>
* <servlet-name>HystrixConfigSseServlet</servlet-name>
* <servlet-class>com.netflix.hystrix.contrib.sample.stream.HystrixConfigSseServlet</servlet-class>
* </servlet>
* <servlet-mapping>
* <servlet-name>HystrixConfigSseServlet</servlet-name>
* <url-pattern>/hystrix/config.stream</url-pattern>
* </servlet-mapping>
* } </pre>
*/
public class HystrixConfigSseServlet extends HystrixSampleSseServlet {
private static final long serialVersionUID = -3599771169762858235L;
/* used to track number of connections and throttle */
private static AtomicInteger concurrentConnections = new AtomicInteger(0);
private static DynamicIntProperty maxConcurrentConnections = DynamicPropertyFactory.getInstance().getIntProperty("hystrix.config.stream.maxConcurrentConnections", 5);
public HystrixConfigSseServlet() {
this(HystrixConfigurationStream.getInstance().observe(), DEFAULT_PAUSE_POLLER_THREAD_DELAY_IN_MS);
}
/* package-private */ HystrixConfigSseServlet(Observable<HystrixConfiguration> sampleStream, int pausePollerThreadDelayInMs) {
super(sampleStream.map(new Func1<HystrixConfiguration, String>() {
@Override
public String call(HystrixConfiguration hystrixConfiguration) {
return SerialHystrixConfiguration.toJsonString(hystrixConfiguration);
}
}), pausePollerThreadDelayInMs);
}
@Override
protected int getMaxNumberConcurrentConnectionsAllowed() {
return maxConcurrentConnections.get();
}
@Override
protected int getNumberCurrentConnections() {
return concurrentConnections.get();
}
@Override
protected int incrementAndGetCurrentConcurrentConnections() {
return concurrentConnections.incrementAndGet();
}
@Override
protected void decrementCurrentConcurrentConnections() {
concurrentConnections.decrementAndGet();
}
}
| 4,534 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-yammer-metrics-publisher/src/main/java/com/netflix/hystrix/contrib | Create_ds/Hystrix/hystrix-contrib/hystrix-yammer-metrics-publisher/src/main/java/com/netflix/hystrix/contrib/yammermetricspublisher/HystrixYammerMetricsPublisherCommand.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.yammermetricspublisher;
import com.netflix.hystrix.HystrixCircuitBreaker;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandMetrics;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherCommand;
import com.netflix.hystrix.util.HystrixRollingNumberEvent;
import com.yammer.metrics.core.Gauge;
import com.yammer.metrics.core.MetricName;
import com.yammer.metrics.core.MetricsRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.functions.Func0;
/**
* Implementation of {@link HystrixMetricsPublisherCommand} using Yammer Metrics (https://github.com/codahale/metrics)
*
* An implementation note. If there's a version mismatch between hystrix-core and hystrix-yammer-metrics-publisher,
* the code below may reference a HystrixRollingNumberEvent that does not exist in hystrix-core. If this happens,
* a j.l.NoSuchFieldError occurs. Since this data is not being generated by hystrix-core, it's safe to count it as 0
* and we should log an error to get users to update their dependency set.
*/
public class HystrixYammerMetricsPublisherCommand implements HystrixMetricsPublisherCommand {
private final HystrixCommandKey key;
private final HystrixCommandGroupKey commandGroupKey;
private final HystrixCommandMetrics metrics;
private final HystrixCircuitBreaker circuitBreaker;
private final HystrixCommandProperties properties;
private final MetricsRegistry metricsRegistry;
private final String metricGroup;
private final String metricType;
static final Logger logger = LoggerFactory.getLogger(HystrixYammerMetricsPublisherCommand.class);
public HystrixYammerMetricsPublisherCommand(HystrixCommandKey commandKey, HystrixCommandGroupKey commandGroupKey, HystrixCommandMetrics metrics, HystrixCircuitBreaker circuitBreaker, HystrixCommandProperties properties, MetricsRegistry metricsRegistry) {
this.key = commandKey;
this.commandGroupKey = commandGroupKey;
this.metrics = metrics;
this.circuitBreaker = circuitBreaker;
this.properties = properties;
this.metricsRegistry = metricsRegistry;
this.metricGroup = "HystrixCommand";
this.metricType = key.name();
}
@Override
public void initialize() {
metricsRegistry.newGauge(createMetricName("isCircuitBreakerOpen"), new Gauge<Boolean>() {
@Override
public Boolean value() {
return circuitBreaker.isOpen();
}
});
// allow monitor to know exactly at what point in time these stats are for so they can be plotted accurately
metricsRegistry.newGauge(createMetricName("currentTime"), new Gauge<Long>() {
@Override
public Long value() {
return System.currentTimeMillis();
}
});
// cumulative counts
safelyCreateCumulativeGauge("countBadRequests", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.BAD_REQUEST;
}
});
safelyCreateCumulativeGauge("countCollapsedRequests", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.COLLAPSED;
}
});
safelyCreateCumulativeGauge("countEmit", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.EMIT;
}
});
safelyCreateCumulativeGauge("countExceptionsThrown", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.EXCEPTION_THROWN;
}
});
safelyCreateCumulativeGauge("countFailure", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.FAILURE;
}
});
safelyCreateCumulativeGauge("countFallbackEmit", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.FALLBACK_EMIT;
}
});
safelyCreateCumulativeGauge("countFallbackFailure", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.FALLBACK_FAILURE;
}
});
safelyCreateCumulativeGauge("countFallbackMissing", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.FALLBACK_MISSING;
}
});
safelyCreateCumulativeGauge("countFallbackRejection", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.FALLBACK_REJECTION;
}
});
safelyCreateCumulativeGauge("countFallbackSuccess", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.FALLBACK_SUCCESS;
}
});
safelyCreateCumulativeGauge("countResponsesFromCache", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.RESPONSE_FROM_CACHE;
}
});
safelyCreateCumulativeGauge("countSemaphoreRejected", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.SEMAPHORE_REJECTED;
}
});
safelyCreateCumulativeGauge("countShortCircuited", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.SHORT_CIRCUITED;
}
});
safelyCreateCumulativeGauge("countSuccess", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.SUCCESS;
}
});
safelyCreateCumulativeGauge("countThreadPoolRejected", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.THREAD_POOL_REJECTED;
}
});
safelyCreateCumulativeGauge("countTimeout", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.TIMEOUT;
}
});
// rolling counts
safelyCreateRollingGauge("rollingCountBadRequests", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.BAD_REQUEST;
}
});
safelyCreateRollingGauge("rollingCountCollapsedRequests", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.COLLAPSED;
}
});
safelyCreateRollingGauge("rollingCountExceptionsThrown", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.EXCEPTION_THROWN;
}
});
safelyCreateRollingGauge("rollingCountFailure", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.FAILURE;
}
});
safelyCreateRollingGauge("rollingCountFallbackFailure", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.FALLBACK_FAILURE;
}
});
safelyCreateRollingGauge("rollingCountFallbackMissing", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.FALLBACK_MISSING;
}
});
safelyCreateRollingGauge("rollingCountFallbackRejection", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.FALLBACK_REJECTION;
}
});
safelyCreateRollingGauge("rollingCountFallbackSuccess", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.FALLBACK_SUCCESS;
}
});
safelyCreateRollingGauge("rollingCountResponsesFromCache", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.RESPONSE_FROM_CACHE;
}
});
safelyCreateRollingGauge("rollingCountSemaphoreRejected", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.SEMAPHORE_REJECTED;
}
});
safelyCreateRollingGauge("rollingCountShortCircuited", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.SHORT_CIRCUITED;
}
});
safelyCreateRollingGauge("rollingCountSuccess", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.SUCCESS;
}
});
safelyCreateRollingGauge("rollingCountThreadPoolRejected", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.THREAD_POOL_REJECTED;
}
});
safelyCreateRollingGauge("rollingCountTimeout", new Func0<HystrixEventType>() {
@Override
public HystrixEventType call() {
return HystrixEventType.TIMEOUT;
}
});
// the number of executionSemaphorePermits in use right now
createCurrentValueGauge("executionSemaphorePermitsInUse", currentConcurrentExecutionCountThunk);
// error percentage derived from current metrics
createCurrentValueGauge("errorPercentage", errorPercentageThunk);
// latency metrics
createExecutionLatencyMeanGauge("latencyExecute_mean");
createExecutionLatencyPercentileGauge("latencyExecute_percentile_5", 5);
createExecutionLatencyPercentileGauge("latencyExecute_percentile_25", 25);
createExecutionLatencyPercentileGauge("latencyExecute_percentile_50", 50);
createExecutionLatencyPercentileGauge("latencyExecute_percentile_75", 75);
createExecutionLatencyPercentileGauge("latencyExecute_percentile_90", 90);
createExecutionLatencyPercentileGauge("latencyExecute_percentile_99", 99);
createExecutionLatencyPercentileGauge("latencyExecute_percentile_995", 99.5);
createTotalLatencyMeanGauge("latencyTotal_mean");
createTotalLatencyPercentileGauge("latencyTotal_percentile_5", 5);
createTotalLatencyPercentileGauge("latencyTotal_percentile_25", 25);
createTotalLatencyPercentileGauge("latencyTotal_percentile_50", 50);
createTotalLatencyPercentileGauge("latencyTotal_percentile_75", 75);
createTotalLatencyPercentileGauge("latencyTotal_percentile_90", 90);
createTotalLatencyPercentileGauge("latencyTotal_percentile_99", 99);
createTotalLatencyPercentileGauge("latencyTotal_percentile_995", 99.5);
// group
metricsRegistry.newGauge(createMetricName("commandGroup"), new Gauge<String>() {
@Override
public String value() {
return commandGroupKey != null ? commandGroupKey.name() : null;
}
});
// properties (so the values can be inspected and monitored)
metricsRegistry.newGauge(createMetricName("propertyValue_rollingStatisticalWindowInMilliseconds"), new Gauge<Number>() {
@Override
public Number value() {
return properties.metricsRollingStatisticalWindowInMilliseconds().get();
}
});
metricsRegistry.newGauge(createMetricName("propertyValue_circuitBreakerRequestVolumeThreshold"), new Gauge<Number>() {
@Override
public Number value() {
return properties.circuitBreakerRequestVolumeThreshold().get();
}
});
metricsRegistry.newGauge(createMetricName("propertyValue_circuitBreakerSleepWindowInMilliseconds"), new Gauge<Number>() {
@Override
public Number value() {
return properties.circuitBreakerSleepWindowInMilliseconds().get();
}
});
metricsRegistry.newGauge(createMetricName("propertyValue_circuitBreakerErrorThresholdPercentage"), new Gauge<Number>() {
@Override
public Number value() {
return properties.circuitBreakerErrorThresholdPercentage().get();
}
});
metricsRegistry.newGauge(createMetricName("propertyValue_circuitBreakerForceOpen"), new Gauge<Boolean>() {
@Override
public Boolean value() {
return properties.circuitBreakerForceOpen().get();
}
});
metricsRegistry.newGauge(createMetricName("propertyValue_circuitBreakerForceClosed"), new Gauge<Boolean>() {
@Override
public Boolean value() {
return properties.circuitBreakerForceClosed().get();
}
});
metricsRegistry.newGauge(createMetricName("propertyValue_executionTimeoutInMilliseconds"), new Gauge<Number>() {
@Override
public Number value() {
return properties.executionTimeoutInMilliseconds().get();
}
});
metricsRegistry.newGauge(createMetricName("propertyValue_executionIsolationThreadTimeoutInMilliseconds"), new Gauge<Number>() {
@Override
public Number value() {
return properties.executionTimeoutInMilliseconds().get();
}
});
metricsRegistry.newGauge(createMetricName("propertyValue_executionIsolationStrategy"), new Gauge<String>() {
@Override
public String value() {
return properties.executionIsolationStrategy().get().name();
}
});
metricsRegistry.newGauge(createMetricName("propertyValue_metricsRollingPercentileEnabled"), new Gauge<Boolean>() {
@Override
public Boolean value() {
return properties.metricsRollingPercentileEnabled().get();
}
});
metricsRegistry.newGauge(createMetricName("propertyValue_requestCacheEnabled"), new Gauge<Boolean>() {
@Override
public Boolean value() {
return properties.requestCacheEnabled().get();
}
});
metricsRegistry.newGauge(createMetricName("propertyValue_requestLogEnabled"), new Gauge<Boolean>() {
@Override
public Boolean value() {
return properties.requestLogEnabled().get();
}
});
metricsRegistry.newGauge(createMetricName("propertyValue_executionIsolationSemaphoreMaxConcurrentRequests"), new Gauge<Number>() {
@Override
public Number value() {
return properties.executionIsolationSemaphoreMaxConcurrentRequests().get();
}
});
metricsRegistry.newGauge(createMetricName("propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests"), new Gauge<Number>() {
@Override
public Number value() {
return properties.fallbackIsolationSemaphoreMaxConcurrentRequests().get();
}
});
}
protected MetricName createMetricName(String name) {
return new MetricName(metricGroup, metricType, name);
}
@Deprecated
protected void createCumulativeCountForEvent(String name, final HystrixRollingNumberEvent event) {
metricsRegistry.newGauge(createMetricName(name), new Gauge<Long>() {
@Override
public Long value() {
return metrics.getCumulativeCount(event);
}
});
}
protected void createCumulativeGauge(final String name, final HystrixEventType eventType) {
metricsRegistry.newGauge(createMetricName(name), new Gauge<Long>() {
@Override
public Long value() {
return metrics.getCumulativeCount(HystrixRollingNumberEvent.from(eventType));
}
});
}
protected void safelyCreateCumulativeGauge(final String name, final Func0<HystrixEventType> eventThunk) {
metricsRegistry.newGauge(createMetricName(name), new Gauge<Long>() {
@Override
public Long value() {
try {
HystrixRollingNumberEvent eventType = HystrixRollingNumberEvent.from(eventThunk.call());
return metrics.getCumulativeCount(eventType);
} catch (NoSuchFieldError error) {
logger.error("While publishing Yammer metrics, error looking up eventType for : {}. Please check that all Hystrix versions are the same!", name);
return 0L;
}
}
});
}
@Deprecated
protected void createRollingGauge(String name, final HystrixRollingNumberEvent event) {
metricsRegistry.newGauge(createMetricName(name), new Gauge<Long>() {
@Override
public Long value() {
return metrics.getRollingCount(event);
}
});
}
protected void createRollingGauge(final String name, final HystrixEventType eventType) {
metricsRegistry.newGauge(createMetricName(name), new Gauge<Long>() {
@Override
public Long value() {
return metrics.getRollingCount(HystrixRollingNumberEvent.from(eventType));
}
});
}
protected void safelyCreateRollingGauge(final String name, final Func0<HystrixEventType> eventThunk) {
metricsRegistry.newGauge(createMetricName(name), new Gauge<Long>() {
@Override
public Long value() {
try {
HystrixRollingNumberEvent eventType = HystrixRollingNumberEvent.from(eventThunk.call());
return metrics.getRollingCount(eventType);
} catch (NoSuchFieldError error) {
logger.error("While publishing Yammer metrics, error looking up eventType for : {}. Please check that all Hystrix versions are the same!", name);
return 0L;
}
}
});
}
protected void createExecutionLatencyMeanGauge(final String name) {
metricsRegistry.newGauge(createMetricName(name), new Gauge<Integer>() {
@Override
public Integer value() {
return metrics.getExecutionTimeMean();
}
});
}
protected void createExecutionLatencyPercentileGauge(final String name, final double percentile) {
metricsRegistry.newGauge(createMetricName(name), new Gauge<Integer>() {
@Override
public Integer value() {
return metrics.getExecutionTimePercentile(percentile);
}
});
}
protected void createTotalLatencyMeanGauge(final String name) {
metricsRegistry.newGauge(createMetricName(name), new Gauge<Integer>() {
@Override
public Integer value() {
return metrics.getTotalTimeMean();
}
});
}
protected void createTotalLatencyPercentileGauge(final String name, final double percentile) {
metricsRegistry.newGauge(createMetricName(name), new Gauge<Integer>() {
@Override
public Integer value() {
return metrics.getTotalTimePercentile(percentile);
}
});
}
protected final Func0<Integer> currentConcurrentExecutionCountThunk = new Func0<Integer>() {
@Override
public Integer call() {
return metrics.getCurrentConcurrentExecutionCount();
}
};
protected final Func0<Long> rollingMaxConcurrentExecutionCountThunk = new Func0<Long>() {
@Override
public Long call() {
return metrics.getRollingMaxConcurrentExecutions();
}
};
protected final Func0<Integer> errorPercentageThunk = new Func0<Integer>() {
@Override
public Integer call() {
return metrics.getHealthCounts().getErrorPercentage();
}
};
protected void createCurrentValueGauge(final String name, final Func0<Integer> metricToEvaluate) {
metricsRegistry.newGauge(createMetricName(name), new Gauge<Integer>() {
@Override
public Integer value() {
return metricToEvaluate.call();
}
});
}
}
| 4,535 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-yammer-metrics-publisher/src/main/java/com/netflix/hystrix/contrib | Create_ds/Hystrix/hystrix-contrib/hystrix-yammer-metrics-publisher/src/main/java/com/netflix/hystrix/contrib/yammermetricspublisher/HystrixYammerMetricsPublisherCollapser.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.yammermetricspublisher;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserMetrics;
import com.netflix.hystrix.HystrixCollapserProperties;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherCollapser;
import com.netflix.hystrix.util.HystrixRollingNumberEvent;
import com.yammer.metrics.core.Gauge;
import com.yammer.metrics.core.MetricName;
import com.yammer.metrics.core.MetricsRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.functions.Func0;
/**
* Implementation of {@link HystrixMetricsPublisherCollapser} using Yammer Metrics
*
*
* An implementation note. If there's a version mismatch between hystrix-core and hystrix-yammer-metrics-publisher,
* the code below may reference a HystrixRollingNumberEvent that does not exist in hystrix-core. If this happens,
* a j.l.NoSuchFieldError occurs. Since this data is not being generated by hystrix-core, it's safe to count it as 0
* and we should log an error to get users to update their dependency set.
*/
public class HystrixYammerMetricsPublisherCollapser implements HystrixMetricsPublisherCollapser {
private final HystrixCollapserKey key;
private final HystrixCollapserMetrics metrics;
private final HystrixCollapserProperties properties;
private final MetricsRegistry metricsRegistry;
private final String metricType;
static final Logger logger = LoggerFactory.getLogger(HystrixYammerMetricsPublisherCollapser.class);
public HystrixYammerMetricsPublisherCollapser(HystrixCollapserKey collapserKey, HystrixCollapserMetrics metrics, HystrixCollapserProperties properties, MetricsRegistry metricsRegistry) {
this.key = collapserKey;
this.metrics = metrics;
this.properties = properties;
this.metricsRegistry = metricsRegistry;
this.metricType = key.name();
}
@Override
public void initialize() {
// allow monitor to know exactly at what point in time these stats are for so they can be plotted accurately
metricsRegistry.newGauge(createMetricName("currentTime"), new Gauge<Long>() {
@Override
public Long value() {
return System.currentTimeMillis();
}
});
// cumulative counts
safelyCreateCumulativeCountForEvent("countRequestsBatched", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.COLLAPSER_REQUEST_BATCHED;
}
});
safelyCreateCumulativeCountForEvent("countBatches", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.COLLAPSER_BATCH;
}
});
safelyCreateCumulativeCountForEvent("countResponsesFromCache", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.RESPONSE_FROM_CACHE;
}
});
// rolling counts
safelyCreateRollingCountForEvent("rollingRequestsBatched", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.COLLAPSER_REQUEST_BATCHED;
}
});
safelyCreateRollingCountForEvent("rollingBatches", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.COLLAPSER_BATCH;
}
});
safelyCreateRollingCountForEvent("rollingCountResponsesFromCache", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.RESPONSE_FROM_CACHE;
}
});
// batch size metrics
metricsRegistry.newGauge(createMetricName("batchSize_mean"), new Gauge<Integer>() {
@Override
public Integer value() {
return metrics.getBatchSizeMean();
}
});
metricsRegistry.newGauge(createMetricName("batchSize_percentile_25"), new Gauge<Integer>() {
@Override
public Integer value() {
return metrics.getBatchSizePercentile(25);
}
});
metricsRegistry.newGauge(createMetricName("batchSize_percentile_50"), new Gauge<Integer>() {
@Override
public Integer value() {
return metrics.getBatchSizePercentile(50);
}
});
metricsRegistry.newGauge(createMetricName("batchSize_percentile_75"), new Gauge<Integer>() {
@Override
public Integer value() {
return metrics.getBatchSizePercentile(75);
}
});
metricsRegistry.newGauge(createMetricName("batchSize_percentile_90"), new Gauge<Integer>() {
@Override
public Integer value() {
return metrics.getBatchSizePercentile(90);
}
});
metricsRegistry.newGauge(createMetricName("batchSize_percentile_99"), new Gauge<Integer>() {
@Override
public Integer value() {
return metrics.getBatchSizePercentile(99);
}
});
metricsRegistry.newGauge(createMetricName("batchSize_percentile_995"), new Gauge<Integer>() {
@Override
public Integer value() {
return metrics.getBatchSizePercentile(99.5);
}
});
// shard size metrics
metricsRegistry.newGauge(createMetricName("shardSize_mean"), new Gauge<Integer>() {
@Override
public Integer value() {
return metrics.getShardSizeMean();
}
});
metricsRegistry.newGauge(createMetricName("shardSize_percentile_25"), new Gauge<Integer>() {
@Override
public Integer value() {
return metrics.getShardSizePercentile(25);
}
});
metricsRegistry.newGauge(createMetricName("shardSize_percentile_50"), new Gauge<Integer>() {
@Override
public Integer value() {
return metrics.getShardSizePercentile(50);
}
});
metricsRegistry.newGauge(createMetricName("shardSize_percentile_75"), new Gauge<Integer>() {
@Override
public Integer value() {
return metrics.getShardSizePercentile(75);
}
});
metricsRegistry.newGauge(createMetricName("shardSize_percentile_90"), new Gauge<Integer>() {
@Override
public Integer value() {
return metrics.getShardSizePercentile(90);
}
});
metricsRegistry.newGauge(createMetricName("shardSize_percentile_99"), new Gauge<Integer>() {
@Override
public Integer value() {
return metrics.getShardSizePercentile(99);
}
});
metricsRegistry.newGauge(createMetricName("shardSize_percentile_995"), new Gauge<Integer>() {
@Override
public Integer value() {
return metrics.getShardSizePercentile(99.5);
}
});
// properties (so the values can be inspected and monitored)
metricsRegistry.newGauge(createMetricName("propertyValue_rollingStatisticalWindowInMilliseconds"), new Gauge<Number>() {
@Override
public Number value() {
return properties.metricsRollingStatisticalWindowInMilliseconds().get();
}
});
metricsRegistry.newGauge(createMetricName("propertyValue_requestCacheEnabled"), new Gauge<Boolean>() {
@Override
public Boolean value() {
return properties.requestCacheEnabled().get();
}
});
metricsRegistry.newGauge(createMetricName("propertyValue_maxRequestsInBatch"), new Gauge<Number>() {
@Override
public Number value() {
return properties.maxRequestsInBatch().get();
}
});
metricsRegistry.newGauge(createMetricName("propertyValue_timerDelayInMilliseconds"), new Gauge<Number>() {
@Override
public Number value() {
return properties.timerDelayInMilliseconds().get();
}
});
}
protected MetricName createMetricName(String name) {
return new MetricName("", metricType, name);
}
protected void createCumulativeCountForEvent(final String name, final HystrixRollingNumberEvent event) {
metricsRegistry.newGauge(createMetricName(name), new Gauge<Long>() {
@Override
public Long value() {
return metrics.getCumulativeCount(event);
}
});
}
protected void safelyCreateCumulativeCountForEvent(final String name, final Func0<HystrixRollingNumberEvent> eventThunk) {
metricsRegistry.newGauge(createMetricName(name), new Gauge<Long>() {
@Override
public Long value() {
try {
return metrics.getCumulativeCount(eventThunk.call());
} catch (NoSuchFieldError error) {
logger.error("While publishing Yammer metrics, error looking up eventType for : {}. Please check that all Hystrix versions are the same!", name);
return 0L;
}
}
});
}
protected void createRollingCountForEvent(final String name, final HystrixRollingNumberEvent event) {
metricsRegistry.newGauge(createMetricName(name), new Gauge<Long>() {
@Override
public Long value() {
return metrics.getRollingCount(event);
}
});
}
protected void safelyCreateRollingCountForEvent(final String name, final Func0<HystrixRollingNumberEvent> eventThunk) {
metricsRegistry.newGauge(createMetricName(name), new Gauge<Long>() {
@Override
public Long value() {
try {
return metrics.getRollingCount(eventThunk.call());
} catch (NoSuchFieldError error) {
logger.error("While publishing Yammer metrics, error looking up eventType for : {}. Please check that all Hystrix versions are the same!", name);
return 0L;
}
}
});
}
}
| 4,536 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-yammer-metrics-publisher/src/main/java/com/netflix/hystrix/contrib | Create_ds/Hystrix/hystrix-contrib/hystrix-yammer-metrics-publisher/src/main/java/com/netflix/hystrix/contrib/yammermetricspublisher/HystrixYammerMetricsPublisher.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.yammermetricspublisher;
import com.netflix.hystrix.HystrixCircuitBreaker;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserMetrics;
import com.netflix.hystrix.HystrixCollapserProperties;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandMetrics;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolMetrics;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisher;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherCollapser;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherCommand;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherThreadPool;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.MetricsRegistry;
/**
* Yammer Metrics (https://github.com/codahale/metrics) implementation of {@link HystrixMetricsPublisher}.
*/
public class HystrixYammerMetricsPublisher extends HystrixMetricsPublisher {
private final MetricsRegistry metricsRegistry;
public HystrixYammerMetricsPublisher() {
this(Metrics.defaultRegistry());
}
public HystrixYammerMetricsPublisher(MetricsRegistry metricsRegistry) {
this.metricsRegistry = metricsRegistry;
}
@Override
public HystrixMetricsPublisherCommand getMetricsPublisherForCommand(HystrixCommandKey commandKey, HystrixCommandGroupKey commandGroupKey, HystrixCommandMetrics metrics, HystrixCircuitBreaker circuitBreaker, HystrixCommandProperties properties) {
return new HystrixYammerMetricsPublisherCommand(commandKey, commandGroupKey, metrics, circuitBreaker, properties, metricsRegistry);
}
@Override
public HystrixMetricsPublisherThreadPool getMetricsPublisherForThreadPool(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolMetrics metrics, HystrixThreadPoolProperties properties) {
return new HystrixYammerMetricsPublisherThreadPool(threadPoolKey, metrics, properties, metricsRegistry);
}
@Override
public HystrixMetricsPublisherCollapser getMetricsPublisherForCollapser(HystrixCollapserKey collapserKey, HystrixCollapserMetrics metrics, HystrixCollapserProperties properties) {
return new HystrixYammerMetricsPublisherCollapser(collapserKey, metrics, properties, metricsRegistry);
}
}
| 4,537 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-yammer-metrics-publisher/src/main/java/com/netflix/hystrix/contrib | Create_ds/Hystrix/hystrix-contrib/hystrix-yammer-metrics-publisher/src/main/java/com/netflix/hystrix/contrib/yammermetricspublisher/HystrixYammerMetricsPublisherThreadPool.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.yammermetricspublisher;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolMetrics;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherThreadPool;
import com.netflix.hystrix.util.HystrixRollingNumberEvent;
import com.yammer.metrics.core.Gauge;
import com.yammer.metrics.core.MetricName;
import com.yammer.metrics.core.MetricsRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implementation of {@link HystrixMetricsPublisherThreadPool} using Yammer Metrics (https://github.com/codahale/metrics)
*/
public class HystrixYammerMetricsPublisherThreadPool implements HystrixMetricsPublisherThreadPool {
private final HystrixThreadPoolKey key;
private final HystrixThreadPoolMetrics metrics;
private final HystrixThreadPoolProperties properties;
private final MetricsRegistry metricsRegistry;
private final String metricGroup;
private final String metricType;
static final Logger logger = LoggerFactory.getLogger(HystrixYammerMetricsPublisherThreadPool.class);
public HystrixYammerMetricsPublisherThreadPool(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolMetrics metrics, HystrixThreadPoolProperties properties, MetricsRegistry metricsRegistry) {
this.key = threadPoolKey;
this.metrics = metrics;
this.properties = properties;
this.metricsRegistry = metricsRegistry;
this.metricGroup = "HystrixThreadPool";
this.metricType = key.name();
}
@Override
public void initialize() {
metricsRegistry.newGauge(createMetricName("name"), new Gauge<String>() {
@Override
public String value() {
return key.name();
}
});
// allow monitor to know exactly at what point in time these stats are for so they can be plotted accurately
metricsRegistry.newGauge(createMetricName("currentTime"), new Gauge<Long>() {
@Override
public Long value() {
return System.currentTimeMillis();
}
});
metricsRegistry.newGauge(createMetricName("threadActiveCount"), new Gauge<Number>() {
@Override
public Number value() {
return metrics.getCurrentActiveCount();
}
});
metricsRegistry.newGauge(createMetricName("completedTaskCount"), new Gauge<Number>() {
@Override
public Number value() {
return metrics.getCurrentCompletedTaskCount();
}
});
metricsRegistry.newGauge(createMetricName("largestPoolSize"), new Gauge<Number>() {
@Override
public Number value() {
return metrics.getCurrentLargestPoolSize();
}
});
metricsRegistry.newGauge(createMetricName("totalTaskCount"), new Gauge<Number>() {
@Override
public Number value() {
return metrics.getCurrentTaskCount();
}
});
metricsRegistry.newGauge(createMetricName("queueSize"), new Gauge<Number>() {
@Override
public Number value() {
return metrics.getCurrentQueueSize();
}
});
metricsRegistry.newGauge(createMetricName("rollingMaxActiveThreads"), new Gauge<Number>() {
@Override
public Number value() {
return metrics.getRollingMaxActiveThreads();
}
});
metricsRegistry.newGauge(createMetricName("countThreadsExecuted"), new Gauge<Number>() {
@Override
public Number value() {
return metrics.getCumulativeCountThreadsExecuted();
}
});
metricsRegistry.newGauge(createMetricName("rollingCountCommandsRejected"), new Gauge<Number>() {
@Override
public Number value() {
try {
return metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED);
} catch (NoSuchFieldError error) {
logger.error("While publishing Yammer metrics, error looking up eventType for : rollingCountCommandsRejected. Please check that all Hystrix versions are the same!");
return 0L;
}
}
});
metricsRegistry.newGauge(createMetricName("rollingCountThreadsExecuted"), new Gauge<Number>() {
@Override
public Number value() {
return metrics.getRollingCountThreadsExecuted();
}
});
// properties
metricsRegistry.newGauge(createMetricName("propertyValue_corePoolSize"), new Gauge<Number>() {
@Override
public Number value() {
return properties.coreSize().get();
}
});
metricsRegistry.newGauge(createMetricName("propertyValue_maximumSize"), new Gauge<Number>() {
@Override
public Number value() {
return properties.maximumSize().get();
}
});
metricsRegistry.newGauge(createMetricName("propertyValue_actualMaximumSize"), new Gauge<Number>() {
@Override
public Number value() {
return properties.actualMaximumSize();
}
});
metricsRegistry.newGauge(createMetricName("propertyValue_keepAliveTimeInMinutes"), new Gauge<Number>() {
@Override
public Number value() {
return properties.keepAliveTimeMinutes().get();
}
});
metricsRegistry.newGauge(createMetricName("propertyValue_queueSizeRejectionThreshold"), new Gauge<Number>() {
@Override
public Number value() {
return properties.queueSizeRejectionThreshold().get();
}
});
metricsRegistry.newGauge(createMetricName("propertyValue_maxQueueSize"), new Gauge<Number>() {
@Override
public Number value() {
return properties.maxQueueSize().get();
}
});
}
protected MetricName createMetricName(String name) {
return new MetricName(metricGroup, metricType, name);
}
}
| 4,538 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream-jaxrs/src/test/java/com/netflix/hystrix/contrib/metrics | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream-jaxrs/src/test/java/com/netflix/hystrix/contrib/metrics/controller/HystricsMetricsControllerTest.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.hystrix.contrib.metrics.controller;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.ServiceUnavailableException;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;
import org.apache.commons.configuration.SystemConfiguration;
import org.glassfish.jersey.media.sse.EventInput;
import org.glassfish.jersey.media.sse.InboundEvent;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.TestProperties;
import org.junit.Assert;
import org.junit.Test;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.contrib.metrics.HystrixStreamFeature;
/**
* @author justinjose28
*
*/
@Path("/hystrix")
public class HystricsMetricsControllerTest extends JerseyTest {
protected static final AtomicInteger requestCount = new AtomicInteger(0);
@POST
@Path("/command")
@Consumes(APPLICATION_JSON)
public void command() throws Exception {
TestHystrixCommand command = new TestHystrixCommand();
command.execute();
}
@Override
protected Application configure() {
int port = 0;
try {
final ServerSocket socket = new ServerSocket(0);
port = socket.getLocalPort();
socket.close();
} catch (IOException e1) {
throw new RuntimeException("Failed to find port to start test server");
}
set(TestProperties.CONTAINER_PORT, port);
try {
SystemConfiguration.setSystemProperties("test.properties");
} catch (Exception e) {
throw new RuntimeException("Failed to load config file");
}
return new ResourceConfig(HystricsMetricsControllerTest.class, HystrixStreamFeature.class);
}
protected String getPath() {
return "hystrix.stream";
}
protected boolean isStreamValid(String data) {
return data.contains("\"type\":\"HystrixThreadPool\"") && data.contains("\"currentCompletedTaskCount\":" + requestCount.get());
}
@Test
public void testInfiniteStream() throws Exception {
executeHystrixCommand(); // Execute a Hystrix command so that metrics are initialized.
EventInput stream = getStream(); // Invoke Stream API which returns a steady stream output.
try {
validateStream(stream, 1000); // Validate the stream.
System.out.println("Validated Stream Output 1");
executeHystrixCommand(); // Execute Hystrix Command again so that request count is updated.
validateStream(stream, 1000); // Stream should show updated request count
System.out.println("Validated Stream Output 2");
} finally {
if (stream != null) {
stream.close();
}
}
}
@Test
public void testConcurrency() throws Exception {
executeHystrixCommand(); // Execute a Hystrix command so that metrics are initialized.
List<EventInput> streamList = new ArrayList<EventInput>();
try {
// Fire 3 requests, validate their responses and hold these connections.
for (int i = 0; i < 3; i++) {
EventInput stream = getStream();
System.out.println("Received Response for Request#" + (i + 1));
streamList.add(stream);
validateStream(stream, 1000);
System.out.println("Validated Response#" + (i + 1));
}
// Fourth request should fail since max configured connection is 3.
try {
streamList.add(getStreamFailFast());
Assert.fail("Expected 'ServiceUnavailableException' but, request went through.");
} catch (ServiceUnavailableException e) {
System.out.println("Got ServiceUnavailableException as expected.");
}
// Close one of the connections
streamList.get(0).close();
streamList.remove(0);
// Try again after closing one of the connections. This request should go through.
EventInput eventInput = getStream();
streamList.add(eventInput);
validateStream(eventInput, 1000);
} finally {
for (EventInput stream : streamList) {
if (stream != null) {
stream.close();
}
}
}
}
private void executeHystrixCommand() throws Exception {
Response response = target("hystrix/command").request().post(null);
assertEquals(204, response.getStatus());
System.out.println("Hystrix Command ran successfully.");
requestCount.incrementAndGet();
}
private EventInput getStream() throws Exception {
long timeElapsed = System.currentTimeMillis();
while (System.currentTimeMillis() - timeElapsed < 3000) {
try {
return getStreamFailFast();
} catch (Exception e) {
}
}
fail("Not able to connect to Stream end point");
return null;
}
private EventInput getStreamFailFast() throws Exception {
return target(getPath()).request().get(EventInput.class);
}
private void validateStream(EventInput eventInput, long waitTime) {
long timeElapsed = System.currentTimeMillis();
while (!eventInput.isClosed() && System.currentTimeMillis() - timeElapsed < waitTime) {
final InboundEvent inboundEvent = eventInput.read();
if (inboundEvent == null) {
Assert.fail("Failed while verifying stream. Looks like connection has been closed.");
break;
}
String data = inboundEvent.readData(String.class);
System.out.println(data);
if (isStreamValid(data)) {
return;
}
}
Assert.fail("Failed while verifying stream");
}
public static class TestHystrixCommand extends HystrixCommand<Void> {
protected TestHystrixCommand() {
super(HystrixCommandGroupKey.Factory.asKey("test"));
}
@Override
protected Void run() throws Exception {
return null;
}
}
}
| 4,539 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream-jaxrs/src/test/java/com/netflix/hystrix/contrib/metrics | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream-jaxrs/src/test/java/com/netflix/hystrix/contrib/metrics/controller/HystrixConfigControllerTest.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.hystrix.contrib.metrics.controller;
/**
* @author justinjose28
*
*/
public class HystrixConfigControllerTest extends HystricsMetricsControllerTest {
@Override
protected String getPath() {
return "hystrix/config.stream";
}
@Override
protected boolean isStreamValid(String data) {
return data.contains("\"type\":\"HystrixConfig\"");
}
}
| 4,540 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream-jaxrs/src/test/java/com/netflix/hystrix/contrib/metrics | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream-jaxrs/src/test/java/com/netflix/hystrix/contrib/metrics/controller/HystrixUtilizationControllerTest.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.hystrix.contrib.metrics.controller;
/**
* @author justinjose28
*
*/
public class HystrixUtilizationControllerTest extends HystricsMetricsControllerTest {
@Override
protected String getPath() {
return "hystrix/utilization.stream";
}
@Override
protected boolean isStreamValid(String data) {
return data.contains("\"type\":\"HystrixUtilization\"");
}
}
| 4,541 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream-jaxrs/src/test/java/com/netflix/hystrix/contrib/metrics | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream-jaxrs/src/test/java/com/netflix/hystrix/contrib/metrics/controller/StreamingOutputProviderTest.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.hystrix.contrib.metrics.controller;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import org.junit.Test;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import com.netflix.hystrix.contrib.metrics.HystrixStream;
import com.netflix.hystrix.contrib.metrics.HystrixStreamingOutputProvider;
public class StreamingOutputProviderTest {
private final Observable<String> streamOfOnNexts = Observable.interval(100, TimeUnit.MILLISECONDS).map(new Func1<Long, String>() {
@Override
public String call(Long timestamp) {
return "test-stream";
}
});
private final Observable<String> streamOfOnNextThenOnError = Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
try {
Thread.sleep(100);
subscriber.onNext("test-stream");
Thread.sleep(100);
subscriber.onError(new RuntimeException("stream failure"));
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}).subscribeOn(Schedulers.computation());
private final Observable<String> streamOfOnNextThenOnCompleted = Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
try {
Thread.sleep(100);
subscriber.onNext("test-stream");
Thread.sleep(100);
subscriber.onCompleted();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}).subscribeOn(Schedulers.computation());
private AbstractHystrixStreamController sse = new AbstractHystrixStreamController(streamOfOnNexts) {
private final AtomicInteger concurrentConnections = new AtomicInteger(0);
@Override
protected int getMaxNumberConcurrentConnectionsAllowed() {
return 2;
}
@Override
protected AtomicInteger getCurrentConnections() {
return concurrentConnections;
}
};
@Test
public void concurrencyTest() throws Exception {
Response resp = sse.handleRequest();
assertEquals(200, resp.getStatus());
assertEquals("text/event-stream;charset=UTF-8", resp.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE));
assertEquals("no-cache, no-store, max-age=0, must-revalidate", resp.getHeaders().getFirst(HttpHeaders.CACHE_CONTROL));
assertEquals("no-cache", resp.getHeaders().getFirst("Pragma"));
resp = sse.handleRequest();
assertEquals(200, resp.getStatus());
resp = sse.handleRequest();
assertEquals(503, resp.getStatus());
assertEquals("MaxConcurrentConnections reached: " + sse.getMaxNumberConcurrentConnectionsAllowed(), resp.getEntity());
sse.getCurrentConnections().decrementAndGet();
resp = sse.handleRequest();
assertEquals(200, resp.getStatus());
}
@Test
public void testInfiniteOnNextStream() throws Exception {
final PipedInputStream is = new PipedInputStream();
final PipedOutputStream os = new PipedOutputStream(is);
final AtomicInteger writes = new AtomicInteger(0);
final HystrixStream stream = new HystrixStream(streamOfOnNexts, 100, new AtomicInteger(1));
Thread streamingThread = startStreamingThread(stream, os);
verifyStream(is, writes);
Thread.sleep(1000); // Let the provider stream for some time.
streamingThread.interrupt(); // Stop streaming
os.close();
is.close();
System.out.println("Total lines:" + writes.get());
assertTrue(writes.get() >= 9); // Observable is configured to emit events in every 100 ms. So expect at least 9 in a second.
// Provider is expected to decrement connection count when streaming process is terminated.
assertTrue(hasNoMoreConcurrentConnections(stream.getConcurrentConnections(), 200, 10, TimeUnit.MILLISECONDS));
}
@Test
public void testOnError() throws Exception {
testStreamOnce(streamOfOnNextThenOnError);
}
@Test
public void testOnComplete() throws Exception {
testStreamOnce(streamOfOnNextThenOnCompleted);
}
// as the concurrentConnections count is decremented asynchronously, we need to potentially give the check a little bit of time
private static boolean hasNoMoreConcurrentConnections(AtomicInteger concurrentConnectionsCount, long waitDuration, long pollInterval, TimeUnit timeUnit) throws InterruptedException {
long period = (pollInterval > waitDuration) ? waitDuration : pollInterval;
for (long i = 0; i < waitDuration; i += period) {
if (concurrentConnectionsCount.get() == 0) {
return true;
}
Thread.sleep(timeUnit.toMillis(period));
}
return false;
}
private void testStreamOnce(Observable<String> observable) throws Exception {
final PipedInputStream is = new PipedInputStream();
final PipedOutputStream os = new PipedOutputStream(is);
final AtomicInteger writes = new AtomicInteger(0);
final HystrixStream stream = new HystrixStream(observable, 100, new AtomicInteger(1));
startStreamingThread(stream, os);
verifyStream(is, writes);
Thread.sleep(1000);
os.close();
is.close();
System.out.println("Total lines:" + writes.get());
assertTrue(writes.get() == 1);
assertTrue(hasNoMoreConcurrentConnections(stream.getConcurrentConnections(), 200, 10, TimeUnit.MILLISECONDS));
}
private static Thread startStreamingThread(final HystrixStream stream, final OutputStream outputSteam) {
Thread th1 = new Thread(new Runnable() {
@Override
public void run() {
try {
final HystrixStreamingOutputProvider provider = new HystrixStreamingOutputProvider();
provider.writeTo(stream, null, null, null, null, null, outputSteam);
} catch (IOException e) {
fail(e.getMessage());
}
}
});
th1.start();
return th1;
}
private static void verifyStream(final InputStream is, final AtomicInteger lineCount) {
Thread th2 = new Thread(new Runnable() {
public void run() {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
if (!"".equals(line)) {
System.out.println(line);
lineCount.incrementAndGet();
}
}
} catch (IOException e) {
fail("Failed while verifying streaming output.Stacktrace:" + e.getMessage());
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
fail("Failed while verifying streaming output.Stacktrace:" + e.getMessage());
}
}
}
}
});
th2.start();
}
}
| 4,542 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream-jaxrs/src/main/java/com/netflix/hystrix/contrib | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream-jaxrs/src/main/java/com/netflix/hystrix/contrib/metrics/HystrixStreamingOutputProvider.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.hystrix.contrib.metrics;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Subscriber;
import rx.Subscription;
import rx.schedulers.Schedulers;
/**
* {@link MessageBodyWriter} implementation which handles serialization of HystrixStream
*
*
* @author justinjose28
*
*/
@Provider
public class HystrixStreamingOutputProvider implements MessageBodyWriter<HystrixStream> {
private static final Logger LOGGER = LoggerFactory.getLogger(HystrixStreamingOutputProvider.class);
@Override
public boolean isWriteable(Class<?> t, Type gt, Annotation[] as, MediaType mediaType) {
return HystrixStream.class.isAssignableFrom(t);
}
@Override
public long getSize(HystrixStream o, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return -1;
}
@Override
public void writeTo(HystrixStream o, Class<?> t, Type gt, Annotation[] as, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, final OutputStream entity) throws IOException {
Subscription sampleSubscription = null;
final AtomicBoolean moreDataWillBeSent = new AtomicBoolean(true);
try {
sampleSubscription = o.getSampleStream().observeOn(Schedulers.io()).subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
LOGGER.error("HystrixSampleSseServlet: ({}) received unexpected OnCompleted from sample stream", getClass().getSimpleName());
moreDataWillBeSent.set(false);
}
@Override
public void onError(Throwable e) {
moreDataWillBeSent.set(false);
}
@Override
public void onNext(String sampleDataAsString) {
if (sampleDataAsString != null) {
try {
entity.write(("data: " + sampleDataAsString + "\n\n").getBytes());
entity.flush();
} catch (IOException ioe) {
moreDataWillBeSent.set(false);
}
}
}
});
while (moreDataWillBeSent.get()) {
try {
Thread.sleep(o.getPausePollerThreadDelayInMs());
} catch (InterruptedException e) {
moreDataWillBeSent.set(false);
}
}
} finally {
o.getConcurrentConnections().decrementAndGet();
if (sampleSubscription != null && !sampleSubscription.isUnsubscribed()) {
sampleSubscription.unsubscribe();
}
}
}
} | 4,543 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream-jaxrs/src/main/java/com/netflix/hystrix/contrib | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream-jaxrs/src/main/java/com/netflix/hystrix/contrib/metrics/HystrixStreamFeature.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.hystrix.contrib.metrics;
import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import com.netflix.hystrix.contrib.metrics.controller.HystrixConfigSseController;
import com.netflix.hystrix.contrib.metrics.controller.HystrixMetricsStreamController;
import com.netflix.hystrix.contrib.metrics.controller.HystrixRequestEventsSseController;
import com.netflix.hystrix.contrib.metrics.controller.HystrixUtilizationSseController;
/**
* @author justinjose28
*
*/
public class HystrixStreamFeature implements Feature {
@Override
public boolean configure(FeatureContext context) {
context.register(new HystrixMetricsStreamController());
context.register(new HystrixUtilizationSseController());
context.register(new HystrixRequestEventsSseController());
context.register(new HystrixConfigSseController());
context.register(HystrixStreamingOutputProvider.class);
return true;
}
}
| 4,544 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream-jaxrs/src/main/java/com/netflix/hystrix/contrib | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream-jaxrs/src/main/java/com/netflix/hystrix/contrib/metrics/HystrixStream.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.hystrix.contrib.metrics;
import java.util.concurrent.atomic.AtomicInteger;
import rx.Observable;
/**
* @author justinjose28
*
*/
public final class HystrixStream {
private final Observable<String> sampleStream;
private final int pausePollerThreadDelayInMs;
private final AtomicInteger concurrentConnections;
public HystrixStream(Observable<String> sampleStream, int pausePollerThreadDelayInMs, AtomicInteger concurrentConnections) {
this.sampleStream = sampleStream;
this.pausePollerThreadDelayInMs = pausePollerThreadDelayInMs;
this.concurrentConnections = concurrentConnections;
}
public Observable<String> getSampleStream() {
return sampleStream;
}
public int getPausePollerThreadDelayInMs() {
return pausePollerThreadDelayInMs;
}
public AtomicInteger getConcurrentConnections() {
return concurrentConnections;
}
} | 4,545 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream-jaxrs/src/main/java/com/netflix/hystrix/contrib/metrics | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream-jaxrs/src/main/java/com/netflix/hystrix/contrib/metrics/controller/HystrixConfigSseController.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.hystrix.contrib.metrics.controller;
import java.util.concurrent.atomic.AtomicInteger;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;
import rx.functions.Func1;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.hystrix.config.HystrixConfiguration;
import com.netflix.hystrix.config.HystrixConfigurationStream;
import com.netflix.hystrix.contrib.metrics.HystrixStreamFeature;
import com.netflix.hystrix.serial.SerialHystrixConfiguration;
/**
* Streams Hystrix config in text/event-stream format.
* <p>
* Install by:
* <p>
* 1) Including hystrix-metrics-event-stream-jaxrs-*.jar in your classpath.
* <p>
* 2) Register {@link HystrixStreamFeature} in your {@link Application}.
* <p>
* 3) Stream will be available at path /hystrix/config.stream
* <p>
*
* @author justinjose28
*
*/
@Path("/hystrix/config.stream")
public class HystrixConfigSseController extends AbstractHystrixStreamController {
private static final AtomicInteger concurrentConnections = new AtomicInteger(0);
private static DynamicIntProperty maxConcurrentConnections = DynamicPropertyFactory.getInstance().getIntProperty("hystrix.config.stream.maxConcurrentConnections", 5);
public HystrixConfigSseController() {
super(HystrixConfigurationStream.getInstance().observe().map(new Func1<HystrixConfiguration, String>() {
@Override
public String call(HystrixConfiguration hystrixConfiguration) {
return SerialHystrixConfiguration.toJsonString(hystrixConfiguration);
}
}));
}
@GET
public Response getStream() {
return handleRequest();
}
@Override
protected int getMaxNumberConcurrentConnectionsAllowed() {
return maxConcurrentConnections.get();
}
@Override
protected AtomicInteger getCurrentConnections() {
return concurrentConnections;
}
}
| 4,546 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream-jaxrs/src/main/java/com/netflix/hystrix/contrib/metrics | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream-jaxrs/src/main/java/com/netflix/hystrix/contrib/metrics/controller/HystrixMetricsStreamController.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.hystrix.contrib.metrics.controller;
import java.util.concurrent.atomic.AtomicInteger;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;
import rx.Observable;
import rx.functions.Func1;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.hystrix.contrib.metrics.HystrixStreamFeature;
import com.netflix.hystrix.metric.consumer.HystrixDashboardStream;
import com.netflix.hystrix.serial.SerialHystrixDashboardData;
/**
* Streams Hystrix metrics in text/event-stream format.
* <p>
* Install by:
* <p>
* 1) Including hystrix-metrics-event-stream-jaxrs-*.jar in your classpath.
* <p>
* 2) Register {@link HystrixStreamFeature} in your {@link Application}.
* <p>
* 3) Stream will be available at path /hystrix.stream
* <p>
*
* @author justinjose28
*
*/
@Path("/hystrix.stream")
public class HystrixMetricsStreamController extends AbstractHystrixStreamController {
private static final AtomicInteger concurrentConnections = new AtomicInteger(0);
private static DynamicIntProperty maxConcurrentConnections = DynamicPropertyFactory.getInstance().getIntProperty("hystrix.config.stream.maxConcurrentConnections", 5);
public HystrixMetricsStreamController() {
super(HystrixDashboardStream.getInstance().observe().concatMap(new Func1<HystrixDashboardStream.DashboardData, Observable<String>>() {
@Override
public Observable<String> call(HystrixDashboardStream.DashboardData dashboardData) {
return Observable.from(SerialHystrixDashboardData.toMultipleJsonStrings(dashboardData));
}
}));
}
@GET
public Response getStream() {
return handleRequest();
}
@Override
protected int getMaxNumberConcurrentConnectionsAllowed() {
return maxConcurrentConnections.get();
}
@Override
protected AtomicInteger getCurrentConnections() {
return concurrentConnections;
}
}
| 4,547 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream-jaxrs/src/main/java/com/netflix/hystrix/contrib/metrics | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream-jaxrs/src/main/java/com/netflix/hystrix/contrib/metrics/controller/HystrixRequestEventsSseController.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.hystrix.contrib.metrics.controller;
import java.util.concurrent.atomic.AtomicInteger;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;
import rx.functions.Func1;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.hystrix.contrib.metrics.HystrixStreamFeature;
import com.netflix.hystrix.metric.HystrixRequestEvents;
import com.netflix.hystrix.metric.HystrixRequestEventsStream;
import com.netflix.hystrix.serial.SerialHystrixRequestEvents;
/**
* Resource that writes SSE JSON every time a request is made
*
* <p>
* Install by:
* <p>
* 1) Including hystrix-metrics-event-stream-jaxrs-*.jar in your classpath.
* <p>
* 2) Register {@link HystrixStreamFeature} in your {@link Application}.
* <p>
* 3) Stream will be available at path /hystrix/request.stream
* <p>
*
* @author justinjose28
*
*/
@Path("/hystrix/request.stream")
public class HystrixRequestEventsSseController extends AbstractHystrixStreamController {
private static final AtomicInteger concurrentConnections = new AtomicInteger(0);
private static DynamicIntProperty maxConcurrentConnections = DynamicPropertyFactory.getInstance().getIntProperty("hystrix.config.stream.maxConcurrentConnections", 5);
public HystrixRequestEventsSseController() {
super(HystrixRequestEventsStream.getInstance().observe().map(new Func1<HystrixRequestEvents, String>() {
@Override
public String call(HystrixRequestEvents requestEvents) {
return SerialHystrixRequestEvents.toJsonString(requestEvents);
}
}));
}
@GET
public Response getStream() {
return handleRequest();
}
@Override
protected int getMaxNumberConcurrentConnectionsAllowed() {
return maxConcurrentConnections.get();
}
@Override
protected AtomicInteger getCurrentConnections() {
return concurrentConnections;
}
}
| 4,548 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream-jaxrs/src/main/java/com/netflix/hystrix/contrib/metrics | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream-jaxrs/src/main/java/com/netflix/hystrix/contrib/metrics/controller/HystrixUtilizationSseController.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.hystrix.contrib.metrics.controller;
import java.util.concurrent.atomic.AtomicInteger;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;
import rx.functions.Func1;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.hystrix.contrib.metrics.HystrixStreamFeature;
import com.netflix.hystrix.metric.sample.HystrixUtilization;
import com.netflix.hystrix.metric.sample.HystrixUtilizationStream;
import com.netflix.hystrix.serial.SerialHystrixUtilization;
/**
* Streams Hystrix config in text/event-stream format.
* <p>
* Install by:
* <p>
* 1) Including hystrix-metrics-event-stream-jaxrs-*.jar in your classpath.
* <p>
* 2) Register {@link HystrixStreamFeature} in your {@link Application}.
* <p>
* 3) Stream will be available at path /hystrix/utilization.stream
* <p>
*
* @author justinjose28
*
*/
@Path("/hystrix/utilization.stream")
public class HystrixUtilizationSseController extends AbstractHystrixStreamController {
private static final AtomicInteger concurrentConnections = new AtomicInteger(0);
private static DynamicIntProperty maxConcurrentConnections = DynamicPropertyFactory.getInstance().getIntProperty("hystrix.config.stream.maxConcurrentConnections", 5);
public HystrixUtilizationSseController() {
super(HystrixUtilizationStream.getInstance().observe().map(new Func1<HystrixUtilization, String>() {
@Override
public String call(HystrixUtilization hystrixUtilization) {
return SerialHystrixUtilization.toJsonString(hystrixUtilization);
}
}));
}
@GET
public Response getStream() {
return handleRequest();
}
@Override
protected int getMaxNumberConcurrentConnectionsAllowed() {
return maxConcurrentConnections.get();
}
@Override
protected AtomicInteger getCurrentConnections() {
return concurrentConnections;
}
}
| 4,549 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream-jaxrs/src/main/java/com/netflix/hystrix/contrib/metrics | Create_ds/Hystrix/hystrix-contrib/hystrix-metrics-event-stream-jaxrs/src/main/java/com/netflix/hystrix/contrib/metrics/controller/AbstractHystrixStreamController.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.hystrix.contrib.metrics.controller;
import java.util.concurrent.atomic.AtomicInteger;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import com.netflix.hystrix.contrib.metrics.HystrixStream;
import com.netflix.hystrix.contrib.metrics.HystrixStreamingOutputProvider;
/**
* @author justinjose28
*
*/
public abstract class AbstractHystrixStreamController {
protected final Observable<String> sampleStream;
static final Logger logger = LoggerFactory.getLogger(AbstractHystrixStreamController.class);
// wake up occasionally and check that poller is still alive. this value controls how often
protected static final int DEFAULT_PAUSE_POLLER_THREAD_DELAY_IN_MS = 500;
private final int pausePollerThreadDelayInMs;
protected AbstractHystrixStreamController(Observable<String> sampleStream) {
this(sampleStream, DEFAULT_PAUSE_POLLER_THREAD_DELAY_IN_MS);
}
protected AbstractHystrixStreamController(Observable<String> sampleStream, int pausePollerThreadDelayInMs) {
this.sampleStream = sampleStream;
this.pausePollerThreadDelayInMs = pausePollerThreadDelayInMs;
}
protected abstract int getMaxNumberConcurrentConnectionsAllowed();
protected abstract AtomicInteger getCurrentConnections();
/**
* Maintain an open connection with the client. On initial connection send latest data of each requested event type and subsequently send all changes for each requested event type.
*
* @return JAX-RS Response - Serialization will be handled by {@link HystrixStreamingOutputProvider}
*/
protected Response handleRequest() {
ResponseBuilder builder = null;
/* ensure we aren't allowing more connections than we want */
int numberConnections = getCurrentConnections().get();
int maxNumberConnectionsAllowed = getMaxNumberConcurrentConnectionsAllowed(); // may change at runtime, so look this up for each request
if (numberConnections >= maxNumberConnectionsAllowed) {
builder = Response.status(Status.SERVICE_UNAVAILABLE).entity("MaxConcurrentConnections reached: " + maxNumberConnectionsAllowed);
} else {
/* initialize response */
builder = Response.status(Status.OK);
builder.header(HttpHeaders.CONTENT_TYPE, "text/event-stream;charset=UTF-8");
builder.header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate");
builder.header("Pragma", "no-cache");
getCurrentConnections().incrementAndGet();
builder.entity(new HystrixStream(sampleStream, pausePollerThreadDelayInMs, getCurrentConnections()));
}
return builder.build();
}
}
| 4,550 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-codahale-metrics-publisher/src/test/java/com/netflix/hystrix/contrib | Create_ds/Hystrix/hystrix-contrib/hystrix-codahale-metrics-publisher/src/test/java/com/netflix/hystrix/contrib/codahalemetricspublisher/ConfigurableCodaHaleMetricFilterTest.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.codahalemetricspublisher;
import com.codahale.metrics.Metric;
import com.netflix.config.DynamicBooleanProperty;
import com.netflix.config.DynamicPropertyFactory;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* Test the ConfigurableCodaHaleMetricFilter
*
* @author Simon Irving
*/
public class ConfigurableCodaHaleMetricFilterTest {
private Metric metric = mock(Metric.class);
private final static DynamicPropertyFactory archiausPropertyFactory = mock(DynamicPropertyFactory.class);
private static final DynamicBooleanProperty DYNAMIC_BOOLEAN_TRUE = mock(DynamicBooleanProperty.class);
private static final DynamicBooleanProperty DYNAMIC_BOOLEAN_FALSE = mock(DynamicBooleanProperty.class);
@BeforeClass
public static void initialiseMocks()
{
when(archiausPropertyFactory.getBooleanProperty(any(String.class), any(Boolean.class))).thenReturn(DYNAMIC_BOOLEAN_FALSE);
when(archiausPropertyFactory.getBooleanProperty(eq("this.metric.is.allowed"), any(Boolean.class))).thenReturn(DYNAMIC_BOOLEAN_TRUE);
when(DYNAMIC_BOOLEAN_TRUE.get()).thenReturn(true);
when(DYNAMIC_BOOLEAN_FALSE.get()).thenReturn(false);
}
@After
public void assertMetricsNotTouched()
{
verifyZeroInteractions(metric);
}
@Test
public void testMetricConfiguredInFilterWithFilterEnabled()
{
when(archiausPropertyFactory.getBooleanProperty(eq("filter.graphite.metrics"), any(Boolean.class))).thenReturn(DYNAMIC_BOOLEAN_TRUE);
ConfigurableCodaHaleMetricFilter filter = new ConfigurableCodaHaleMetricFilter(archiausPropertyFactory);
assertTrue(filter.matches("this.metric.is.allowed", metric));
}
@Test
public void testMetricConfiguredInFilterWithFilterDisabled()
{
when(archiausPropertyFactory.getBooleanProperty(eq("filter.graphite.metrics"), any(Boolean.class))).thenReturn(DYNAMIC_BOOLEAN_FALSE);
ConfigurableCodaHaleMetricFilter filter = new ConfigurableCodaHaleMetricFilter(archiausPropertyFactory);
assertTrue(filter.matches("this.metric.is.allowed", metric));
}
@Test
public void testMetricNotConfiguredInFilterWithFilterEnabled()
{
when(archiausPropertyFactory.getBooleanProperty(eq("filter.graphite.metrics"), any(Boolean.class))).thenReturn(DYNAMIC_BOOLEAN_TRUE);
ConfigurableCodaHaleMetricFilter filter = new ConfigurableCodaHaleMetricFilter(archiausPropertyFactory);
assertFalse(filter.matches("this.metric.is.not.allowed", metric));
}
@Test
public void testMetricNotConfiguredInFilterWithFilterDisabled()
{
when(archiausPropertyFactory.getBooleanProperty(eq("filter.graphite.metrics"), any(Boolean.class))).thenReturn(DYNAMIC_BOOLEAN_FALSE);
ConfigurableCodaHaleMetricFilter filter = new ConfigurableCodaHaleMetricFilter(archiausPropertyFactory);
assertTrue(filter.matches("this.metric.is.not.allowed", metric));
}
}
| 4,551 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-codahale-metrics-publisher/src/test/java/com/netflix/hystrix/contrib | Create_ds/Hystrix/hystrix-contrib/hystrix-codahale-metrics-publisher/src/test/java/com/netflix/hystrix/contrib/codahalemetricspublisher/HystrixCodaHaleMetricsPublisherCommandTest.java | package com.netflix.hystrix.contrib.codahalemetricspublisher;
import com.codahale.metrics.MetricRegistry;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.strategy.HystrixPlugins;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class HystrixCodaHaleMetricsPublisherCommandTest {
private final MetricRegistry metricRegistry = new MetricRegistry();
@Before
public void setup() {
HystrixPlugins.getInstance().registerMetricsPublisher(new HystrixCodaHaleMetricsPublisher("hystrix", metricRegistry));
}
@Test
public void testCommandSuccess() throws InterruptedException {
Command command = new Command();
command.execute();
Thread.sleep(1000);
assertThat((Long) metricRegistry.getGauges().get("hystrix.testGroup.testCommand.countSuccess").getValue(), is(1L));
assertThat((Long) metricRegistry.getGauges().get("hystrix.HystrixThreadPool.threadGroup.totalTaskCount").getValue(), is(1L));
}
private static class Command extends HystrixCommand<Void> {
final static HystrixCommandKey hystrixCommandKey = HystrixCommandKey.Factory.asKey("testCommand");
final static HystrixCommandGroupKey hystrixCommandGroupKey = HystrixCommandGroupKey.Factory.asKey("testGroup");
final static HystrixThreadPoolKey hystrixThreadPool = HystrixThreadPoolKey.Factory.asKey("threadGroup");
Command() {
super(Setter.withGroupKey(hystrixCommandGroupKey).andCommandKey(hystrixCommandKey).andThreadPoolKey(hystrixThreadPool));
}
@Override
protected Void run() throws Exception {
return null;
}
}
}
| 4,552 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-codahale-metrics-publisher/src/main/java/com/netflix/hystrix/contrib | Create_ds/Hystrix/hystrix-contrib/hystrix-codahale-metrics-publisher/src/main/java/com/netflix/hystrix/contrib/codahalemetricspublisher/HystrixCodaHaleMetricsPublisherCommand.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.codahalemetricspublisher;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricRegistry;
import com.netflix.hystrix.*;
import com.netflix.hystrix.metric.consumer.*;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherCommand;
import com.netflix.hystrix.util.HystrixRollingNumberEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.functions.Func0;
/**
* Implementation of {@link HystrixMetricsPublisherCommand} using Coda Hale Metrics (https://github.com/codahale/metrics)
*/
public class HystrixCodaHaleMetricsPublisherCommand implements HystrixMetricsPublisherCommand {
private final String metricsRootNode;
private final HystrixCommandKey key;
private final HystrixCommandGroupKey commandGroupKey;
private final HystrixCommandMetrics metrics;
private final HystrixCircuitBreaker circuitBreaker;
private final HystrixCommandProperties properties;
private final MetricRegistry metricRegistry;
private final String metricGroup;
private final String metricType;
static final Logger logger = LoggerFactory.getLogger(HystrixCodaHaleMetricsPublisherCommand.class);
public HystrixCodaHaleMetricsPublisherCommand(String metricsRootNode, HystrixCommandKey commandKey, HystrixCommandGroupKey commandGroupKey, HystrixCommandMetrics metrics, HystrixCircuitBreaker circuitBreaker, HystrixCommandProperties properties, MetricRegistry metricRegistry) {
this.metricsRootNode = metricsRootNode;
this.key = commandKey;
this.commandGroupKey = commandGroupKey;
this.metrics = metrics;
this.circuitBreaker = circuitBreaker;
this.properties = properties;
this.metricRegistry = metricRegistry;
this.metricGroup = commandGroupKey.name();
this.metricType = key.name();
}
/**
* An implementation note. If there's a version mismatch between hystrix-core and hystrix-codahale-metrics-publisher,
* the code below may reference a HystrixRollingNumberEvent that does not exist in hystrix-core. If this happens,
* a j.l.NoSuchFieldError occurs. Since this data is not being generated by hystrix-core, it's safe to count it as 0
* and we should log an error to get users to update their dependency set.
*/
@Override
public void initialize() {
metricRegistry.register(createMetricName("isCircuitBreakerOpen"), new Gauge<Boolean>() {
@Override
public Boolean getValue() {
return circuitBreaker.isOpen();
}
});
// allow monitor to know exactly at what point in time these stats are for so they can be plotted accurately
metricRegistry.register(createMetricName("currentTime"), new Gauge<Long>() {
@Override
public Long getValue() {
return System.currentTimeMillis();
}
});
// cumulative counts
safelyCreateCumulativeCountForEvent("countBadRequests", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.BAD_REQUEST;
}
});
safelyCreateCumulativeCountForEvent("countCollapsedRequests", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.COLLAPSED;
}
});
safelyCreateCumulativeCountForEvent("countEmit", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.EMIT;
}
});
safelyCreateCumulativeCountForEvent("countExceptionsThrown", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.EXCEPTION_THROWN;
}
});
safelyCreateCumulativeCountForEvent("countFailure", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.FAILURE;
}
});
safelyCreateCumulativeCountForEvent("countFallbackEmit", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.FALLBACK_EMIT;
}
});
safelyCreateCumulativeCountForEvent("countFallbackFailure", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.FALLBACK_FAILURE;
}
});
safelyCreateCumulativeCountForEvent("countFallbackDisabled", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.FALLBACK_DISABLED;
}
});
safelyCreateCumulativeCountForEvent("countFallbackMissing", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.FALLBACK_MISSING;
}
});
safelyCreateCumulativeCountForEvent("countFallbackRejection", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.FALLBACK_REJECTION;
}
});
safelyCreateCumulativeCountForEvent("countFallbackSuccess", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.FALLBACK_SUCCESS;
}
});
safelyCreateCumulativeCountForEvent("countResponsesFromCache", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.RESPONSE_FROM_CACHE;
}
});
safelyCreateCumulativeCountForEvent("countSemaphoreRejected", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.SEMAPHORE_REJECTED;
}
});
safelyCreateCumulativeCountForEvent("countShortCircuited", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.SHORT_CIRCUITED;
}
});
safelyCreateCumulativeCountForEvent("countSuccess", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.SUCCESS;
}
});
safelyCreateCumulativeCountForEvent("countThreadPoolRejected", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.THREAD_POOL_REJECTED;
}
});
safelyCreateCumulativeCountForEvent("countTimeout", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.TIMEOUT;
}
});
// rolling counts
safelyCreateRollingCountForEvent("rollingCountBadRequests", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.BAD_REQUEST;
}
});
safelyCreateRollingCountForEvent("rollingCountCollapsedRequests", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.COLLAPSED;
}
});
safelyCreateRollingCountForEvent("rollingCountEmit", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.EMIT;
}
});
safelyCreateRollingCountForEvent("rollingCountExceptionsThrown", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.EXCEPTION_THROWN;
}
});
safelyCreateRollingCountForEvent("rollingCountFailure", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.FAILURE;
}
});
safelyCreateRollingCountForEvent("rollingCountFallbackEmit", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.FALLBACK_EMIT;
}
});
safelyCreateRollingCountForEvent("rollingCountFallbackFailure", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.FALLBACK_FAILURE;
}
});
safelyCreateRollingCountForEvent("rollingCountFallbackDisabled", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.FALLBACK_DISABLED;
}
});
safelyCreateRollingCountForEvent("rollingCountFallbackMissing", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.FALLBACK_MISSING;
}
});
safelyCreateRollingCountForEvent("rollingCountFallbackRejection", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.FALLBACK_REJECTION;
}
});
safelyCreateRollingCountForEvent("rollingCountFallbackSuccess", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.FALLBACK_SUCCESS;
}
});
safelyCreateRollingCountForEvent("rollingCountResponsesFromCache", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.RESPONSE_FROM_CACHE;
}
});
safelyCreateRollingCountForEvent("rollingCountSemaphoreRejected", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.SEMAPHORE_REJECTED;
}
});
safelyCreateRollingCountForEvent("rollingCountShortCircuited", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.SHORT_CIRCUITED;
}
});
safelyCreateRollingCountForEvent("rollingCountSuccess", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.SUCCESS;
}
});
safelyCreateRollingCountForEvent("rollingCountThreadPoolRejected", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.THREAD_POOL_REJECTED;
}
});
safelyCreateRollingCountForEvent("rollingCountTimeout", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.TIMEOUT;
}
});
// the rolling number of MaxConcurrentExecutionCount. Can be used to determine saturation
safelyCreateRollingCountForEvent("rollingMaxConcurrentExecutionCount", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.COMMAND_MAX_ACTIVE;
}
});
// the number of executionSemaphorePermits in use right now
metricRegistry.register(createMetricName("executionSemaphorePermitsInUse"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getCurrentConcurrentExecutionCount();
}
});
// error percentage derived from current metrics
metricRegistry.register(createMetricName("errorPercentage"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getHealthCounts().getErrorPercentage();
}
});
// latency metrics
metricRegistry.register(createMetricName("latencyExecute_mean"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getExecutionTimeMean();
}
});
metricRegistry.register(createMetricName("latencyExecute_percentile_5"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getExecutionTimePercentile(5);
}
});
metricRegistry.register(createMetricName("latencyExecute_percentile_25"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getExecutionTimePercentile(25);
}
});
metricRegistry.register(createMetricName("latencyExecute_percentile_50"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getExecutionTimePercentile(50);
}
});
metricRegistry.register(createMetricName("latencyExecute_percentile_75"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getExecutionTimePercentile(75);
}
});
metricRegistry.register(createMetricName("latencyExecute_percentile_90"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getExecutionTimePercentile(90);
}
});
metricRegistry.register(createMetricName("latencyExecute_percentile_99"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getExecutionTimePercentile(99);
}
});
metricRegistry.register(createMetricName("latencyExecute_percentile_995"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getExecutionTimePercentile(99.5);
}
});
metricRegistry.register(createMetricName("latencyTotal_mean"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getTotalTimeMean();
}
});
metricRegistry.register(createMetricName("latencyTotal_percentile_5"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getTotalTimePercentile(5);
}
});
metricRegistry.register(createMetricName("latencyTotal_percentile_25"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getTotalTimePercentile(25);
}
});
metricRegistry.register(createMetricName("latencyTotal_percentile_50"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getTotalTimePercentile(50);
}
});
metricRegistry.register(createMetricName("latencyTotal_percentile_75"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getTotalTimePercentile(75);
}
});
metricRegistry.register(createMetricName("latencyTotal_percentile_90"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getTotalTimePercentile(90);
}
});
metricRegistry.register(createMetricName("latencyTotal_percentile_99"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getTotalTimePercentile(99);
}
});
metricRegistry.register(createMetricName("latencyTotal_percentile_995"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getTotalTimePercentile(99.5);
}
});
// group
metricRegistry.register(createMetricName("commandGroup"), new Gauge<String>() {
@Override
public String getValue() {
return commandGroupKey != null ? commandGroupKey.name() : null;
}
});
// properties (so the values can be inspected and monitored)
metricRegistry.register(createMetricName("propertyValue_rollingStatisticalWindowInMilliseconds"), new Gauge<Number>() {
@Override
public Number getValue() {
return properties.metricsRollingStatisticalWindowInMilliseconds().get();
}
});
metricRegistry.register(createMetricName("propertyValue_circuitBreakerRequestVolumeThreshold"), new Gauge<Number>() {
@Override
public Number getValue() {
return properties.circuitBreakerRequestVolumeThreshold().get();
}
});
metricRegistry.register(createMetricName("propertyValue_circuitBreakerSleepWindowInMilliseconds"), new Gauge<Number>() {
@Override
public Number getValue() {
return properties.circuitBreakerSleepWindowInMilliseconds().get();
}
});
metricRegistry.register(createMetricName("propertyValue_circuitBreakerErrorThresholdPercentage"), new Gauge<Number>() {
@Override
public Number getValue() {
return properties.circuitBreakerErrorThresholdPercentage().get();
}
});
metricRegistry.register(createMetricName("propertyValue_circuitBreakerForceOpen"), new Gauge<Boolean>() {
@Override
public Boolean getValue() {
return properties.circuitBreakerForceOpen().get();
}
});
metricRegistry.register(createMetricName("propertyValue_circuitBreakerForceClosed"), new Gauge<Boolean>() {
@Override
public Boolean getValue() {
return properties.circuitBreakerForceClosed().get();
}
});
metricRegistry.register(createMetricName("propertyValue_executionIsolationThreadTimeoutInMilliseconds"), new Gauge<Number>() {
@Override
public Number getValue() {
return properties.executionTimeoutInMilliseconds().get();
}
});
metricRegistry.register(createMetricName("propertyValue_executionTimeoutInMilliseconds"), new Gauge<Number>() {
@Override
public Number getValue() {
return properties.executionTimeoutInMilliseconds().get();
}
});
metricRegistry.register(createMetricName("propertyValue_executionIsolationStrategy"), new Gauge<String>() {
@Override
public String getValue() {
return properties.executionIsolationStrategy().get().name();
}
});
metricRegistry.register(createMetricName("propertyValue_metricsRollingPercentileEnabled"), new Gauge<Boolean>() {
@Override
public Boolean getValue() {
return properties.metricsRollingPercentileEnabled().get();
}
});
metricRegistry.register(createMetricName("propertyValue_requestCacheEnabled"), new Gauge<Boolean>() {
@Override
public Boolean getValue() {
return properties.requestCacheEnabled().get();
}
});
metricRegistry.register(createMetricName("propertyValue_requestLogEnabled"), new Gauge<Boolean>() {
@Override
public Boolean getValue() {
return properties.requestLogEnabled().get();
}
});
metricRegistry.register(createMetricName("propertyValue_executionIsolationSemaphoreMaxConcurrentRequests"), new Gauge<Number>() {
@Override
public Number getValue() {
return properties.executionIsolationSemaphoreMaxConcurrentRequests().get();
}
});
metricRegistry.register(createMetricName("propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests"), new Gauge<Number>() {
@Override
public Number getValue() {
return properties.fallbackIsolationSemaphoreMaxConcurrentRequests().get();
}
});
RollingCommandEventCounterStream.getInstance(key, properties).startCachingStreamValuesIfUnstarted();
CumulativeCommandEventCounterStream.getInstance(key, properties).startCachingStreamValuesIfUnstarted();
RollingCommandLatencyDistributionStream.getInstance(key, properties).startCachingStreamValuesIfUnstarted();
RollingCommandUserLatencyDistributionStream.getInstance(key, properties).startCachingStreamValuesIfUnstarted();
RollingCommandMaxConcurrencyStream.getInstance(key, properties).startCachingStreamValuesIfUnstarted();
}
protected String createMetricName(String name) {
return MetricRegistry.name(metricsRootNode, metricGroup, metricType, name);
}
protected void createCumulativeCountForEvent(final String name, final HystrixRollingNumberEvent event) {
metricRegistry.register(createMetricName(name), new Gauge<Long>() {
@Override
public Long getValue() {
return metrics.getCumulativeCount(event);
}
});
}
protected void safelyCreateCumulativeCountForEvent(final String name, final Func0<HystrixRollingNumberEvent> eventThunk) {
metricRegistry.register(createMetricName(name), new Gauge<Long>() {
@Override
public Long getValue() {
try {
return metrics.getCumulativeCount(eventThunk.call());
} catch (NoSuchFieldError error) {
logger.error("While publishing CodaHale metrics, error looking up eventType for : {}. Please check that all Hystrix versions are the same!", name);
return 0L;
}
}
});
}
protected void createRollingCountForEvent(final String name, final HystrixRollingNumberEvent event) {
metricRegistry.register(createMetricName(name), new Gauge<Long>() {
@Override
public Long getValue() {
return metrics.getRollingCount(event);
}
});
}
protected void safelyCreateRollingCountForEvent(final String name, final Func0<HystrixRollingNumberEvent> eventThunk) {
metricRegistry.register(createMetricName(name), new Gauge<Long>() {
@Override
public Long getValue() {
try {
return metrics.getRollingCount(eventThunk.call());
} catch (NoSuchFieldError error) {
logger.error("While publishing CodaHale metrics, error looking up eventType for : {}. Please check that all Hystrix versions are the same!", name);
return 0L;
}
}
});
}
}
| 4,553 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-codahale-metrics-publisher/src/main/java/com/netflix/hystrix/contrib | Create_ds/Hystrix/hystrix-contrib/hystrix-codahale-metrics-publisher/src/main/java/com/netflix/hystrix/contrib/codahalemetricspublisher/ConfigurableCodaHaleMetricFilter.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.codahalemetricspublisher;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricFilter;
import com.netflix.config.DynamicPropertyFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An implementation of @MetricFilter based upon an Archaius DynamicPropertyFactory
*
* To enable this filter, the property 'filter.graphite.metrics' must be set to TRUE
*
* If this is the case, metrics will be filtered unless METRIC_NAME = true is set in
* the properties
*
*
* eg HystrixCommand.IndiciaService.GetIndicia.countFailure = true
*
*
* For detail on how the metric names are constructed, refer to the source of the
*
* {@link HystrixCodaHaleMetricsPublisherCommand}
*
* and
*
* {@link HystrixCodaHaleMetricsPublisherThreadPool}
*
* classes.
*
* @author Simon Irving
*/
public class ConfigurableCodaHaleMetricFilter implements MetricFilter{
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurableCodaHaleMetricFilter.class);
private DynamicPropertyFactory archaiusPropertyFactory;
public ConfigurableCodaHaleMetricFilter(DynamicPropertyFactory archaiusPropertyFactory)
{
this.archaiusPropertyFactory = archaiusPropertyFactory;
}
@Override
public boolean matches(String s, Metric metric) {
if (!isFilterEnabled())
{
return true;
}
boolean matchesFilter = archaiusPropertyFactory.getBooleanProperty(s, false).get();
LOGGER.debug("Does metric [{}] match filter? [{}]",s,matchesFilter);
return matchesFilter;
}
protected boolean isFilterEnabled() {
boolean filterEnabled = archaiusPropertyFactory.getBooleanProperty("filter.graphite.metrics", false).get();
LOGGER.debug("Is filter enabled? [{}]", filterEnabled);
return filterEnabled;
}
}
| 4,554 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-codahale-metrics-publisher/src/main/java/com/netflix/hystrix/contrib | Create_ds/Hystrix/hystrix-contrib/hystrix-codahale-metrics-publisher/src/main/java/com/netflix/hystrix/contrib/codahalemetricspublisher/HystrixCodaHaleMetricsPublisher.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.codahalemetricspublisher;
import com.codahale.metrics.MetricRegistry;
import com.netflix.hystrix.HystrixCircuitBreaker;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserMetrics;
import com.netflix.hystrix.HystrixCollapserProperties;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandMetrics;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolMetrics;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisher;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherCollapser;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherCommand;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherThreadPool;
/**
* Coda Hale Metrics (https://github.com/codahale/metrics) implementation of {@link HystrixMetricsPublisher}.
*/
public class HystrixCodaHaleMetricsPublisher extends HystrixMetricsPublisher {
private final String metricsRootNode;
private final MetricRegistry metricRegistry;
public HystrixCodaHaleMetricsPublisher(MetricRegistry metricRegistry) {
this(null, metricRegistry);
}
public HystrixCodaHaleMetricsPublisher(String metricsRootNode, MetricRegistry metricRegistry) {
this.metricsRootNode = metricsRootNode;
this.metricRegistry = metricRegistry;
}
@Override
public HystrixMetricsPublisherCommand getMetricsPublisherForCommand(HystrixCommandKey commandKey, HystrixCommandGroupKey commandGroupKey, HystrixCommandMetrics metrics, HystrixCircuitBreaker circuitBreaker, HystrixCommandProperties properties) {
return new HystrixCodaHaleMetricsPublisherCommand(metricsRootNode, commandKey, commandGroupKey, metrics, circuitBreaker, properties, metricRegistry);
}
@Override
public HystrixMetricsPublisherThreadPool getMetricsPublisherForThreadPool(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolMetrics metrics, HystrixThreadPoolProperties properties) {
return new HystrixCodaHaleMetricsPublisherThreadPool(metricsRootNode, threadPoolKey, metrics, properties, metricRegistry);
}
@Override
public HystrixMetricsPublisherCollapser getMetricsPublisherForCollapser(HystrixCollapserKey collapserKey, HystrixCollapserMetrics metrics, HystrixCollapserProperties properties) {
return new HystrixCodaHaleMetricsPublisherCollapser(collapserKey, metrics, properties, metricRegistry);
}
}
| 4,555 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-codahale-metrics-publisher/src/main/java/com/netflix/hystrix/contrib | Create_ds/Hystrix/hystrix-contrib/hystrix-codahale-metrics-publisher/src/main/java/com/netflix/hystrix/contrib/codahalemetricspublisher/HystrixCodaHaleMetricsPublisherCollapser.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.codahalemetricspublisher;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricRegistry;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserMetrics;
import com.netflix.hystrix.HystrixCollapserProperties;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherCollapser;
import com.netflix.hystrix.util.HystrixRollingNumberEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.functions.Func0;
/**
* Implementation of {@link HystrixMetricsPublisherCollapser} using Coda Hale Metrics (https://github.com/codahale/metrics)
*/
public class HystrixCodaHaleMetricsPublisherCollapser implements HystrixMetricsPublisherCollapser {
private final HystrixCollapserKey key;
private final HystrixCollapserMetrics metrics;
private final HystrixCollapserProperties properties;
private final MetricRegistry metricRegistry;
private final String metricType;
static final Logger logger = LoggerFactory.getLogger(HystrixCodaHaleMetricsPublisherCollapser.class);
public HystrixCodaHaleMetricsPublisherCollapser(HystrixCollapserKey collapserKey, HystrixCollapserMetrics metrics, HystrixCollapserProperties properties, MetricRegistry metricRegistry) {
this.key = collapserKey;
this.metrics = metrics;
this.properties = properties;
this.metricRegistry = metricRegistry;
this.metricType = key.name();
}
/**
* An implementation note. If there's a version mismatch between hystrix-core and hystrix-codahale-metrics-publisher,
* the code below may reference a HystrixRollingNumberEvent that does not exist in hystrix-core. If this happens,
* a j.l.NoSuchFieldError occurs. Since this data is not being generated by hystrix-core, it's safe to count it as 0
* and we should log an error to get users to update their dependency set.
*/
@Override
public void initialize() {
// allow monitor to know exactly at what point in time these stats are for so they can be plotted accurately
metricRegistry.register(createMetricName("currentTime"), new Gauge<Long>() {
@Override
public Long getValue() {
return System.currentTimeMillis();
}
});
// cumulative counts
safelyCreateCumulativeCountForEvent("countRequestsBatched", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.COLLAPSER_REQUEST_BATCHED;
}
});
safelyCreateCumulativeCountForEvent("countBatches", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.COLLAPSER_BATCH;
}
});
safelyCreateCumulativeCountForEvent("countResponsesFromCache", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.RESPONSE_FROM_CACHE;
}
});
// rolling counts
safelyCreateRollingCountForEvent("rollingRequestsBatched", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.COLLAPSER_REQUEST_BATCHED;
}
});
safelyCreateRollingCountForEvent("rollingBatches", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.COLLAPSER_BATCH;
}
});
safelyCreateRollingCountForEvent("rollingCountResponsesFromCache", new Func0<HystrixRollingNumberEvent>() {
@Override
public HystrixRollingNumberEvent call() {
return HystrixRollingNumberEvent.RESPONSE_FROM_CACHE;
}
});
// batch size metrics
metricRegistry.register(createMetricName("batchSize_mean"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getBatchSizeMean();
}
});
metricRegistry.register(createMetricName("batchSize_percentile_25"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getBatchSizePercentile(25);
}
});
metricRegistry.register(createMetricName("batchSize_percentile_50"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getBatchSizePercentile(50);
}
});
metricRegistry.register(createMetricName("batchSize_percentile_75"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getBatchSizePercentile(75);
}
});
metricRegistry.register(createMetricName("batchSize_percentile_90"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getBatchSizePercentile(90);
}
});
metricRegistry.register(createMetricName("batchSize_percentile_99"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getBatchSizePercentile(99);
}
});
metricRegistry.register(createMetricName("batchSize_percentile_995"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getBatchSizePercentile(99.5);
}
});
// shard size metrics
metricRegistry.register(createMetricName("shardSize_mean"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getShardSizeMean();
}
});
metricRegistry.register(createMetricName("shardSize_percentile_25"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getShardSizePercentile(25);
}
});
metricRegistry.register(createMetricName("shardSize_percentile_50"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getShardSizePercentile(50);
}
});
metricRegistry.register(createMetricName("shardSize_percentile_75"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getShardSizePercentile(75);
}
});
metricRegistry.register(createMetricName("shardSize_percentile_90"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getShardSizePercentile(90);
}
});
metricRegistry.register(createMetricName("shardSize_percentile_99"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getShardSizePercentile(99);
}
});
metricRegistry.register(createMetricName("shardSize_percentile_995"), new Gauge<Integer>() {
@Override
public Integer getValue() {
return metrics.getShardSizePercentile(99.5);
}
});
// properties (so the values can be inspected and monitored)
metricRegistry.register(createMetricName("propertyValue_rollingStatisticalWindowInMilliseconds"), new Gauge<Number>() {
@Override
public Number getValue() {
return properties.metricsRollingStatisticalWindowInMilliseconds().get();
}
});
metricRegistry.register(createMetricName("propertyValue_requestCacheEnabled"), new Gauge<Boolean>() {
@Override
public Boolean getValue() {
return properties.requestCacheEnabled().get();
}
});
metricRegistry.register(createMetricName("propertyValue_maxRequestsInBatch"), new Gauge<Number>() {
@Override
public Number getValue() {
return properties.maxRequestsInBatch().get();
}
});
metricRegistry.register(createMetricName("propertyValue_timerDelayInMilliseconds"), new Gauge<Number>() {
@Override
public Number getValue() {
return properties.timerDelayInMilliseconds().get();
}
});
}
protected String createMetricName(String name) {
return MetricRegistry.name("", metricType, name);
}
protected void createCumulativeCountForEvent(final String name, final HystrixRollingNumberEvent event) {
metricRegistry.register(createMetricName(name), new Gauge<Long>() {
@Override
public Long getValue() {
return metrics.getCumulativeCount(event);
}
});
}
protected void safelyCreateCumulativeCountForEvent(final String name, final Func0<HystrixRollingNumberEvent> eventThunk) {
metricRegistry.register(createMetricName(name), new Gauge<Long>() {
@Override
public Long getValue() {
try {
return metrics.getCumulativeCount(eventThunk.call());
} catch (NoSuchFieldError error) {
logger.error("While publishing CodaHale metrics, error looking up eventType for : {}. Please check that all Hystrix versions are the same!", name);
return 0L;
}
}
});
}
protected void createRollingCountForEvent(final String name, final HystrixRollingNumberEvent event) {
metricRegistry.register(createMetricName(name), new Gauge<Long>() {
@Override
public Long getValue() {
return metrics.getRollingCount(event);
}
});
}
protected void safelyCreateRollingCountForEvent(final String name, final Func0<HystrixRollingNumberEvent> eventThunk) {
metricRegistry.register(createMetricName(name), new Gauge<Long>() {
@Override
public Long getValue() {
try {
return metrics.getRollingCount(eventThunk.call());
} catch (NoSuchFieldError error) {
logger.error("While publishing CodaHale metrics, error looking up eventType for : {}. Please check that all Hystrix versions are the same!", name);
return 0L;
}
}
});
}
}
| 4,556 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-codahale-metrics-publisher/src/main/java/com/netflix/hystrix/contrib | Create_ds/Hystrix/hystrix-contrib/hystrix-codahale-metrics-publisher/src/main/java/com/netflix/hystrix/contrib/codahalemetricspublisher/HystrixCodaHaleMetricsPublisherThreadPool.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.codahalemetricspublisher;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricRegistry;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolMetrics;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherThreadPool;
import com.netflix.hystrix.util.HystrixRollingNumberEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implementation of {@link HystrixMetricsPublisherThreadPool} using Coda Hale Metrics (https://github.com/codahale/metrics)
*/
public class HystrixCodaHaleMetricsPublisherThreadPool implements HystrixMetricsPublisherThreadPool {
private final String metricsRootNode;
private final HystrixThreadPoolKey key;
private final HystrixThreadPoolMetrics metrics;
private final HystrixThreadPoolProperties properties;
private final MetricRegistry metricRegistry;
private final String metricGroup;
private final String metricType;
static final Logger logger = LoggerFactory.getLogger(HystrixCodaHaleMetricsPublisherThreadPool.class);
public HystrixCodaHaleMetricsPublisherThreadPool(String metricsRootNode, HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolMetrics metrics, HystrixThreadPoolProperties properties, MetricRegistry metricRegistry) {
this.metricsRootNode = metricsRootNode;
this.key = threadPoolKey;
this.metrics = metrics;
this.properties = properties;
this.metricRegistry = metricRegistry;
this.metricGroup = "HystrixThreadPool";
this.metricType = key.name();
}
/**
* An implementation note. If there's a version mismatch between hystrix-core and hystrix-codahale-metrics-publisher,
* the code below may reference a HystrixRollingNumberEvent that does not exist in hystrix-core. If this happens,
* a j.l.NoSuchFieldError occurs. Since this data is not being generated by hystrix-core, it's safe to count it as 0
* and we should log an error to get users to update their dependency set.
*/
@Override
public void initialize() {
metricRegistry.register(createMetricName("name"), new Gauge<String>() {
@Override
public String getValue() {
return key.name();
}
});
// allow monitor to know exactly at what point in time these stats are for so they can be plotted accurately
metricRegistry.register(createMetricName("currentTime"), new Gauge<Long>() {
@Override
public Long getValue() {
return System.currentTimeMillis();
}
});
metricRegistry.register(createMetricName("threadActiveCount"), new Gauge<Number>() {
@Override
public Number getValue() {
return metrics.getCurrentActiveCount();
}
});
metricRegistry.register(createMetricName("completedTaskCount"), new Gauge<Number>() {
@Override
public Number getValue() {
return metrics.getCurrentCompletedTaskCount();
}
});
metricRegistry.register(createMetricName("largestPoolSize"), new Gauge<Number>() {
@Override
public Number getValue() {
return metrics.getCurrentLargestPoolSize();
}
});
metricRegistry.register(createMetricName("totalTaskCount"), new Gauge<Number>() {
@Override
public Number getValue() {
return metrics.getCurrentTaskCount();
}
});
metricRegistry.register(createMetricName("queueSize"), new Gauge<Number>() {
@Override
public Number getValue() {
return metrics.getCurrentQueueSize();
}
});
metricRegistry.register(createMetricName("rollingMaxActiveThreads"), new Gauge<Number>() {
@Override
public Number getValue() {
return metrics.getRollingMaxActiveThreads();
}
});
metricRegistry.register(createMetricName("countThreadsExecuted"), new Gauge<Number>() {
@Override
public Number getValue() {
return metrics.getCumulativeCountThreadsExecuted();
}
});
metricRegistry.register(createMetricName("rollingCountCommandsRejected"), new Gauge<Number>() {
@Override
public Number getValue() {
try {
return metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED);
} catch (NoSuchFieldError error) {
logger.error("While publishing CodaHale metrics, error looking up eventType for : rollingCountCommandsRejected. Please check that all Hystrix versions are the same!");
return 0L;
}
}
});
metricRegistry.register(createMetricName("rollingCountThreadsExecuted"), new Gauge<Number>() {
@Override
public Number getValue() {
return metrics.getRollingCountThreadsExecuted();
}
});
// properties
metricRegistry.register(createMetricName("propertyValue_corePoolSize"), new Gauge<Number>() {
@Override
public Number getValue() {
return properties.coreSize().get();
}
});
metricRegistry.register(createMetricName("propertyValue_maximumSize"), new Gauge<Number>() {
@Override
public Number getValue() {
return properties.maximumSize().get();
}
});
metricRegistry.register(createMetricName("propertyValue_actualMaximumSize"), new Gauge<Number>() {
@Override
public Number getValue() {
return properties.actualMaximumSize();
}
});
metricRegistry.register(createMetricName("propertyValue_keepAliveTimeInMinutes"), new Gauge<Number>() {
@Override
public Number getValue() {
return properties.keepAliveTimeMinutes().get();
}
});
metricRegistry.register(createMetricName("propertyValue_queueSizeRejectionThreshold"), new Gauge<Number>() {
@Override
public Number getValue() {
return properties.queueSizeRejectionThreshold().get();
}
});
metricRegistry.register(createMetricName("propertyValue_maxQueueSize"), new Gauge<Number>() {
@Override
public Number getValue() {
return properties.maxQueueSize().get();
}
});
}
protected String createMetricName(String name) {
return MetricRegistry.name(metricsRootNode, metricGroup, metricType, name);
}
}
| 4,557 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-network-auditor-agent/src/main/java/com/netflix/hystrix/contrib | Create_ds/Hystrix/hystrix-contrib/hystrix-network-auditor-agent/src/main/java/com/netflix/hystrix/contrib/networkauditor/HystrixNetworkAuditorEventListener.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.networkauditor;
/**
* Event listener that gets implemented and registered with {@link HystrixNetworkAuditorAgent#registerEventListener(HystrixNetworkAuditorEventListener)} by the application
* running Hystrix in the application classloader into this JavaAgent running in the boot classloader so events can be invoked on code inside the application classloader.
*/
public interface HystrixNetworkAuditorEventListener {
/**
* Invoked by the {@link HystrixNetworkAuditorAgent} when network events occur.
* <p>
* An event may be the opening of a socket, channel or reading/writing bytes. It is not guaranteed to be a one-to-one relationship with a request/response.
* <p>
* No arguments are returned as it is left to the implementation to decide whether the current thread stacktrace should be captured or not.
* <p>
* Typical implementations will want to filter to non-Hystrix isolated network traffic with code such as this:
*
* <pre> {@code
*
* if (Hystrix.getCurrentThreadExecutingCommand() == null) {
* // this event is not inside a Hystrix context (according to ThreadLocal variables)
* StackTraceElement[] stack = Thread.currentThread().getStackTrace();
* // increment counters, fire alerts, log stack traces etc
* }
* } </pre>
*
*/
public void handleNetworkEvent();
}
| 4,558 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-network-auditor-agent/src/main/java/com/netflix/hystrix/contrib | Create_ds/Hystrix/hystrix-contrib/hystrix-network-auditor-agent/src/main/java/com/netflix/hystrix/contrib/networkauditor/HystrixNetworkAuditorAgent.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.networkauditor;
import java.lang.instrument.Instrumentation;
/**
* Java Agent to instrument network code in the java.* libraries and use Hystrix state to determine if calls are Hystrix-isolated or not.
*/
public class HystrixNetworkAuditorAgent {
private static final HystrixNetworkAuditorEventListener DEFAULT_BRIDGE = new HystrixNetworkAuditorEventListener() {
@Override
public void handleNetworkEvent() {
// do nothing
}
};
private static volatile HystrixNetworkAuditorEventListener bridge = DEFAULT_BRIDGE;
public static void premain(String agentArgs, Instrumentation inst) {
inst.addTransformer(new NetworkClassTransform());
}
/**
* Invoked by instrumented code when network access occurs.
*/
public static void notifyOfNetworkEvent() {
bridge.handleNetworkEvent();
}
/**
* Register the implementation of the {@link HystrixNetworkAuditorEventListener} that will receive the events.
*
* @param bridge
* {@link HystrixNetworkAuditorEventListener} implementation
*/
public static void registerEventListener(HystrixNetworkAuditorEventListener bridge) {
if (bridge == null) {
throw new IllegalArgumentException("HystrixNetworkAuditorEventListener can not be NULL");
}
HystrixNetworkAuditorAgent.bridge = bridge;
}
}
| 4,559 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-network-auditor-agent/src/main/java/com/netflix/hystrix/contrib | Create_ds/Hystrix/hystrix-contrib/hystrix-network-auditor-agent/src/main/java/com/netflix/hystrix/contrib/networkauditor/NetworkClassTransform.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.contrib.networkauditor;
import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtMethod;
import javassist.NotFoundException;
/**
* Bytecode ClassFileTransformer used by the Java Agent to instrument network code in the java.* libraries and use Hystrix state to determine if calls are Hystrix-isolated or not.
*/
public class NetworkClassTransform implements ClassFileTransformer {
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
String name = className.replace('/', '.');
try {
/*
* These hook points were found through trial-and-error after wrapping all java.net/java.io/java.nio classes and methods and finding reliable
* notifications that matched statistics and events in an application.
*
* There may very well be problems here or code paths that don't correctly trigger an event.
*
* If someone can provide a more reliable and cleaner hook point or if there are examples of code paths that don't trigger either of these
* then please file a bug or submit a pull request at https://github.com/Netflix/Hystrix
*/
if (name.equals("java.net.Socket$2")) {
// this one seems to be fairly reliable in counting each time a request/response occurs on blocking IO
return wrapConstructorsOfClass(name);
} else if (name.equals("java.nio.channels.SocketChannel")) {
// handle NIO
return wrapConstructorsOfClass(name);
}
} catch (Exception e) {
throw new RuntimeException("Failed trying to wrap class: " + className, e);
}
// we didn't transform anything so return null to leave untouched
return null;
}
/**
* Wrap all constructors of a given class
*
* @param className
* @throws NotFoundException
* @throws CannotCompileException
* @throws IOException
*/
private byte[] wrapConstructorsOfClass(String className) throws NotFoundException, IOException, CannotCompileException {
return wrapClass(className, true);
}
/**
* Wrap all signatures of a given method name.
*
* @param className
* @param methodName
* @throws NotFoundException
* @throws CannotCompileException
* @throws IOException
*/
private byte[] wrapClass(String className, boolean wrapConstructors, String... methodNames) throws NotFoundException, IOException, CannotCompileException {
ClassPool cp = ClassPool.getDefault();
CtClass ctClazz = cp.get(className);
// constructors
if (wrapConstructors) {
CtConstructor[] constructors = ctClazz.getConstructors();
for (CtConstructor constructor : constructors) {
try {
constructor.insertBefore("{ com.netflix.hystrix.contrib.networkauditor.HystrixNetworkAuditorAgent.notifyOfNetworkEvent(); }");
} catch (Exception e) {
throw new RuntimeException("Failed trying to wrap constructor of class: " + className, e);
}
}
}
// methods
CtMethod[] methods = ctClazz.getDeclaredMethods();
for (CtMethod method : methods) {
try {
for (String methodName : methodNames) {
if (method.getName().equals(methodName)) {
method.insertBefore("{ com.netflix.hystrix.contrib.networkauditor.HystrixNetworkAuditorAgent.handleNetworkEvent(); }");
}
}
} catch (Exception e) {
throw new RuntimeException("Failed trying to wrap method [" + method.getName() + "] of class: " + className, e);
}
}
return ctClazz.toBytecode();
}
} | 4,560 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-junit/src/test/java/com/hystrix | Create_ds/Hystrix/hystrix-contrib/hystrix-junit/src/test/java/com/hystrix/junit/HystrixRequestContextRuleTest.java | package com.hystrix.junit;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.Rule;
import org.junit.Test;
public final class HystrixRequestContextRuleTest {
@Rule
public HystrixRequestContextRule request = new HystrixRequestContextRule();
@Test
public void initsContext() {
MatcherAssert.assertThat(this.request.context(), CoreMatchers.notNullValue());
}
@Test
public void manuallyShutdownContextDontBreak() {
this.request.after();
this.request.after();
MatcherAssert.assertThat(this.request.context(), CoreMatchers.nullValue());
}
}
| 4,561 |
0 | Create_ds/Hystrix/hystrix-contrib/hystrix-junit/src/main/java/com/hystrix | Create_ds/Hystrix/hystrix-contrib/hystrix-junit/src/main/java/com/hystrix/junit/HystrixRequestContextRule.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.hystrix.junit;
import com.netflix.hystrix.Hystrix;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import org.junit.rules.ExternalResource;
/**
* JUnit rule to be used to simplify tests that require a HystrixRequestContext.
*
* Example of usage:
*
* <blockquote>
* <pre>
* @Rule
* public HystrixRequestContextRule context = new HystrixRequestContextRule();
* </pre>
* </blockquote>
*
*/
public final class HystrixRequestContextRule extends ExternalResource {
private HystrixRequestContext context;
@Override
protected void before() {
this.context = HystrixRequestContext.initializeContext();
Hystrix.reset();
}
@Override
protected void after() {
if (this.context != null) {
this.context.shutdown();
this.context = null;
}
}
public HystrixRequestContext context() {
return this.context;
}
public void reset() {
after();
before();
}
}
| 4,562 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/HystrixCollapserTest.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix;
import com.hystrix.junit.HystrixRequestContextRule;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import com.netflix.hystrix.strategy.concurrency.HystrixContextScheduler;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import com.netflix.hystrix.strategy.properties.HystrixPropertiesCollapserDefault;
import com.netflix.hystrix.strategy.properties.HystrixPropertiesFactory;
import com.netflix.hystrix.util.HystrixTimer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import com.netflix.hystrix.HystrixCollapser.CollapsedRequest;
import com.netflix.hystrix.collapser.CollapserTimer;
import com.netflix.hystrix.collapser.RealCollapserTimer;
import com.netflix.hystrix.collapser.RequestCollapser;
import com.netflix.hystrix.collapser.RequestCollapserFactory;
import com.netflix.hystrix.strategy.HystrixPlugins;
import com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableHolder;
import com.netflix.hystrix.util.HystrixTimer.TimerListener;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.functions.Action0;
import rx.observers.Subscribers;
import rx.observers.TestSubscriber;
import rx.schedulers.Schedulers;
import static org.junit.Assert.*;
public class HystrixCollapserTest {
@Rule
public HystrixRequestContextRule context = new HystrixRequestContextRule();
@Before
public void init() {
HystrixCollapserMetrics.reset();
HystrixCommandMetrics.reset();
HystrixPropertiesFactory.reset();
}
@Test
public void testTwoRequests() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixCollapser<List<String>, String, String> collapser1 = new TestRequestCollapser(timer, 1);
Future<String> response1 = collapser1.queue();
HystrixCollapser<List<String>, String, String> collapser2 = new TestRequestCollapser(timer, 2);
Future<String> response2 = collapser2.queue();
timer.incrementTime(10); // let time pass that equals the default delay/period
assertEquals("1", response1.get());
assertEquals("2", response2.get(1000, TimeUnit.MILLISECONDS));
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixCollapserMetrics metrics = collapser1.getMetrics();
assertSame(metrics, collapser2.getMetrics());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator().next();
assertEquals(2, command.getNumberCollapsed());
}
@Test
public void testMultipleBatches() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixCollapser<List<String>, String, String> collapser1 = new TestRequestCollapser(timer, 1);
Future<String> response1 = collapser1.queue();
Future<String> response2 = new TestRequestCollapser(timer, 2).queue();
timer.incrementTime(10); // let time pass that equals the default delay/period
assertEquals("1", response1.get(1000, TimeUnit.MILLISECONDS));
assertEquals("2", response2.get(1000, TimeUnit.MILLISECONDS));
// now request more
Future<String> response3 = new TestRequestCollapser(timer, 3).queue();
timer.incrementTime(10); // let time pass that equals the default delay/period
assertEquals("3", response3.get(1000, TimeUnit.MILLISECONDS));
// we should have had it execute twice now
assertEquals(2, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
Iterator<HystrixInvokableInfo<?>> cmdIterator = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator();
assertEquals(2, cmdIterator.next().getNumberCollapsed());
assertEquals(1, cmdIterator.next().getNumberCollapsed());
}
@Test
public void testMaxRequestsInBatch() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixCollapser<List<String>, String, String> collapser1 = new TestRequestCollapser(timer, 1, 2, 10);
HystrixCollapser<List<String>, String, String> collapser2 = new TestRequestCollapser(timer, 2, 2, 10);
HystrixCollapser<List<String>, String, String> collapser3 = new TestRequestCollapser(timer, 3, 2, 10);
System.out.println("*** " + System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Constructed the collapsers");
Future<String> response1 = collapser1.queue();
Future<String> response2 = collapser2.queue();
Future<String> response3 = collapser3.queue();
System.out.println("*** " +System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " queued the collapsers");
timer.incrementTime(10); // let time pass that equals the default delay/period
System.out.println("*** " +System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " incremented the virtual timer");
assertEquals("1", response1.get(1000, TimeUnit.MILLISECONDS));
assertEquals("2", response2.get(1000, TimeUnit.MILLISECONDS));
assertEquals("3", response3.get(1000, TimeUnit.MILLISECONDS));
// we should have had it execute twice because the batch size was 2
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertEquals(2, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
Iterator<HystrixInvokableInfo<?>> cmdIterator = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator();
assertEquals(2, cmdIterator.next().getNumberCollapsed());
assertEquals(1, cmdIterator.next().getNumberCollapsed());
}
@Test
public void testRequestsOverTime() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixCollapser<List<String>, String, String> collapser1 = new TestRequestCollapser(timer, 1);
Future<String> response1 = collapser1.queue();
timer.incrementTime(5);
Future<String> response2 = new TestRequestCollapser(timer, 2).queue();
timer.incrementTime(8);
// should execute here
Future<String> response3 = new TestRequestCollapser(timer, 3).queue();
timer.incrementTime(6);
Future<String> response4 = new TestRequestCollapser(timer, 4).queue();
timer.incrementTime(8);
// should execute here
Future<String> response5 = new TestRequestCollapser(timer, 5).queue();
timer.incrementTime(10);
// should execute here
// wait for all tasks to complete
assertEquals("1", response1.get(1000, TimeUnit.MILLISECONDS));
assertEquals("2", response2.get(1000, TimeUnit.MILLISECONDS));
assertEquals("3", response3.get(1000, TimeUnit.MILLISECONDS));
assertEquals("4", response4.get(1000, TimeUnit.MILLISECONDS));
assertEquals("5", response5.get(1000, TimeUnit.MILLISECONDS));
assertEquals(3, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
Iterator<HystrixInvokableInfo<?>> cmdIterator = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator();
assertEquals(2, cmdIterator.next().getNumberCollapsed());
assertEquals(2, cmdIterator.next().getNumberCollapsed());
assertEquals(1, cmdIterator.next().getNumberCollapsed());
}
class Pair<A, B> {
final A a;
final B b;
Pair(A a, B b) {
this.a = a;
this.b = b;
}
}
class MyCommand extends HystrixCommand<List<Pair<String, Integer>>> {
private final List<String> args;
public MyCommand(List<String> args) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("BATCH")));
this.args = args;
}
@Override
protected List<Pair<String, Integer>> run() throws Exception {
System.out.println("Executing batch command on : " + Thread.currentThread().getName() + " with args : " + args);
List<Pair<String, Integer>> results = new ArrayList<Pair<String, Integer>>();
for (String arg: args) {
results.add(new Pair<String, Integer>(arg, Integer.parseInt(arg)));
}
return results;
}
}
class MyCollapser extends HystrixCollapser<List<Pair<String, Integer>>, Integer, String> {
private final String arg;
MyCollapser(String arg, boolean reqCacheEnabled) {
super(HystrixCollapserKey.Factory.asKey("UNITTEST"),
Scope.REQUEST,
new RealCollapserTimer(),
HystrixCollapserProperties.Setter().withRequestCacheEnabled(reqCacheEnabled),
HystrixCollapserMetrics.getInstance(HystrixCollapserKey.Factory.asKey("UNITTEST"),
new HystrixPropertiesCollapserDefault(HystrixCollapserKey.Factory.asKey("UNITTEST"),
HystrixCollapserProperties.Setter())));
this.arg = arg;
}
@Override
public String getRequestArgument() {
return arg;
}
@Override
protected HystrixCommand<List<Pair<String, Integer>>> createCommand(Collection<CollapsedRequest<Integer, String>> collapsedRequests) {
List<String> args = new ArrayList<String>(collapsedRequests.size());
for (CollapsedRequest<Integer, String> req: collapsedRequests) {
args.add(req.getArgument());
}
return new MyCommand(args);
}
@Override
protected void mapResponseToRequests(List<Pair<String, Integer>> batchResponse, Collection<CollapsedRequest<Integer, String>> collapsedRequests) {
for (Pair<String, Integer> pair: batchResponse) {
for (CollapsedRequest<Integer, String> collapsedReq: collapsedRequests) {
if (collapsedReq.getArgument().equals(pair.a)) {
collapsedReq.setResponse(pair.b);
}
}
}
}
@Override
protected String getCacheKey() {
return arg;
}
}
@Test
public void testDuplicateArgumentsWithRequestCachingOn() throws Exception {
final int NUM = 10;
List<Observable<Integer>> observables = new ArrayList<Observable<Integer>>();
for (int i = 0; i < NUM; i++) {
MyCollapser c = new MyCollapser("5", true);
observables.add(c.toObservable());
}
List<TestSubscriber<Integer>> subscribers = new ArrayList<TestSubscriber<Integer>>();
for (final Observable<Integer> o: observables) {
final TestSubscriber<Integer> sub = new TestSubscriber<Integer>();
subscribers.add(sub);
o.subscribe(sub);
}
Thread.sleep(100);
//all subscribers should receive the same value
for (TestSubscriber<Integer> sub: subscribers) {
sub.awaitTerminalEvent(1000, TimeUnit.MILLISECONDS);
System.out.println("Subscriber received : " + sub.getOnNextEvents());
sub.assertNoErrors();
sub.assertValues(5);
}
}
@Test
public void testDuplicateArgumentsWithRequestCachingOff() throws Exception {
final int NUM = 10;
List<Observable<Integer>> observables = new ArrayList<Observable<Integer>>();
for (int i = 0; i < NUM; i++) {
MyCollapser c = new MyCollapser("5", false);
observables.add(c.toObservable());
}
List<TestSubscriber<Integer>> subscribers = new ArrayList<TestSubscriber<Integer>>();
for (final Observable<Integer> o: observables) {
final TestSubscriber<Integer> sub = new TestSubscriber<Integer>();
subscribers.add(sub);
o.subscribe(sub);
}
Thread.sleep(100);
AtomicInteger numErrors = new AtomicInteger(0);
AtomicInteger numValues = new AtomicInteger(0);
// only the first subscriber should receive the value.
// the others should get an error that the batch contains duplicates
for (TestSubscriber<Integer> sub: subscribers) {
sub.awaitTerminalEvent(1000, TimeUnit.MILLISECONDS);
if (sub.getOnCompletedEvents().isEmpty()) {
System.out.println(Thread.currentThread().getName() + " Error : " + sub.getOnErrorEvents());
sub.assertError(IllegalArgumentException.class);
sub.assertNoValues();
numErrors.getAndIncrement();
} else {
System.out.println(Thread.currentThread().getName() + " OnNext : " + sub.getOnNextEvents());
sub.assertValues(5);
sub.assertCompleted();
sub.assertNoErrors();
numValues.getAndIncrement();
}
}
assertEquals(1, numValues.get());
assertEquals(NUM - 1, numErrors.get());
}
@Test
public void testUnsubscribeFromSomeDuplicateArgsDoesNotRemoveFromBatch() throws Exception {
final int NUM = 10;
List<Observable<Integer>> observables = new ArrayList<Observable<Integer>>();
for (int i = 0; i < NUM; i++) {
MyCollapser c = new MyCollapser("5", true);
observables.add(c.toObservable());
}
List<TestSubscriber<Integer>> subscribers = new ArrayList<TestSubscriber<Integer>>();
List<Subscription> subscriptions = new ArrayList<Subscription>();
for (final Observable<Integer> o: observables) {
final TestSubscriber<Integer> sub = new TestSubscriber<Integer>();
subscribers.add(sub);
Subscription s = o.subscribe(sub);
subscriptions.add(s);
}
//unsubscribe from all but 1
for (int i = 0; i < NUM - 1; i++) {
Subscription s = subscriptions.get(i);
s.unsubscribe();
}
Thread.sleep(100);
//all subscribers with an active subscription should receive the same value
for (TestSubscriber<Integer> sub: subscribers) {
if (!sub.isUnsubscribed()) {
sub.awaitTerminalEvent(1000, TimeUnit.MILLISECONDS);
System.out.println("Subscriber received : " + sub.getOnNextEvents());
sub.assertNoErrors();
sub.assertValues(5);
} else {
System.out.println("Subscriber is unsubscribed");
}
}
}
@Test
public void testUnsubscribeOnOneDoesntKillBatch() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixCollapser<List<String>, String, String> collapser1 = new TestRequestCollapser(timer, 1);
Future<String> response1 = collapser1.queue();
Future<String> response2 = new TestRequestCollapser(timer, 2).queue();
// kill the first
response1.cancel(true);
timer.incrementTime(10); // let time pass that equals the default delay/period
// the first is cancelled so should return null
try {
response1.get(1000, TimeUnit.MILLISECONDS);
fail("expect CancellationException after cancelling");
} catch (CancellationException e) {
// expected
}
// we should still get a response on the second
assertEquals("2", response2.get(1000, TimeUnit.MILLISECONDS));
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
Iterator<HystrixInvokableInfo<?>> cmdIterator = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator();
assertEquals(1, cmdIterator.next().getNumberCollapsed());
}
@Test
public void testShardedRequests() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixCollapser<List<String>, String, String> collapser1 = new TestShardedRequestCollapser(timer, "1a");
Future<String> response1 = collapser1.queue();
Future<String> response2 = new TestShardedRequestCollapser(timer, "2b").queue();
Future<String> response3 = new TestShardedRequestCollapser(timer, "3b").queue();
Future<String> response4 = new TestShardedRequestCollapser(timer, "4a").queue();
timer.incrementTime(10); // let time pass that equals the default delay/period
assertEquals("1a", response1.get(1000, TimeUnit.MILLISECONDS));
assertEquals("2b", response2.get(1000, TimeUnit.MILLISECONDS));
assertEquals("3b", response3.get(1000, TimeUnit.MILLISECONDS));
assertEquals("4a", response4.get(1000, TimeUnit.MILLISECONDS));
/* we should get 2 batches since it gets sharded */
assertEquals(2, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
Iterator<HystrixInvokableInfo<?>> cmdIterator = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator();
assertEquals(2, cmdIterator.next().getNumberCollapsed());
assertEquals(2, cmdIterator.next().getNumberCollapsed());
}
@Test
public void testRequestScope() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixCollapser<List<String>, String, String> collapser1 = new TestRequestCollapser(timer, "1");
Future<String> response1 = collapser1.queue();
Future<String> response2 = new TestRequestCollapser(timer, "2").queue();
// simulate a new request
RequestCollapserFactory.resetRequest();
Future<String> response3 = new TestRequestCollapser(timer, "3").queue();
Future<String> response4 = new TestRequestCollapser(timer, "4").queue();
timer.incrementTime(10); // let time pass that equals the default delay/period
assertEquals("1", response1.get(1000, TimeUnit.MILLISECONDS));
assertEquals("2", response2.get(1000, TimeUnit.MILLISECONDS));
assertEquals("3", response3.get(1000, TimeUnit.MILLISECONDS));
assertEquals("4", response4.get(1000, TimeUnit.MILLISECONDS));
// 2 different batches should execute, 1 per request
assertEquals(2, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
Iterator<HystrixInvokableInfo<?>> cmdIterator = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator();
assertEquals(2, cmdIterator.next().getNumberCollapsed());
assertEquals(2, cmdIterator.next().getNumberCollapsed());
}
@Test
public void testGlobalScope() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixCollapser<List<String>, String, String> collapser1 = new TestGloballyScopedRequestCollapser(timer, "1");
Future<String> response1 = collapser1.queue();
Future<String> response2 = new TestGloballyScopedRequestCollapser(timer, "2").queue();
// simulate a new request
RequestCollapserFactory.resetRequest();
Future<String> response3 = new TestGloballyScopedRequestCollapser(timer, "3").queue();
Future<String> response4 = new TestGloballyScopedRequestCollapser(timer, "4").queue();
timer.incrementTime(10); // let time pass that equals the default delay/period
assertEquals("1", response1.get(1000, TimeUnit.MILLISECONDS));
assertEquals("2", response2.get(1000, TimeUnit.MILLISECONDS));
assertEquals("3", response3.get(1000, TimeUnit.MILLISECONDS));
assertEquals("4", response4.get(1000, TimeUnit.MILLISECONDS));
// despite having cleared the cache in between we should have a single execution because this is on the global not request cache
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
Iterator<HystrixInvokableInfo<?>> cmdIterator = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator();
assertEquals(4, cmdIterator.next().getNumberCollapsed());
}
@Test
public void testErrorHandlingViaFutureException() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixCollapser<List<String>, String, String> collapser1 = new TestRequestCollapserWithFaultyCreateCommand(timer, "1");
Future<String> response1 = collapser1.queue();
Future<String> response2 = new TestRequestCollapserWithFaultyCreateCommand(timer, "2").queue();
timer.incrementTime(10); // let time pass that equals the default delay/period
try {
response1.get(1000, TimeUnit.MILLISECONDS);
fail("we should have received an exception");
} catch (ExecutionException e) {
// what we expect
}
try {
response2.get(1000, TimeUnit.MILLISECONDS);
fail("we should have received an exception");
} catch (ExecutionException e) {
// what we expect
}
assertEquals(0, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
}
@Test
public void testErrorHandlingWhenMapToResponseFails() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixCollapser<List<String>, String, String> collapser1 = new TestRequestCollapserWithFaultyMapToResponse(timer, "1");
Future<String> response1 = collapser1.queue();
Future<String> response2 = new TestRequestCollapserWithFaultyMapToResponse(timer, "2").queue();
timer.incrementTime(10); // let time pass that equals the default delay/period
try {
response1.get(1000, TimeUnit.MILLISECONDS);
fail("we should have received an exception");
} catch (ExecutionException e) {
// what we expect
}
try {
response2.get(1000, TimeUnit.MILLISECONDS);
fail("we should have received an exception");
} catch (ExecutionException e) {
// what we expect
}
// the batch failed so no executions
// but it still executed the command once
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
Iterator<HystrixInvokableInfo<?>> cmdIterator = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator();
assertEquals(2, cmdIterator.next().getNumberCollapsed());
}
@Test
public void testRequestVariableLifecycle1() throws Exception {
HystrixRequestContext reqContext = HystrixRequestContext.initializeContext();
// do actual work
TestCollapserTimer timer = new TestCollapserTimer();
HystrixCollapser<List<String>, String, String> collapser1 = new TestRequestCollapser(timer, 1);
Future<String> response1 = collapser1.queue();
timer.incrementTime(5);
Future<String> response2 = new TestRequestCollapser(timer, 2).queue();
timer.incrementTime(8);
// should execute here
Future<String> response3 = new TestRequestCollapser(timer, 3).queue();
timer.incrementTime(6);
Future<String> response4 = new TestRequestCollapser(timer, 4).queue();
timer.incrementTime(8);
// should execute here
Future<String> response5 = new TestRequestCollapser(timer, 5).queue();
timer.incrementTime(10);
// should execute here
// wait for all tasks to complete
assertEquals("1", response1.get(1000, TimeUnit.MILLISECONDS));
assertEquals("2", response2.get(1000, TimeUnit.MILLISECONDS));
assertEquals("3", response3.get(1000, TimeUnit.MILLISECONDS));
assertEquals("4", response4.get(1000, TimeUnit.MILLISECONDS));
assertEquals("5", response5.get(1000, TimeUnit.MILLISECONDS));
// each task should have been executed 3 times
for (TestCollapserTimer.ATask t : timer.tasks) {
assertEquals(3, t.task.count.get());
}
System.out.println("timer.tasks.size() A: " + timer.tasks.size());
System.out.println("tasks in test: " + timer.tasks);
Iterator<HystrixInvokableInfo<?>> cmdIterator = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator();
assertEquals(2, cmdIterator.next().getNumberCollapsed());
assertEquals(2, cmdIterator.next().getNumberCollapsed());
assertEquals(1, cmdIterator.next().getNumberCollapsed());
System.out.println("timer.tasks.size() B: " + timer.tasks.size());
HystrixRequestVariableHolder<RequestCollapser<?, ?, ?>> rv = RequestCollapserFactory.getRequestVariable(new TestRequestCollapser(timer, 1).getCollapserKey().name());
reqContext.close();
assertNotNull(rv);
// they should have all been removed as part of ThreadContext.remove()
assertEquals(0, timer.tasks.size());
}
@Test
public void testRequestVariableLifecycle2() throws Exception {
final HystrixRequestContext reqContext = HystrixRequestContext.initializeContext();
final TestCollapserTimer timer = new TestCollapserTimer();
final ConcurrentLinkedQueue<Future<String>> responses = new ConcurrentLinkedQueue<Future<String>>();
ConcurrentLinkedQueue<Thread> threads = new ConcurrentLinkedQueue<Thread>();
// kick off work (simulating a single request with multiple threads)
for (int t = 0; t < 5; t++) {
final int outerLoop = t;
Thread th = new Thread(new HystrixContextRunnable(HystrixPlugins.getInstance().getConcurrencyStrategy(), new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
int uniqueInt = (outerLoop * 100) + i;
responses.add(new TestRequestCollapser(timer, uniqueInt).queue());
}
}
}));
threads.add(th);
th.start();
}
for (Thread th : threads) {
// wait for each thread to finish
th.join();
}
// we expect 5 threads * 100 responses each
assertEquals(500, responses.size());
for (Future<String> f : responses) {
// they should not be done yet because the counter hasn't incremented
assertFalse(f.isDone());
}
timer.incrementTime(5);
HystrixCollapser<List<String>, String, String> collapser1 = new TestRequestCollapser(timer, 2);
Future<String> response2 = collapser1.queue();
timer.incrementTime(8);
// should execute here
Future<String> response3 = new TestRequestCollapser(timer, 3).queue();
timer.incrementTime(6);
Future<String> response4 = new TestRequestCollapser(timer, 4).queue();
timer.incrementTime(8);
// should execute here
Future<String> response5 = new TestRequestCollapser(timer, 5).queue();
timer.incrementTime(10);
// should execute here
// wait for all tasks to complete
for (Future<String> f : responses) {
f.get(1000, TimeUnit.MILLISECONDS);
}
assertEquals("2", response2.get(1000, TimeUnit.MILLISECONDS));
assertEquals("3", response3.get(1000, TimeUnit.MILLISECONDS));
assertEquals("4", response4.get(1000, TimeUnit.MILLISECONDS));
assertEquals("5", response5.get(1000, TimeUnit.MILLISECONDS));
// each task should have been executed 3 times
for (TestCollapserTimer.ATask t : timer.tasks) {
assertEquals(3, t.task.count.get());
}
Iterator<HystrixInvokableInfo<?>> cmdIterator = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator();
assertEquals(500, cmdIterator.next().getNumberCollapsed());
assertEquals(2, cmdIterator.next().getNumberCollapsed());
assertEquals(1, cmdIterator.next().getNumberCollapsed());
HystrixRequestVariableHolder<RequestCollapser<?, ?, ?>> rv = RequestCollapserFactory.getRequestVariable(new TestRequestCollapser(timer, 1).getCollapserKey().name());
reqContext.close();
assertNotNull(rv);
// they should have all been removed as part of ThreadContext.remove()
assertEquals(0, timer.tasks.size());
}
/**
* Test Request scoped caching of commands so that a 2nd duplicate call doesn't execute but returns the previous Future
*/
@Test
public void testRequestCache1() {
final TestCollapserTimer timer = new TestCollapserTimer();
SuccessfulCacheableCollapsedCommand command1 = new SuccessfulCacheableCollapsedCommand(timer, "A", true);
SuccessfulCacheableCollapsedCommand command2 = new SuccessfulCacheableCollapsedCommand(timer, "A", true);
Future<String> f1 = command1.queue();
Future<String> f2 = command2.queue();
// increment past batch time so it executes
timer.incrementTime(15);
try {
assertEquals("A", f1.get(1000, TimeUnit.MILLISECONDS));
assertEquals("A", f2.get(1000, TimeUnit.MILLISECONDS));
} catch (Exception e) {
throw new RuntimeException(e);
}
Future<String> f3 = command1.queue();
// increment past batch time so it executes
timer.incrementTime(15);
try {
assertEquals("A", f3.get(1000, TimeUnit.MILLISECONDS));
} catch (Exception e) {
throw new RuntimeException(e);
}
// we should still have executed only one command
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().toArray(new HystrixInvokableInfo<?>[1])[0];
System.out.println("command.getExecutionEvents(): " + command.getExecutionEvents());
assertEquals(2, command.getExecutionEvents().size());
assertTrue(command.getExecutionEvents().contains(HystrixEventType.SUCCESS));
assertTrue(command.getExecutionEvents().contains(HystrixEventType.COLLAPSED));
Iterator<HystrixInvokableInfo<?>> cmdIterator = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator();
assertEquals(1, cmdIterator.next().getNumberCollapsed());
}
/**
* Test Request scoped caching doesn't prevent different ones from executing
*/
@Test
public void testRequestCache2() {
final TestCollapserTimer timer = new TestCollapserTimer();
SuccessfulCacheableCollapsedCommand command1 = new SuccessfulCacheableCollapsedCommand(timer, "A", true);
SuccessfulCacheableCollapsedCommand command2 = new SuccessfulCacheableCollapsedCommand(timer, "B", true);
Future<String> f1 = command1.queue();
Future<String> f2 = command2.queue();
// increment past batch time so it executes
timer.incrementTime(15);
try {
assertEquals("A", f1.get(1000, TimeUnit.MILLISECONDS));
assertEquals("B", f2.get(1000, TimeUnit.MILLISECONDS));
} catch (Exception e) {
throw new RuntimeException(e);
}
Future<String> f3 = command1.queue();
Future<String> f4 = command2.queue();
// increment past batch time so it executes
timer.incrementTime(15);
try {
assertEquals("A", f3.get(1000, TimeUnit.MILLISECONDS));
assertEquals("B", f4.get(1000, TimeUnit.MILLISECONDS));
} catch (Exception e) {
throw new RuntimeException(e);
}
// we should still have executed only one command
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().toArray(new HystrixInvokableInfo<?>[1])[0];
assertEquals(2, command.getExecutionEvents().size());
assertTrue(command.getExecutionEvents().contains(HystrixEventType.SUCCESS));
assertTrue(command.getExecutionEvents().contains(HystrixEventType.COLLAPSED));
Iterator<HystrixInvokableInfo<?>> cmdIterator = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator();
assertEquals(2, cmdIterator.next().getNumberCollapsed());
}
/**
* Test Request scoped caching with a mixture of commands
*/
@Test
public void testRequestCache3() {
final TestCollapserTimer timer = new TestCollapserTimer();
SuccessfulCacheableCollapsedCommand command1 = new SuccessfulCacheableCollapsedCommand(timer, "A", true);
SuccessfulCacheableCollapsedCommand command2 = new SuccessfulCacheableCollapsedCommand(timer, "B", true);
SuccessfulCacheableCollapsedCommand command3 = new SuccessfulCacheableCollapsedCommand(timer, "B", true);
Future<String> f1 = command1.queue();
Future<String> f2 = command2.queue();
Future<String> f3 = command3.queue();
// increment past batch time so it executes
timer.incrementTime(15);
try {
assertEquals("A", f1.get(1000, TimeUnit.MILLISECONDS));
assertEquals("B", f2.get(1000, TimeUnit.MILLISECONDS));
assertEquals("B", f3.get(1000, TimeUnit.MILLISECONDS));
} catch (Exception e) {
throw new RuntimeException(e);
}
Future<String> f4 = command1.queue();
Future<String> f5 = command2.queue();
Future<String> f6 = command3.queue();
// increment past batch time so it executes
timer.incrementTime(15);
try {
assertEquals("A", f4.get(1000, TimeUnit.MILLISECONDS));
assertEquals("B", f5.get(1000, TimeUnit.MILLISECONDS));
assertEquals("B", f6.get(1000, TimeUnit.MILLISECONDS));
} catch (Exception e) {
throw new RuntimeException(e);
}
// we should still have executed only one command
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().toArray(new HystrixInvokableInfo<?>[1])[0];
assertEquals(2, command.getExecutionEvents().size());
assertTrue(command.getExecutionEvents().contains(HystrixEventType.SUCCESS));
assertTrue(command.getExecutionEvents().contains(HystrixEventType.COLLAPSED));
Iterator<HystrixInvokableInfo<?>> cmdIterator = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator();
assertEquals(2, cmdIterator.next().getNumberCollapsed());
}
/**
* Test Request scoped caching with a mixture of commands
*/
@Test
public void testNoRequestCache3() {
final TestCollapserTimer timer = new TestCollapserTimer();
SuccessfulCacheableCollapsedCommand command1 = new SuccessfulCacheableCollapsedCommand(timer, "A", false);
SuccessfulCacheableCollapsedCommand command2 = new SuccessfulCacheableCollapsedCommand(timer, "B", false);
SuccessfulCacheableCollapsedCommand command3 = new SuccessfulCacheableCollapsedCommand(timer, "B", false);
Future<String> f1 = command1.queue();
Future<String> f2 = command2.queue();
Future<String> f3 = command3.queue();
// increment past batch time so it executes
timer.incrementTime(15);
try {
assertEquals("A", f1.get(1000, TimeUnit.MILLISECONDS));
assertEquals("B", f2.get(1000, TimeUnit.MILLISECONDS));
assertEquals("B", f3.get(1000, TimeUnit.MILLISECONDS));
} catch (Exception e) {
throw new RuntimeException(e);
}
Future<String> f4 = command1.queue();
Future<String> f5 = command2.queue();
Future<String> f6 = command3.queue();
// increment past batch time so it executes
timer.incrementTime(15);
try {
assertEquals("A", f4.get(1000, TimeUnit.MILLISECONDS));
assertEquals("B", f5.get(1000, TimeUnit.MILLISECONDS));
assertEquals("B", f6.get(1000, TimeUnit.MILLISECONDS));
} catch (Exception e) {
throw new RuntimeException(e);
}
// request caching is turned off on this so we expect 2 command executions
assertEquals(2, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
// we expect to see it with SUCCESS and COLLAPSED and both
HystrixInvokableInfo<?> commandA = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().toArray(new HystrixInvokableInfo<?>[2])[0];
assertEquals(2, commandA.getExecutionEvents().size());
assertTrue(commandA.getExecutionEvents().contains(HystrixEventType.SUCCESS));
assertTrue(commandA.getExecutionEvents().contains(HystrixEventType.COLLAPSED));
// we expect to see it with SUCCESS and COLLAPSED and both
HystrixInvokableInfo<?> commandB = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().toArray(new HystrixInvokableInfo<?>[2])[1];
assertEquals(2, commandB.getExecutionEvents().size());
assertTrue(commandB.getExecutionEvents().contains(HystrixEventType.SUCCESS));
assertTrue(commandB.getExecutionEvents().contains(HystrixEventType.COLLAPSED));
Iterator<HystrixInvokableInfo<?>> cmdIterator = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator();
assertEquals(2, cmdIterator.next().getNumberCollapsed()); //1 for A, 1 for B. Batch contains only unique arguments (no duplicates)
assertEquals(2, cmdIterator.next().getNumberCollapsed()); //1 for A, 1 for B. Batch contains only unique arguments (no duplicates)
}
/**
* Test command that uses a null request argument
*/
@Test
public void testRequestCacheWithNullRequestArgument() throws Exception {
ConcurrentLinkedQueue<HystrixCommand<List<String>>> commands = new ConcurrentLinkedQueue<HystrixCommand<List<String>>>();
final TestCollapserTimer timer = new TestCollapserTimer();
SuccessfulCacheableCollapsedCommand command1 = new SuccessfulCacheableCollapsedCommand(timer, null, true, commands);
SuccessfulCacheableCollapsedCommand command2 = new SuccessfulCacheableCollapsedCommand(timer, null, true, commands);
Future<String> f1 = command1.queue();
Future<String> f2 = command2.queue();
// increment past batch time so it executes
timer.incrementTime(15);
assertEquals("NULL", f1.get(1000, TimeUnit.MILLISECONDS));
assertEquals("NULL", f2.get(1000, TimeUnit.MILLISECONDS));
// it should have executed 1 command
assertEquals(1, commands.size());
assertTrue(commands.peek().getExecutionEvents().contains(HystrixEventType.SUCCESS));
assertTrue(commands.peek().getExecutionEvents().contains(HystrixEventType.COLLAPSED));
Future<String> f3 = command1.queue();
// increment past batch time so it executes
timer.incrementTime(15);
assertEquals("NULL", f3.get(1000, TimeUnit.MILLISECONDS));
// it should still be 1 ... no new executions
assertEquals(1, commands.size());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
Iterator<HystrixInvokableInfo<?>> cmdIterator = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator();
assertEquals(1, cmdIterator.next().getNumberCollapsed());
}
@Test
public void testRequestCacheWithCommandError() {
ConcurrentLinkedQueue<HystrixCommand<List<String>>> commands = new ConcurrentLinkedQueue<HystrixCommand<List<String>>>();
final TestCollapserTimer timer = new TestCollapserTimer();
SuccessfulCacheableCollapsedCommand command1 = new SuccessfulCacheableCollapsedCommand(timer, "FAILURE", true, commands);
SuccessfulCacheableCollapsedCommand command2 = new SuccessfulCacheableCollapsedCommand(timer, "FAILURE", true, commands);
Future<String> f1 = command1.queue();
Future<String> f2 = command2.queue();
// increment past batch time so it executes
timer.incrementTime(15);
try {
assertEquals("A", f1.get(1000, TimeUnit.MILLISECONDS));
assertEquals("A", f2.get(1000, TimeUnit.MILLISECONDS));
fail("exception should have been thrown");
} catch (Exception e) {
// expected
}
// it should have executed 1 command
assertEquals(1, commands.size());
assertTrue(commands.peek().getExecutionEvents().contains(HystrixEventType.FAILURE));
assertTrue(commands.peek().getExecutionEvents().contains(HystrixEventType.COLLAPSED));
Future<String> f3 = command1.queue();
// increment past batch time so it executes
timer.incrementTime(15);
try {
assertEquals("A", f3.get(1000, TimeUnit.MILLISECONDS));
fail("exception should have been thrown");
} catch (Exception e) {
// expected
}
// it should still be 1 ... no new executions
assertEquals(1, commands.size());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
Iterator<HystrixInvokableInfo<?>> cmdIterator = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator();
assertEquals(1, cmdIterator.next().getNumberCollapsed());
}
/**
* Test that a command that times out will still be cached and when retrieved will re-throw the exception.
*/
@Test
public void testRequestCacheWithCommandTimeout() {
ConcurrentLinkedQueue<HystrixCommand<List<String>>> commands = new ConcurrentLinkedQueue<HystrixCommand<List<String>>>();
final TestCollapserTimer timer = new TestCollapserTimer();
SuccessfulCacheableCollapsedCommand command1 = new SuccessfulCacheableCollapsedCommand(timer, "TIMEOUT", true, commands);
SuccessfulCacheableCollapsedCommand command2 = new SuccessfulCacheableCollapsedCommand(timer, "TIMEOUT", true, commands);
Future<String> f1 = command1.queue();
Future<String> f2 = command2.queue();
// increment past batch time so it executes
timer.incrementTime(15);
try {
assertEquals("A", f1.get(1000, TimeUnit.MILLISECONDS));
assertEquals("A", f2.get(1000, TimeUnit.MILLISECONDS));
fail("exception should have been thrown");
} catch (Exception e) {
// expected
}
// it should have executed 1 command
assertEquals(1, commands.size());
assertTrue(commands.peek().getExecutionEvents().contains(HystrixEventType.TIMEOUT));
assertTrue(commands.peek().getExecutionEvents().contains(HystrixEventType.COLLAPSED));
Future<String> f3 = command1.queue();
// increment past batch time so it executes
timer.incrementTime(15);
try {
assertEquals("A", f3.get(1000, TimeUnit.MILLISECONDS));
fail("exception should have been thrown");
} catch (Exception e) {
// expected
}
// it should still be 1 ... no new executions
assertEquals(1, commands.size());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
Iterator<HystrixInvokableInfo<?>> cmdIterator = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator();
assertEquals(1, cmdIterator.next().getNumberCollapsed());
}
/**
* Test how the collapser behaves when the circuit is short-circuited
*/
@Test
public void testRequestWithCommandShortCircuited() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixCollapser<List<String>, String, String> collapser1 = new TestRequestCollapserWithShortCircuitedCommand(timer, "1");
Observable<String> response1 = collapser1.observe();
Observable<String> response2 = new TestRequestCollapserWithShortCircuitedCommand(timer, "2").observe();
timer.incrementTime(10); // let time pass that equals the default delay/period
try {
response1.toBlocking().first();
fail("we should have received an exception");
} catch (Exception e) {
e.printStackTrace();
// what we expect
}
try {
response2.toBlocking().first();
fail("we should have received an exception");
} catch (Exception e) {
e.printStackTrace();
// what we expect
}
// it will execute once (short-circuited)
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
Iterator<HystrixInvokableInfo<?>> cmdIterator = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator();
assertEquals(2, cmdIterator.next().getNumberCollapsed());
}
/**
* Test a Void response type - null being set as response.
*
* @throws Exception
*/
@Test
public void testVoidResponseTypeFireAndForgetCollapsing1() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
TestCollapserWithVoidResponseType collapser1 = new TestCollapserWithVoidResponseType(timer, 1);
Future<Void> response1 = collapser1.queue();
Future<Void> response2 = new TestCollapserWithVoidResponseType(timer, 2).queue();
timer.incrementTime(100); // let time pass that equals the default delay/period
// normally someone wouldn't wait on these, but we need to make sure they do in fact return
// and not block indefinitely in case someone does call get()
assertEquals(null, response1.get(1000, TimeUnit.MILLISECONDS));
assertEquals(null, response2.get(1000, TimeUnit.MILLISECONDS));
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
Iterator<HystrixInvokableInfo<?>> cmdIterator = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator();
assertEquals(2, cmdIterator.next().getNumberCollapsed());
}
/**
* Test a Void response type - response never being set in mapResponseToRequest
*
* @throws Exception
*/
@Test
public void testVoidResponseTypeFireAndForgetCollapsing2() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
TestCollapserWithVoidResponseTypeAndMissingMapResponseToRequests collapser1 = new TestCollapserWithVoidResponseTypeAndMissingMapResponseToRequests(timer, 1);
Future<Void> response1 = collapser1.queue();
new TestCollapserWithVoidResponseTypeAndMissingMapResponseToRequests(timer, 2).queue();
timer.incrementTime(100); // let time pass that equals the default delay/period
// we will fetch one of these just so we wait for completion ... but expect an error
try {
assertEquals(null, response1.get(1000, TimeUnit.MILLISECONDS));
fail("expected an error as mapResponseToRequests did not set responses");
} catch (ExecutionException e) {
assertTrue(e.getCause() instanceof IllegalStateException);
assertTrue(e.getCause().getMessage().startsWith("No response set by"));
}
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
Iterator<HystrixInvokableInfo<?>> cmdIterator = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator();
assertEquals(2, cmdIterator.next().getNumberCollapsed());
}
/**
* Test a Void response type with execute - response being set in mapResponseToRequest to null
*
* @throws Exception
*/
@Test
public void testVoidResponseTypeFireAndForgetCollapsing3() throws Exception {
CollapserTimer timer = new RealCollapserTimer();
TestCollapserWithVoidResponseType collapser1 = new TestCollapserWithVoidResponseType(timer, 1);
assertNull(collapser1.execute());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
Iterator<HystrixInvokableInfo<?>> cmdIterator = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator();
assertEquals(1, cmdIterator.next().getNumberCollapsed());
}
@Test
public void testEarlyUnsubscribeExecutedViaToObservable() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixCollapser<List<String>, String, String> collapser1 = new TestRequestCollapser(timer, 1);
Observable<String> response1 = collapser1.toObservable();
HystrixCollapser<List<String>, String, String> collapser2 = new TestRequestCollapser(timer, 2);
Observable<String> response2 = collapser2.toObservable();
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final AtomicReference<String> value1 = new AtomicReference<String>(null);
final AtomicReference<String> value2 = new AtomicReference<String>(null);
Subscription s1 = response1
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s1 Unsubscribed!");
latch1.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s1 OnCompleted");
latch1.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s1 OnError : " + e);
latch1.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s1 OnNext : " + s);
value1.set(s);
}
});
Subscription s2 = response2
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s2 Unsubscribed!");
latch2.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s2 OnCompleted");
latch2.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s2 OnError : " + e);
latch2.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s2 OnNext : " + s);
value2.set(s);
}
});
s1.unsubscribe();
timer.incrementTime(10); // let time pass that equals the default delay/period
assertTrue(latch1.await(1000, TimeUnit.MILLISECONDS));
assertTrue(latch2.await(1000, TimeUnit.MILLISECONDS));
assertNull(value1.get());
assertEquals("2", value2.get());
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixCollapserMetrics metrics = collapser1.getMetrics();
assertSame(metrics, collapser2.getMetrics());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator().next();
assertEquals(1, command.getNumberCollapsed()); //1 should have been removed from batch
}
@Test
public void testEarlyUnsubscribeExecutedViaObserve() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixCollapser<List<String>, String, String> collapser1 = new TestRequestCollapser(timer, 1);
Observable<String> response1 = collapser1.observe();
HystrixCollapser<List<String>, String, String> collapser2 = new TestRequestCollapser(timer, 2);
Observable<String> response2 = collapser2.observe();
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final AtomicReference<String> value1 = new AtomicReference<String>(null);
final AtomicReference<String> value2 = new AtomicReference<String>(null);
Subscription s1 = response1
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s1 Unsubscribed!");
latch1.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s1 OnCompleted");
latch1.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s1 OnError : " + e);
latch1.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s1 OnNext : " + s);
value1.set(s);
}
});
Subscription s2 = response2
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s2 Unsubscribed!");
latch2.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s2 OnCompleted");
latch2.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s2 OnError : " + e);
latch2.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s2 OnNext : " + s);
value2.set(s);
}
});
s1.unsubscribe();
timer.incrementTime(10); // let time pass that equals the default delay/period
assertTrue(latch1.await(1000, TimeUnit.MILLISECONDS));
assertTrue(latch2.await(1000, TimeUnit.MILLISECONDS));
assertNull(value1.get());
assertEquals("2", value2.get());
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixCollapserMetrics metrics = collapser1.getMetrics();
assertSame(metrics, collapser2.getMetrics());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator().next();
assertEquals(1, command.getNumberCollapsed()); //1 should have been removed from batch
}
@Test
public void testEarlyUnsubscribeFromAllCancelsBatch() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixCollapser<List<String>, String, String> collapser1 = new TestRequestCollapser(timer, 1);
Observable<String> response1 = collapser1.observe();
HystrixCollapser<List<String>, String, String> collapser2 = new TestRequestCollapser(timer, 2);
Observable<String> response2 = collapser2.observe();
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final AtomicReference<String> value1 = new AtomicReference<String>(null);
final AtomicReference<String> value2 = new AtomicReference<String>(null);
Subscription s1 = response1
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s1 Unsubscribed!");
latch1.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s1 OnCompleted");
latch1.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s1 OnError : " + e);
latch1.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s1 OnNext : " + s);
value1.set(s);
}
});
Subscription s2 = response2
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s2 Unsubscribed!");
latch2.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s2 OnCompleted");
latch2.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s2 OnError : " + e);
latch2.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s2 OnNext : " + s);
value2.set(s);
}
});
s1.unsubscribe();
s2.unsubscribe();
timer.incrementTime(10); // let time pass that equals the default delay/period
assertTrue(latch1.await(1000, TimeUnit.MILLISECONDS));
assertTrue(latch2.await(1000, TimeUnit.MILLISECONDS));
assertNull(value1.get());
assertNull(value2.get());
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertEquals(0, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
}
@Test
public void testRequestThenCacheHitAndCacheHitUnsubscribed() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixCollapser<List<String>, String, String> collapser1 = new SuccessfulCacheableCollapsedCommand(timer, "foo", true);
Observable<String> response1 = collapser1.observe();
HystrixCollapser<List<String>, String, String> collapser2 = new SuccessfulCacheableCollapsedCommand(timer, "foo", true);
Observable<String> response2 = collapser2.observe();
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final AtomicReference<String> value1 = new AtomicReference<String>(null);
final AtomicReference<String> value2 = new AtomicReference<String>(null);
Subscription s1 = response1
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s1 Unsubscribed!");
latch1.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s1 OnCompleted");
latch1.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s1 OnError : " + e);
latch1.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s1 OnNext : " + s);
value1.set(s);
}
});
Subscription s2 = response2
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s2 Unsubscribed!");
latch2.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s2 OnCompleted");
latch2.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s2 OnError : " + e);
latch2.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s2 OnNext : " + s);
value2.set(s);
}
});
s2.unsubscribe();
timer.incrementTime(10); // let time pass that equals the default delay/period
assertTrue(latch1.await(1000, TimeUnit.MILLISECONDS));
assertTrue(latch2.await(1000, TimeUnit.MILLISECONDS));
assertEquals("foo", value1.get());
assertNull(value2.get());
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator().next();
assertCommandExecutionEvents(command, HystrixEventType.SUCCESS, HystrixEventType.COLLAPSED);
assertEquals(1, command.getNumberCollapsed()); //should only be 1 collapsed - other came from cache, then was cancelled
}
@Test
public void testRequestThenCacheHitAndOriginalUnsubscribed() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixCollapser<List<String>, String, String> collapser1 = new SuccessfulCacheableCollapsedCommand(timer, "foo", true);
Observable<String> response1 = collapser1.observe();
HystrixCollapser<List<String>, String, String> collapser2 = new SuccessfulCacheableCollapsedCommand(timer, "foo", true);
Observable<String> response2 = collapser2.observe();
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final AtomicReference<String> value1 = new AtomicReference<String>(null);
final AtomicReference<String> value2 = new AtomicReference<String>(null);
Subscription s1 = response1
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s1 Unsubscribed!");
latch1.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s1 OnCompleted");
latch1.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s1 OnError : " + e);
latch1.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s1 OnNext : " + s);
value1.set(s);
}
});
Subscription s2 = response2
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s2 Unsubscribed!");
latch2.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s2 OnCompleted");
latch2.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s2 OnError : " + e);
latch2.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s2 OnNext : " + s);
value2.set(s);
}
});
s1.unsubscribe();
timer.incrementTime(10); // let time pass that equals the default delay/period
assertTrue(latch1.await(1000, TimeUnit.MILLISECONDS));
assertTrue(latch2.await(1000, TimeUnit.MILLISECONDS));
assertNull(value1.get());
assertEquals("foo", value2.get());
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator().next();
assertCommandExecutionEvents(command, HystrixEventType.SUCCESS, HystrixEventType.COLLAPSED);
assertEquals(1, command.getNumberCollapsed()); //should only be 1 collapsed - other came from cache, then was cancelled
}
@Test
public void testRequestThenTwoCacheHitsOriginalAndOneCacheHitUnsubscribed() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixCollapser<List<String>, String, String> collapser1 = new SuccessfulCacheableCollapsedCommand(timer, "foo", true);
Observable<String> response1 = collapser1.observe();
HystrixCollapser<List<String>, String, String> collapser2 = new SuccessfulCacheableCollapsedCommand(timer, "foo", true);
Observable<String> response2 = collapser2.observe();
HystrixCollapser<List<String>, String, String> collapser3 = new SuccessfulCacheableCollapsedCommand(timer, "foo", true);
Observable<String> response3 = collapser3.observe();
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final CountDownLatch latch3 = new CountDownLatch(1);
final AtomicReference<String> value1 = new AtomicReference<String>(null);
final AtomicReference<String> value2 = new AtomicReference<String>(null);
final AtomicReference<String> value3 = new AtomicReference<String>(null);
Subscription s1 = response1
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s1 Unsubscribed!");
latch1.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s1 OnCompleted");
latch1.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s1 OnError : " + e);
latch1.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s1 OnNext : " + s);
value1.set(s);
}
});
Subscription s2 = response2
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s2 Unsubscribed!");
latch2.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s2 OnCompleted");
latch2.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s2 OnError : " + e);
latch2.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s2 OnNext : " + s);
value2.set(s);
}
});
Subscription s3 = response3
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s3 Unsubscribed!");
latch3.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s3 OnCompleted");
latch3.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s3 OnError : " + e);
latch3.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s3 OnNext : " + s);
value3.set(s);
}
});
s1.unsubscribe();
s3.unsubscribe();
timer.incrementTime(10); // let time pass that equals the default delay/period
assertTrue(latch1.await(1000, TimeUnit.MILLISECONDS));
assertTrue(latch2.await(1000, TimeUnit.MILLISECONDS));
assertNull(value1.get());
assertEquals("foo", value2.get());
assertNull(value3.get());
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator().next();
assertCommandExecutionEvents(command, HystrixEventType.SUCCESS, HystrixEventType.COLLAPSED);
assertEquals(1, command.getNumberCollapsed()); //should only be 1 collapsed - other came from cache, then was cancelled
}
@Test
public void testRequestThenTwoCacheHitsAllUnsubscribed() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixCollapser<List<String>, String, String> collapser1 = new SuccessfulCacheableCollapsedCommand(timer, "foo", true);
Observable<String> response1 = collapser1.observe();
HystrixCollapser<List<String>, String, String> collapser2 = new SuccessfulCacheableCollapsedCommand(timer, "foo", true);
Observable<String> response2 = collapser2.observe();
HystrixCollapser<List<String>, String, String> collapser3 = new SuccessfulCacheableCollapsedCommand(timer, "foo", true);
Observable<String> response3 = collapser3.observe();
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final CountDownLatch latch3 = new CountDownLatch(1);
final AtomicReference<String> value1 = new AtomicReference<String>(null);
final AtomicReference<String> value2 = new AtomicReference<String>(null);
final AtomicReference<String> value3 = new AtomicReference<String>(null);
Subscription s1 = response1
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s1 Unsubscribed!");
latch1.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s1 OnCompleted");
latch1.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s1 OnError : " + e);
latch1.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s1 OnNext : " + s);
value1.set(s);
}
});
Subscription s2 = response2
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s2 Unsubscribed!");
latch2.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s2 OnCompleted");
latch2.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s2 OnError : " + e);
latch2.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s2 OnNext : " + s);
value2.set(s);
}
});
Subscription s3 = response3
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s3 Unsubscribed!");
latch3.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s3 OnCompleted");
latch3.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s3 OnError : " + e);
latch3.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s3 OnNext : " + s);
value3.set(s);
}
});
s1.unsubscribe();
s2.unsubscribe();
s3.unsubscribe();
timer.incrementTime(10); // let time pass that equals the default delay/period
assertTrue(latch1.await(1000, TimeUnit.MILLISECONDS));
assertTrue(latch2.await(1000, TimeUnit.MILLISECONDS));
assertNull(value1.get());
assertNull(value2.get());
assertNull(value3.get());
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertEquals(0, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
}
protected void assertCommandExecutionEvents(HystrixInvokableInfo<?> command, HystrixEventType... expectedEventTypes) {
boolean emitExpected = false;
int expectedEmitCount = 0;
boolean fallbackEmitExpected = false;
int expectedFallbackEmitCount = 0;
List<HystrixEventType> condensedEmitExpectedEventTypes = new ArrayList<HystrixEventType>();
for (HystrixEventType expectedEventType: expectedEventTypes) {
if (expectedEventType.equals(HystrixEventType.EMIT)) {
if (!emitExpected) {
//first EMIT encountered, add it to condensedEmitExpectedEventTypes
condensedEmitExpectedEventTypes.add(HystrixEventType.EMIT);
}
emitExpected = true;
expectedEmitCount++;
} else if (expectedEventType.equals(HystrixEventType.FALLBACK_EMIT)) {
if (!fallbackEmitExpected) {
//first FALLBACK_EMIT encountered, add it to condensedEmitExpectedEventTypes
condensedEmitExpectedEventTypes.add(HystrixEventType.FALLBACK_EMIT);
}
fallbackEmitExpected = true;
expectedFallbackEmitCount++;
} else {
condensedEmitExpectedEventTypes.add(expectedEventType);
}
}
List<HystrixEventType> actualEventTypes = command.getExecutionEvents();
assertEquals(expectedEmitCount, command.getNumberEmissions());
assertEquals(expectedFallbackEmitCount, command.getNumberFallbackEmissions());
assertEquals(condensedEmitExpectedEventTypes, actualEventTypes);
}
private static class TestRequestCollapser extends HystrixCollapser<List<String>, String, String> {
private final String value;
private ConcurrentLinkedQueue<HystrixCommand<List<String>>> commandsExecuted;
public TestRequestCollapser(TestCollapserTimer timer, int value) {
this(timer, String.valueOf(value));
}
public TestRequestCollapser(TestCollapserTimer timer, String value) {
this(timer, value, 10000, 10);
}
public TestRequestCollapser(Scope scope, TestCollapserTimer timer, String value) {
this(scope, timer, value, 10000, 10);
}
public TestRequestCollapser(TestCollapserTimer timer, String value, ConcurrentLinkedQueue<HystrixCommand<List<String>>> executionLog) {
this(timer, value, 10000, 10, executionLog);
}
public TestRequestCollapser(TestCollapserTimer timer, int value, int defaultMaxRequestsInBatch, int defaultTimerDelayInMilliseconds) {
this(timer, String.valueOf(value), defaultMaxRequestsInBatch, defaultTimerDelayInMilliseconds);
}
public TestRequestCollapser(TestCollapserTimer timer, String value, int defaultMaxRequestsInBatch, int defaultTimerDelayInMilliseconds) {
this(timer, value, defaultMaxRequestsInBatch, defaultTimerDelayInMilliseconds, null);
}
public TestRequestCollapser(Scope scope, TestCollapserTimer timer, String value, int defaultMaxRequestsInBatch, int defaultTimerDelayInMilliseconds) {
this(scope, timer, value, defaultMaxRequestsInBatch, defaultTimerDelayInMilliseconds, null);
}
public TestRequestCollapser(TestCollapserTimer timer, String value, int defaultMaxRequestsInBatch, int defaultTimerDelayInMilliseconds, ConcurrentLinkedQueue<HystrixCommand<List<String>>> executionLog) {
this(Scope.REQUEST, timer, value, defaultMaxRequestsInBatch, defaultTimerDelayInMilliseconds, executionLog);
}
private static HystrixCollapserMetrics createMetrics() {
HystrixCollapserKey key = HystrixCollapserKey.Factory.asKey("COLLAPSER_ONE");
return HystrixCollapserMetrics.getInstance(key, new HystrixPropertiesCollapserDefault(key, HystrixCollapserProperties.Setter()));
}
public TestRequestCollapser(Scope scope, TestCollapserTimer timer, String value, int defaultMaxRequestsInBatch, int defaultTimerDelayInMilliseconds, ConcurrentLinkedQueue<HystrixCommand<List<String>>> executionLog) {
// use a CollapserKey based on the CollapserTimer object reference so it's unique for each timer as we don't want caching
// of properties to occur and we're using the default HystrixProperty which typically does caching
super(collapserKeyFromString(timer), scope, timer, HystrixCollapserProperties.Setter().withMaxRequestsInBatch(defaultMaxRequestsInBatch).withTimerDelayInMilliseconds(defaultTimerDelayInMilliseconds), createMetrics());
this.value = value;
this.commandsExecuted = executionLog;
}
@Override
public String getRequestArgument() {
return value;
}
@Override
public HystrixCommand<List<String>> createCommand(final Collection<CollapsedRequest<String, String>> requests) {
/* return a mocked command */
HystrixCommand<List<String>> command = new TestCollapserCommand(requests);
if (commandsExecuted != null) {
commandsExecuted.add(command);
}
return command;
}
@Override
public void mapResponseToRequests(List<String> batchResponse, Collection<CollapsedRequest<String, String>> requests) {
// for simplicity I'll assume it's a 1:1 mapping between lists ... in real implementations they often need to index to maps
// to allow random access as the response size does not match the request size
if (batchResponse.size() != requests.size()) {
throw new RuntimeException("lists don't match in size => " + batchResponse.size() + " : " + requests.size());
}
int i = 0;
for (CollapsedRequest<String, String> request : requests) {
request.setResponse(batchResponse.get(i++));
}
}
}
/**
* Shard on the artificially provided 'type' variable.
*/
private static class TestShardedRequestCollapser extends TestRequestCollapser {
public TestShardedRequestCollapser(TestCollapserTimer timer, String value) {
super(timer, value);
}
@Override
protected Collection<Collection<CollapsedRequest<String, String>>> shardRequests(Collection<CollapsedRequest<String, String>> requests) {
Collection<CollapsedRequest<String, String>> typeA = new ArrayList<CollapsedRequest<String, String>>();
Collection<CollapsedRequest<String, String>> typeB = new ArrayList<CollapsedRequest<String, String>>();
for (CollapsedRequest<String, String> request : requests) {
if (request.getArgument().endsWith("a")) {
typeA.add(request);
} else if (request.getArgument().endsWith("b")) {
typeB.add(request);
}
}
ArrayList<Collection<CollapsedRequest<String, String>>> shards = new ArrayList<Collection<CollapsedRequest<String, String>>>();
shards.add(typeA);
shards.add(typeB);
return shards;
}
}
/**
* Test the global scope
*/
private static class TestGloballyScopedRequestCollapser extends TestRequestCollapser {
public TestGloballyScopedRequestCollapser(TestCollapserTimer timer, String value) {
super(Scope.GLOBAL, timer, value);
}
}
/**
* Throw an exception when creating a command.
*/
private static class TestRequestCollapserWithFaultyCreateCommand extends TestRequestCollapser {
public TestRequestCollapserWithFaultyCreateCommand(TestCollapserTimer timer, String value) {
super(timer, value);
}
@Override
public HystrixCommand<List<String>> createCommand(Collection<CollapsedRequest<String, String>> requests) {
throw new RuntimeException("some failure");
}
}
/**
* Throw an exception when creating a command.
*/
private static class TestRequestCollapserWithShortCircuitedCommand extends TestRequestCollapser {
public TestRequestCollapserWithShortCircuitedCommand(TestCollapserTimer timer, String value) {
super(timer, value);
}
@Override
public HystrixCommand<List<String>> createCommand(Collection<CollapsedRequest<String, String>> requests) {
// args don't matter as it's short-circuited
return new ShortCircuitedCommand();
}
}
/**
* Throw an exception when mapToResponse is invoked
*/
private static class TestRequestCollapserWithFaultyMapToResponse extends TestRequestCollapser {
public TestRequestCollapserWithFaultyMapToResponse(TestCollapserTimer timer, String value) {
super(timer, value);
}
@Override
public void mapResponseToRequests(List<String> batchResponse, Collection<CollapsedRequest<String, String>> requests) {
// pretend we blow up with an NPE
throw new NullPointerException("batchResponse was null and we blew up");
}
}
private static class TestCollapserCommand extends TestHystrixCommand<List<String>> {
private final Collection<CollapsedRequest<String, String>> requests;
TestCollapserCommand(Collection<CollapsedRequest<String, String>> requests) {
super(testPropsBuilder().setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionTimeoutInMilliseconds(500)));
this.requests = requests;
}
@Override
protected List<String> run() {
System.out.println(">>> TestCollapserCommand run() ... batch size: " + requests.size());
// simulate a batch request
ArrayList<String> response = new ArrayList<String>();
for (CollapsedRequest<String, String> request : requests) {
if (request.getArgument() == null) {
response.add("NULL");
} else {
if (request.getArgument().equals("FAILURE")) {
throw new NullPointerException("Simulated Error");
}
if (request.getArgument().equals("TIMEOUT")) {
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
response.add(request.getArgument());
}
}
return response;
}
}
/**
* A Command implementation that supports caching.
*/
private static class SuccessfulCacheableCollapsedCommand extends TestRequestCollapser {
private final boolean cacheEnabled;
public SuccessfulCacheableCollapsedCommand(TestCollapserTimer timer, String value, boolean cacheEnabled) {
super(timer, value);
this.cacheEnabled = cacheEnabled;
}
public SuccessfulCacheableCollapsedCommand(TestCollapserTimer timer, String value, boolean cacheEnabled, ConcurrentLinkedQueue<HystrixCommand<List<String>>> executionLog) {
super(timer, value, executionLog);
this.cacheEnabled = cacheEnabled;
}
@Override
public String getCacheKey() {
if (cacheEnabled)
return "aCacheKey_" + super.value;
else
return null;
}
}
private static class ShortCircuitedCommand extends HystrixCommand<List<String>> {
protected ShortCircuitedCommand() {
super(HystrixCommand.Setter.withGroupKey(
HystrixCommandGroupKey.Factory.asKey("shortCircuitedCommand"))
.andCommandPropertiesDefaults(HystrixCommandPropertiesTest
.getUnitTestPropertiesSetter()
.withCircuitBreakerForceOpen(true)));
}
@Override
protected List<String> run() throws Exception {
System.out.println("*** execution (this shouldn't happen)");
// this won't ever get called as we're forcing short-circuiting
ArrayList<String> values = new ArrayList<String>();
values.add("hello");
return values;
}
}
private static class FireAndForgetCommand extends HystrixCommand<Void> {
protected FireAndForgetCommand(List<Integer> values) {
super(HystrixCommand.Setter.withGroupKey(
HystrixCommandGroupKey.Factory.asKey("fireAndForgetCommand"))
.andCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter()));
}
@Override
protected Void run() throws Exception {
System.out.println("*** FireAndForgetCommand execution: " + Thread.currentThread());
return null;
}
}
/* package */ static class TestCollapserTimer implements CollapserTimer {
private final ConcurrentLinkedQueue<ATask> tasks = new ConcurrentLinkedQueue<ATask>();
@Override
public Reference<TimerListener> addListener(final TimerListener collapseTask) {
tasks.add(new ATask(new TestTimerListener(collapseTask)));
/**
* This is a hack that overrides 'clear' of a WeakReference to match the required API
* but then removes the strong-reference we have inside 'tasks'.
* <p>
* We do this so our unit tests know if the WeakReference is cleared correctly, and if so then the ATack is removed from 'tasks'
*/
return new SoftReference<TimerListener>(collapseTask) {
@Override
public void clear() {
// super.clear();
for (ATask t : tasks) {
if (t.task.actualListener.equals(collapseTask)) {
tasks.remove(t);
}
}
}
};
}
/**
* Increment time by X. Note that incrementing by multiples of delay or period time will NOT execute multiple times.
* <p>
* You must call incrementTime multiple times each increment being larger than 'period' on subsequent calls to cause multiple executions.
* <p>
* This is because executing multiple times in a tight-loop would not achieve the correct behavior, such as batching, since it will all execute "now" not after intervals of time.
*
* @param timeInMilliseconds amount of time to increment
*/
public synchronized void incrementTime(int timeInMilliseconds) {
for (ATask t : tasks) {
t.incrementTime(timeInMilliseconds);
}
}
private static class ATask {
final TestTimerListener task;
final int delay = 10;
// our relative time that we'll use
volatile int time = 0;
volatile int executionCount = 0;
private ATask(TestTimerListener task) {
this.task = task;
}
public synchronized void incrementTime(int timeInMilliseconds) {
time += timeInMilliseconds;
if (task != null) {
if (executionCount == 0) {
System.out.println("ExecutionCount 0 => Time: " + time + " Delay: " + delay);
if (time >= delay) {
// first execution, we're past the delay time
executeTask();
}
} else {
System.out.println("ExecutionCount 1+ => Time: " + time + " Delay: " + delay);
if (time >= delay) {
// subsequent executions, we're past the interval time
executeTask();
}
}
}
}
private synchronized void executeTask() {
System.out.println("Executing task ...");
task.tick();
this.time = 0; // we reset time after each execution
this.executionCount++;
System.out.println("executionCount: " + executionCount);
}
}
}
private static class TestTimerListener implements TimerListener {
private final TimerListener actualListener;
private final AtomicInteger count = new AtomicInteger();
public TestTimerListener(TimerListener actual) {
this.actualListener = actual;
}
@Override
public void tick() {
count.incrementAndGet();
actualListener.tick();
}
@Override
public int getIntervalTimeInMilliseconds() {
return 10;
}
}
private static HystrixCollapserKey collapserKeyFromString(final Object o) {
return new HystrixCollapserKey() {
@Override
public String name() {
return String.valueOf(o);
}
};
}
private static class TestCollapserWithVoidResponseType extends HystrixCollapser<Void, Void, Integer> {
private final Integer value;
public TestCollapserWithVoidResponseType(CollapserTimer timer, int value) {
super(collapserKeyFromString(timer), Scope.REQUEST, timer, HystrixCollapserProperties.Setter().withMaxRequestsInBatch(1000).withTimerDelayInMilliseconds(50));
this.value = value;
}
@Override
public Integer getRequestArgument() {
return value;
}
@Override
protected HystrixCommand<Void> createCommand(Collection<CollapsedRequest<Void, Integer>> requests) {
ArrayList<Integer> args = new ArrayList<Integer>();
for (CollapsedRequest<Void, Integer> request : requests) {
args.add(request.getArgument());
}
return new FireAndForgetCommand(args);
}
@Override
protected void mapResponseToRequests(Void batchResponse, Collection<CollapsedRequest<Void, Integer>> requests) {
for (CollapsedRequest<Void, Integer> r : requests) {
r.setResponse(null);
}
}
}
private static class TestCollapserWithVoidResponseTypeAndMissingMapResponseToRequests extends HystrixCollapser<Void, Void, Integer> {
private final Integer value;
public TestCollapserWithVoidResponseTypeAndMissingMapResponseToRequests(CollapserTimer timer, int value) {
super(collapserKeyFromString(timer), Scope.REQUEST, timer, HystrixCollapserProperties.Setter().withMaxRequestsInBatch(1000).withTimerDelayInMilliseconds(50));
this.value = value;
}
@Override
public Integer getRequestArgument() {
return value;
}
@Override
protected HystrixCommand<Void> createCommand(Collection<CollapsedRequest<Void, Integer>> requests) {
ArrayList<Integer> args = new ArrayList<Integer>();
for (CollapsedRequest<Void, Integer> request : requests) {
args.add(request.getArgument());
}
return new FireAndForgetCommand(args);
}
@Override
protected void mapResponseToRequests(Void batchResponse, Collection<CollapsedRequest<Void, Integer>> requests) {
}
}
}
| 4,563 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/HystrixCommandTest.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix;
import com.hystrix.junit.HystrixRequestContextRule;
import com.netflix.config.ConfigurationManager;
import com.netflix.hystrix.AbstractCommand.TryableSemaphore;
import com.netflix.hystrix.AbstractCommand.TryableSemaphoreActual;
import com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker;
import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import com.netflix.hystrix.strategy.HystrixPlugins;
import com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable;
import com.netflix.hystrix.strategy.concurrency.HystrixContextScheduler;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook;
import com.netflix.hystrix.strategy.properties.HystrixProperty;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import rx.Observable;
import rx.Observer;
import rx.Scheduler;
import rx.Subscriber;
import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.observers.TestSubscriber;
import rx.schedulers.Schedulers;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.*;
public class HystrixCommandTest extends CommonHystrixCommandTests<TestHystrixCommand<Integer>> {
@Rule
public HystrixRequestContextRule ctx = new HystrixRequestContextRule();
@After
public void cleanup() {
// force properties to be clean as well
ConfigurationManager.getConfigInstance().clear();
HystrixCommandKey key = Hystrix.getCurrentThreadExecutingCommand();
if (key != null) {
System.out.println("WARNING: Hystrix.getCurrentThreadExecutingCommand() should be null but got: " + key + ". Can occur when calling queue() and never retrieving.");
}
}
/**
* Test a successful command execution.
*/
@Test
public void testExecutionSuccess() {
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS);
assertEquals(FlexibleTestHystrixCommand.EXECUTE_VALUE, command.execute());
assertEquals(null, command.getFailedExecutionException());
assertNull(command.getExecutionException());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isSuccessfulExecution());
assertCommandExecutionEvents(command, HystrixEventType.SUCCESS);
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertSaneHystrixRequestLog(1);
}
/**
* Test that a command can not be executed multiple times.
*/
@Test
public void testExecutionMultipleTimes() {
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS);
assertFalse(command.isExecutionComplete());
// first should succeed
assertEquals(FlexibleTestHystrixCommand.EXECUTE_VALUE, command.execute());
assertTrue(command.isExecutionComplete());
assertTrue(command.isExecutedInThread());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isSuccessfulExecution());
assertNull(command.getExecutionException());
try {
// second should fail
command.execute();
fail("we should not allow this ... it breaks the state of request logs");
} catch (HystrixRuntimeException e) {
e.printStackTrace();
// we want to get here
}
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
assertCommandExecutionEvents(command, HystrixEventType.SUCCESS);
}
/**
* Test a command execution that throws an HystrixException and didn't implement getFallback.
*/
@Test
public void testExecutionHystrixFailureWithNoFallback() {
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.HYSTRIX_FAILURE, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED);
try {
command.execute();
fail("we shouldn't get here");
} catch (HystrixRuntimeException e) {
e.printStackTrace();
assertNotNull(e.getFallbackException());
assertNotNull(e.getImplementingClass());
}
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isFailedExecution());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_MISSING);
assertNotNull(command.getExecutionException());
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test a command execution that throws an unknown exception (not HystrixException) and didn't implement getFallback.
*/
@Test
public void testExecutionFailureWithNoFallback() {
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.FAILURE, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED);
try {
command.execute();
fail("we shouldn't get here");
} catch (HystrixRuntimeException e) {
e.printStackTrace();
assertNotNull(e.getFallbackException());
assertNotNull(e.getImplementingClass());
}
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isFailedExecution());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_MISSING);
assertNotNull(command.getExecutionException());
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test a command execution that throws an exception that should not be wrapped.
*/
@Test
public void testNotWrappedExceptionWithNoFallback() {
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.NOT_WRAPPED_FAILURE, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED);
try {
command.execute();
fail("we shouldn't get here");
} catch (HystrixRuntimeException e) {
e.printStackTrace();
fail("we shouldn't get a HystrixRuntimeException");
} catch (RuntimeException e) {
assertTrue(e instanceof NotWrappedByHystrixTestRuntimeException);
}
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isFailedExecution());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_MISSING);
assertNotNull(command.getExecutionException());
assertTrue(command.getExecutionException() instanceof NotWrappedByHystrixTestRuntimeException);
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test a command execution that throws an exception that should not be wrapped.
*/
@Test
public void testNotWrappedBadRequestWithNoFallback() {
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.BAD_REQUEST_NOT_WRAPPED, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED);
try {
command.execute();
fail("we shouldn't get here");
} catch (HystrixRuntimeException e) {
e.printStackTrace();
fail("we shouldn't get a HystrixRuntimeException");
} catch (RuntimeException e) {
assertTrue(e instanceof NotWrappedByHystrixTestRuntimeException);
}
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.getEventCounts().contains(HystrixEventType.BAD_REQUEST));
assertCommandExecutionEvents(command, HystrixEventType.BAD_REQUEST);
assertNotNull(command.getExecutionException());
assertTrue(command.getExecutionException() instanceof HystrixBadRequestException);
assertTrue(command.getExecutionException().getCause() instanceof NotWrappedByHystrixTestRuntimeException);
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
@Test
public void testNotWrappedBadRequestWithFallback() throws Exception {
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.BAD_REQUEST_NOT_WRAPPED, AbstractTestHystrixCommand.FallbackResult.SUCCESS);
try {
command.execute();
fail("we shouldn't get here");
} catch (HystrixRuntimeException e) {
e.printStackTrace();
fail("we shouldn't get a HystrixRuntimeException");
} catch (RuntimeException e) {
assertTrue(e instanceof NotWrappedByHystrixTestRuntimeException);
}
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.getEventCounts().contains(HystrixEventType.BAD_REQUEST));
assertCommandExecutionEvents(command, HystrixEventType.BAD_REQUEST);
assertNotNull(command.getExecutionException());
assertTrue(command.getExecutionException() instanceof HystrixBadRequestException);
assertTrue(command.getExecutionException().getCause() instanceof NotWrappedByHystrixTestRuntimeException);
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test a command execution that fails but has a fallback.
*/
@Test
public void testExecutionFailureWithFallback() {
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.FAILURE, AbstractTestHystrixCommand.FallbackResult.SUCCESS);
assertEquals(FlexibleTestHystrixCommand.FALLBACK_VALUE, command.execute());
assertEquals("Execution Failure for TestHystrixCommand", command.getFailedExecutionException().getMessage());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isFailedExecution());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_SUCCESS);
assertNotNull(command.getExecutionException());
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test a command execution that throws exception that should not be wrapped but has a fallback.
*/
@Test
public void testNotWrappedExceptionWithFallback() {
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.NOT_WRAPPED_FAILURE, AbstractTestHystrixCommand.FallbackResult.SUCCESS);
assertEquals(FlexibleTestHystrixCommand.FALLBACK_VALUE, command.execute());
assertEquals("Raw exception for TestHystrixCommand", command.getFailedExecutionException().getMessage());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isFailedExecution());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_SUCCESS);
assertNotNull(command.getExecutionException());
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test a command execution that fails, has getFallback implemented but that fails as well.
*/
@Test
public void testExecutionFailureWithFallbackFailure() {
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.FAILURE, AbstractTestHystrixCommand.FallbackResult.FAILURE);
try {
command.execute();
fail("we shouldn't get here");
} catch (HystrixRuntimeException e) {
System.out.println("------------------------------------------------");
e.printStackTrace();
System.out.println("------------------------------------------------");
assertNotNull(e.getFallbackException());
}
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isFailedExecution());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_FAILURE);
assertNotNull(command.getExecutionException());
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test a successful command execution (asynchronously).
*/
@Test
public void testQueueSuccess() throws Exception {
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS);
Future<Integer> future = command.queue();
assertEquals(FlexibleTestHystrixCommand.EXECUTE_VALUE, future.get());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isSuccessfulExecution());
assertCommandExecutionEvents(command, HystrixEventType.SUCCESS);
assertNull(command.getExecutionException());
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test a command execution (asynchronously) that throws an HystrixException and didn't implement getFallback.
*/
@Test
public void testQueueKnownFailureWithNoFallback() {
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.HYSTRIX_FAILURE, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED);
try {
command.queue().get();
fail("we shouldn't get here");
} catch (Exception e) {
e.printStackTrace();
if (e.getCause() instanceof HystrixRuntimeException) {
HystrixRuntimeException de = (HystrixRuntimeException) e.getCause();
assertNotNull(de.getFallbackException());
assertNotNull(de.getImplementingClass());
} else {
fail("the cause should be HystrixRuntimeException");
}
}
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isFailedExecution());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_MISSING);
assertNotNull(command.getExecutionException());
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test a command execution (asynchronously) that throws an unknown exception (not HystrixException) and didn't implement getFallback.
*/
@Test
public void testQueueUnknownFailureWithNoFallback() {
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.FAILURE, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED);
try {
command.queue().get();
fail("we shouldn't get here");
} catch (Exception e) {
e.printStackTrace();
if (e.getCause() instanceof HystrixRuntimeException) {
HystrixRuntimeException de = (HystrixRuntimeException) e.getCause();
assertNotNull(de.getFallbackException());
assertNotNull(de.getImplementingClass());
} else {
fail("the cause should be HystrixRuntimeException");
}
}
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isFailedExecution());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_MISSING);
assertNotNull(command.getExecutionException());
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test a command execution (asynchronously) that fails but has a fallback.
*/
@Test
public void testQueueFailureWithFallback() {
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.FAILURE, AbstractTestHystrixCommand.FallbackResult.SUCCESS);
try {
Future<Integer> future = command.queue();
assertEquals(FlexibleTestHystrixCommand.FALLBACK_VALUE, future.get());
} catch (Exception e) {
e.printStackTrace();
fail("We should have received a response from the fallback.");
}
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isFailedExecution());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_SUCCESS);
assertNotNull(command.getExecutionException());
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test a command execution (asynchronously) that fails, has getFallback implemented but that fails as well.
*/
@Test
public void testQueueFailureWithFallbackFailure() {
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.FAILURE, AbstractTestHystrixCommand.FallbackResult.FAILURE);
try {
command.queue().get();
fail("we shouldn't get here");
} catch (Exception e) {
if (e.getCause() instanceof HystrixRuntimeException) {
HystrixRuntimeException de = (HystrixRuntimeException) e.getCause();
e.printStackTrace();
assertNotNull(de.getFallbackException());
} else {
fail("the cause should be HystrixRuntimeException");
}
}
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isFailedExecution());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_FAILURE);
assertNotNull(command.getExecutionException());
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test a successful command execution.
*/
@Test
public void testObserveSuccess() {
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS);
assertEquals(FlexibleTestHystrixCommand.EXECUTE_VALUE, command.observe().toBlocking().single());
assertEquals(null, command.getFailedExecutionException());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isSuccessfulExecution());
assertCommandExecutionEvents(command, HystrixEventType.SUCCESS);
assertNull(command.getExecutionException());
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test a successful command execution.
*/
@Test
public void testCallbackThreadForThreadIsolation() throws Exception {
final AtomicReference<Thread> commandThread = new AtomicReference<Thread>();
final AtomicReference<Thread> subscribeThread = new AtomicReference<Thread>();
TestHystrixCommand<Boolean> command = new TestHystrixCommand<Boolean>(TestHystrixCommand.testPropsBuilder()) {
@Override
protected Boolean run() {
commandThread.set(Thread.currentThread());
return true;
}
};
final CountDownLatch latch = new CountDownLatch(1);
command.toObservable().subscribe(new Observer<Boolean>() {
@Override
public void onCompleted() {
latch.countDown();
}
@Override
public void onError(Throwable e) {
latch.countDown();
e.printStackTrace();
}
@Override
public void onNext(Boolean args) {
subscribeThread.set(Thread.currentThread());
}
});
if (!latch.await(2000, TimeUnit.MILLISECONDS)) {
fail("timed out");
}
assertNotNull(commandThread.get());
assertNotNull(subscribeThread.get());
System.out.println("Command Thread: " + commandThread.get());
System.out.println("Subscribe Thread: " + subscribeThread.get());
assertTrue(commandThread.get().getName().startsWith("hystrix-"));
assertTrue(subscribeThread.get().getName().startsWith("hystrix-"));
}
/**
* Test a successful command execution.
*/
@Test
public void testCallbackThreadForSemaphoreIsolation() throws Exception {
final AtomicReference<Thread> commandThread = new AtomicReference<Thread>();
final AtomicReference<Thread> subscribeThread = new AtomicReference<Thread>();
TestHystrixCommand<Boolean> command = new TestHystrixCommand<Boolean>(TestHystrixCommand.testPropsBuilder()
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE))) {
@Override
protected Boolean run() {
commandThread.set(Thread.currentThread());
return true;
}
};
final CountDownLatch latch = new CountDownLatch(1);
command.toObservable().subscribe(new Observer<Boolean>() {
@Override
public void onCompleted() {
latch.countDown();
}
@Override
public void onError(Throwable e) {
latch.countDown();
e.printStackTrace();
}
@Override
public void onNext(Boolean args) {
subscribeThread.set(Thread.currentThread());
}
});
if (!latch.await(2000, TimeUnit.MILLISECONDS)) {
fail("timed out");
}
assertNotNull(commandThread.get());
assertNotNull(subscribeThread.get());
System.out.println("Command Thread: " + commandThread.get());
System.out.println("Subscribe Thread: " + subscribeThread.get());
String mainThreadName = Thread.currentThread().getName();
// semaphore should be on the calling thread
assertTrue(commandThread.get().getName().equals(mainThreadName));
assertTrue(subscribeThread.get().getName().equals(mainThreadName));
}
/**
* Tests that the circuit-breaker reports itself as "OPEN" if set as forced-open
*/
@Test
public void testCircuitBreakerReportsOpenIfForcedOpen() {
HystrixCommand<Boolean> cmd = new HystrixCommand<Boolean>(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("GROUP")).andCommandPropertiesDefaults(new HystrixCommandProperties.Setter().withCircuitBreakerForceOpen(true))) {
@Override
protected Boolean run() throws Exception {
return true;
}
@Override
protected Boolean getFallback() {
return false;
}
};
assertFalse(cmd.execute()); //fallback should fire
System.out.println("RESULT : " + cmd.getExecutionEvents());
assertTrue(cmd.isCircuitBreakerOpen());
}
/**
* Tests that the circuit-breaker reports itself as "CLOSED" if set as forced-closed
*/
@Test
public void testCircuitBreakerReportsClosedIfForcedClosed() {
HystrixCommand<Boolean> cmd = new HystrixCommand<Boolean>(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("GROUP")).andCommandPropertiesDefaults(
new HystrixCommandProperties.Setter().withCircuitBreakerForceOpen(false).withCircuitBreakerForceClosed(true))) {
@Override
protected Boolean run() throws Exception {
return true;
}
@Override
protected Boolean getFallback() {
return false;
}
};
assertTrue(cmd.execute());
System.out.println("RESULT : " + cmd.getExecutionEvents());
assertFalse(cmd.isCircuitBreakerOpen());
}
/**
* Test that the circuit-breaker is shared across HystrixCommand objects with the same CommandKey.
* <p>
* This will test HystrixCommand objects with a single circuit-breaker (as if each injected with same CommandKey)
* <p>
* Multiple HystrixCommand objects with the same dependency use the same circuit-breaker.
*/
@Test
public void testCircuitBreakerAcrossMultipleCommandsButSameCircuitBreaker() throws InterruptedException {
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("SharedCircuitBreaker");
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(key);
/* fail 3 times and then it should trip the circuit and stop executing */
// failure 1
TestHystrixCommand<Integer> attempt1 = getSharedCircuitBreakerCommand(key, ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.FallbackResult.SUCCESS, circuitBreaker);
System.out.println("COMMAND KEY (from cmd): " + attempt1.commandKey.name());
attempt1.execute();
Thread.sleep(100);
assertTrue(attempt1.isResponseFromFallback());
assertFalse(attempt1.isCircuitBreakerOpen());
assertFalse(attempt1.isResponseShortCircuited());
// failure 2 with a different command, same circuit breaker
TestHystrixCommand<Integer> attempt2 = getSharedCircuitBreakerCommand(key, ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.FallbackResult.SUCCESS, circuitBreaker);
attempt2.execute();
Thread.sleep(100);
assertTrue(attempt2.isFailedExecution());
assertTrue(attempt2.isResponseFromFallback());
assertFalse(attempt2.isCircuitBreakerOpen());
assertFalse(attempt2.isResponseShortCircuited());
// failure 3 of the Hystrix, 2nd for this particular HystrixCommand
TestHystrixCommand<Integer> attempt3 = getSharedCircuitBreakerCommand(key, ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.FallbackResult.SUCCESS, circuitBreaker);
attempt3.execute();
Thread.sleep(100);
assertTrue(attempt3.isFailedExecution());
assertTrue(attempt3.isResponseFromFallback());
assertFalse(attempt3.isResponseShortCircuited());
// it should now be 'open' and prevent further executions
// after having 3 failures on the Hystrix that these 2 different HystrixCommand objects are for
assertTrue(attempt3.isCircuitBreakerOpen());
// attempt 4
TestHystrixCommand<Integer> attempt4 = getSharedCircuitBreakerCommand(key, ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.FallbackResult.SUCCESS, circuitBreaker);
attempt4.execute();
Thread.sleep(100);
assertTrue(attempt4.isResponseFromFallback());
// this should now be true as the response will be short-circuited
assertTrue(attempt4.isResponseShortCircuited());
// this should remain open
assertTrue(attempt4.isCircuitBreakerOpen());
assertSaneHystrixRequestLog(4);
assertCommandExecutionEvents(attempt1, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_SUCCESS);
assertCommandExecutionEvents(attempt2, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_SUCCESS);
assertCommandExecutionEvents(attempt3, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_SUCCESS);
assertCommandExecutionEvents(attempt4, HystrixEventType.SHORT_CIRCUITED, HystrixEventType.FALLBACK_SUCCESS);
}
/**
* Test that the circuit-breaker being disabled doesn't wreak havoc.
*/
@Test
public void testExecutionSuccessWithCircuitBreakerDisabled() {
TestHystrixCommand<Integer> command = getCircuitBreakerDisabledCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS);
assertEquals(FlexibleTestHystrixCommand.EXECUTE_VALUE, command.execute());
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
// we'll still get metrics ... just not the circuit breaker opening/closing
assertCommandExecutionEvents(command, HystrixEventType.SUCCESS);
}
/**
* Test a command execution timeout where the command didn't implement getFallback.
*/
@Test
public void testExecutionTimeoutWithNoFallback() {
TestHystrixCommand<Integer> command = getLatentCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 200, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED, 50);
try {
command.execute();
fail("we shouldn't get here");
} catch (Exception e) {
// e.printStackTrace();
if (e instanceof HystrixRuntimeException) {
HystrixRuntimeException de = (HystrixRuntimeException) e;
assertNotNull(de.getFallbackException());
assertTrue(de.getFallbackException() instanceof UnsupportedOperationException);
assertNotNull(de.getImplementingClass());
assertNotNull(de.getCause());
assertTrue(de.getCause() instanceof TimeoutException);
} else {
fail("the exception should be HystrixRuntimeException");
}
}
// the time should be 50+ since we timeout at 50ms
assertTrue("Execution Time is: " + command.getExecutionTimeInMilliseconds(), command.getExecutionTimeInMilliseconds() >= 50);
assertTrue(command.isResponseTimedOut());
assertFalse(command.isResponseFromFallback());
assertFalse(command.isResponseRejected());
assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING);
assertNotNull(command.getExecutionException());
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test a command execution timeout where the command implemented getFallback.
*/
@Test
public void testExecutionTimeoutWithFallback() {
TestHystrixCommand<Integer> command = getLatentCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 200, AbstractTestHystrixCommand.FallbackResult.SUCCESS, 50);
assertEquals(FlexibleTestHystrixCommand.FALLBACK_VALUE, command.execute());
// the time should be 50+ since we timeout at 50ms
assertTrue("Execution Time is: " + command.getExecutionTimeInMilliseconds(), command.getExecutionTimeInMilliseconds() >= 50);
assertFalse(command.isCircuitBreakerOpen());
assertFalse(command.isResponseShortCircuited());
assertTrue(command.isResponseTimedOut());
assertTrue(command.isResponseFromFallback());
assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_SUCCESS);
assertNotNull(command.getExecutionException());
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test a command execution timeout where the command implemented getFallback but it fails.
*/
@Test
public void testExecutionTimeoutFallbackFailure() {
TestHystrixCommand<Integer> command = getLatentCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 200, AbstractTestHystrixCommand.FallbackResult.FAILURE, 50);
try {
command.execute();
fail("we shouldn't get here");
} catch (Exception e) {
if (e instanceof HystrixRuntimeException) {
HystrixRuntimeException de = (HystrixRuntimeException) e;
assertNotNull(de.getFallbackException());
assertFalse(de.getFallbackException() instanceof UnsupportedOperationException);
assertNotNull(de.getImplementingClass());
assertNotNull(de.getCause());
assertTrue(de.getCause() instanceof TimeoutException);
} else {
fail("the exception should be HystrixRuntimeException");
}
}
assertNotNull(command.getExecutionException());
// the time should be 50+ since we timeout at 50ms
assertTrue("Execution Time is: " + command.getExecutionTimeInMilliseconds(), command.getExecutionTimeInMilliseconds() >= 50);
assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_FAILURE);
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test that the command finishing AFTER a timeout (because thread continues in background) does not register a SUCCESS
*/
@Test
public void testCountersOnExecutionTimeout() throws Exception {
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 200, AbstractTestHystrixCommand.FallbackResult.SUCCESS, 50);
command.execute();
/* wait long enough for the command to have finished */
Thread.sleep(200);
/* response should still be the same as 'testCircuitBreakerOnExecutionTimeout' */
assertTrue(command.isResponseFromFallback());
assertFalse(command.isCircuitBreakerOpen());
assertFalse(command.isResponseShortCircuited());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isResponseTimedOut());
assertFalse(command.isSuccessfulExecution());
assertNotNull(command.getExecutionException());
assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_SUCCESS);
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test a queued command execution timeout where the command didn't implement getFallback.
* <p>
* We specifically want to protect against developers queuing commands and using queue().get() without a timeout (such as queue().get(3000, TimeUnit.Milliseconds)) and ending up blocking
* indefinitely by skipping the timeout protection of the execute() command.
*/
@Test
public void testQueuedExecutionTimeoutWithNoFallback() {
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 200, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED, 50);
try {
command.queue().get();
fail("we shouldn't get here");
} catch (Exception e) {
e.printStackTrace();
if (e instanceof ExecutionException && e.getCause() instanceof HystrixRuntimeException) {
HystrixRuntimeException de = (HystrixRuntimeException) e.getCause();
assertNotNull(de.getFallbackException());
assertTrue(de.getFallbackException() instanceof UnsupportedOperationException);
assertNotNull(de.getImplementingClass());
assertNotNull(de.getCause());
assertTrue(de.getCause() instanceof TimeoutException);
} else {
fail("the exception should be ExecutionException with cause as HystrixRuntimeException");
}
}
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isResponseTimedOut());
assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING);
assertNotNull(command.getExecutionException());
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test a queued command execution timeout where the command implemented getFallback.
* <p>
* We specifically want to protect against developers queuing commands and using queue().get() without a timeout (such as queue().get(3000, TimeUnit.Milliseconds)) and ending up blocking
* indefinitely by skipping the timeout protection of the execute() command.
*/
@Test
public void testQueuedExecutionTimeoutWithFallback() throws Exception {
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 200, AbstractTestHystrixCommand.FallbackResult.SUCCESS, 50);
assertEquals(FlexibleTestHystrixCommand.FALLBACK_VALUE, command.queue().get());
assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_SUCCESS);
assertNotNull(command.getExecutionException());
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test a queued command execution timeout where the command implemented getFallback but it fails.
* <p>
* We specifically want to protect against developers queuing commands and using queue().get() without a timeout (such as queue().get(3000, TimeUnit.Milliseconds)) and ending up blocking
* indefinitely by skipping the timeout protection of the execute() command.
*/
@Test
public void testQueuedExecutionTimeoutFallbackFailure() {
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 200, AbstractTestHystrixCommand.FallbackResult.FAILURE, 50);
try {
command.queue().get();
fail("we shouldn't get here");
} catch (Exception e) {
if (e instanceof ExecutionException && e.getCause() instanceof HystrixRuntimeException) {
HystrixRuntimeException de = (HystrixRuntimeException) e.getCause();
assertNotNull(de.getFallbackException());
assertFalse(de.getFallbackException() instanceof UnsupportedOperationException);
assertNotNull(de.getImplementingClass());
assertNotNull(de.getCause());
assertTrue(de.getCause() instanceof TimeoutException);
} else {
fail("the exception should be ExecutionException with cause as HystrixRuntimeException");
}
}
assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_FAILURE);
assertNotNull(command.getExecutionException());
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test a queued command execution timeout where the command didn't implement getFallback.
* <p>
* We specifically want to protect against developers queuing commands and using queue().get() without a timeout (such as queue().get(3000, TimeUnit.Milliseconds)) and ending up blocking
* indefinitely by skipping the timeout protection of the execute() command.
*/
@Test
public void testObservedExecutionTimeoutWithNoFallback() {
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 200, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED, 50);
try {
command.observe().toBlocking().single();
fail("we shouldn't get here");
} catch (Exception e) {
e.printStackTrace();
if (e instanceof HystrixRuntimeException) {
HystrixRuntimeException de = (HystrixRuntimeException) e;
assertNotNull(de.getFallbackException());
assertTrue(de.getFallbackException() instanceof UnsupportedOperationException);
assertNotNull(de.getImplementingClass());
assertNotNull(de.getCause());
assertTrue(de.getCause() instanceof TimeoutException);
} else {
fail("the exception should be ExecutionException with cause as HystrixRuntimeException");
}
}
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isResponseTimedOut());
assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING);
assertNotNull(command.getExecutionException());
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test a queued command execution timeout where the command implemented getFallback.
* <p>
* We specifically want to protect against developers queuing commands and using queue().get() without a timeout (such as queue().get(3000, TimeUnit.Milliseconds)) and ending up blocking
* indefinitely by skipping the timeout protection of the execute() command.
*/
@Test
public void testObservedExecutionTimeoutWithFallback() throws Exception {
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 200, AbstractTestHystrixCommand.FallbackResult.SUCCESS, 50);
assertEquals(FlexibleTestHystrixCommand.FALLBACK_VALUE, command.observe().toBlocking().single());
assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_SUCCESS);
assertNotNull(command.getExecutionException());
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test a queued command execution timeout where the command implemented getFallback but it fails.
* <p>
* We specifically want to protect against developers queuing commands and using queue().get() without a timeout (such as queue().get(3000, TimeUnit.Milliseconds)) and ending up blocking
* indefinitely by skipping the timeout protection of the execute() command.
*/
@Test
public void testObservedExecutionTimeoutFallbackFailure() {
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 200, AbstractTestHystrixCommand.FallbackResult.FAILURE, 50);
try {
command.observe().toBlocking().single();
fail("we shouldn't get here");
} catch (Exception e) {
if (e instanceof HystrixRuntimeException) {
HystrixRuntimeException de = (HystrixRuntimeException) e;
assertNotNull(de.getFallbackException());
assertFalse(de.getFallbackException() instanceof UnsupportedOperationException);
assertNotNull(de.getImplementingClass());
assertNotNull(de.getCause());
assertTrue(de.getCause() instanceof TimeoutException);
} else {
fail("the exception should be ExecutionException with cause as HystrixRuntimeException");
}
}
assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_FAILURE);
assertNotNull(command.getExecutionException());
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
@Test
public void testShortCircuitFallbackCounter() {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker().setForceShortCircuit(true);
KnownFailureTestCommandWithFallback command1 = new KnownFailureTestCommandWithFallback(circuitBreaker);
command1.execute();
KnownFailureTestCommandWithFallback command2 = new KnownFailureTestCommandWithFallback(circuitBreaker);
command2.execute();
// will be -1 because it never attempted execution
assertTrue(command1.getExecutionTimeInMilliseconds() == -1);
assertTrue(command1.isResponseShortCircuited());
assertFalse(command1.isResponseTimedOut());
assertNotNull(command1.getExecutionException());
assertCommandExecutionEvents(command1, HystrixEventType.SHORT_CIRCUITED, HystrixEventType.FALLBACK_SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.SHORT_CIRCUITED, HystrixEventType.FALLBACK_SUCCESS);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(2);
}
/**
* Test when a command fails to get queued up in the threadpool where the command didn't implement getFallback.
* <p>
* We specifically want to protect against developers getting random thread exceptions and instead just correctly receiving HystrixRuntimeException when no fallback exists.
*/
@Test
public void testRejectedThreadWithNoFallback() throws Exception {
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("Rejection-NoFallback");
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
SingleThreadedPoolWithQueue pool = new SingleThreadedPoolWithQueue(1);
// fill up the queue
pool.queue.add(new Runnable() {
@Override
public void run() {
System.out.println("**** queue filler1 ****");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Future<Boolean> f = null;
TestCommandRejection command1 = null;
TestCommandRejection command2 = null;
try {
command1 = new TestCommandRejection(key, circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_NOT_IMPLEMENTED);
f = command1.queue();
command2 = new TestCommandRejection(key, circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_NOT_IMPLEMENTED);
command2.queue();
fail("we shouldn't get here");
} catch (Exception e) {
e.printStackTrace();
System.out.println("command.getExecutionTimeInMilliseconds(): " + command2.getExecutionTimeInMilliseconds());
// will be -1 because it never attempted execution
assertTrue(command2.isResponseRejected());
assertFalse(command2.isResponseShortCircuited());
assertFalse(command2.isResponseTimedOut());
assertNotNull(command2.getExecutionException());
if (e instanceof HystrixRuntimeException && e.getCause() instanceof RejectedExecutionException) {
HystrixRuntimeException de = (HystrixRuntimeException) e;
assertNotNull(de.getFallbackException());
assertTrue(de.getFallbackException() instanceof UnsupportedOperationException);
assertNotNull(de.getImplementingClass());
assertNotNull(de.getCause());
assertTrue(de.getCause() instanceof RejectedExecutionException);
} else {
fail("the exception should be HystrixRuntimeException with cause as RejectedExecutionException");
}
}
f.get();
assertCommandExecutionEvents(command1, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.THREAD_POOL_REJECTED, HystrixEventType.FALLBACK_MISSING);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(2);
}
/**
* Test when a command fails to get queued up in the threadpool where the command implemented getFallback.
* <p>
* We specifically want to protect against developers getting random thread exceptions and instead just correctly receives a fallback.
*/
@Test
public void testRejectedThreadWithFallback() throws InterruptedException {
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("Rejection-Fallback");
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
SingleThreadedPoolWithQueue pool = new SingleThreadedPoolWithQueue(1);
//command 1 will execute in threadpool (passing through the queue)
//command 2 will execute after spending time in the queue (after command1 completes)
//command 3 will get rejected, since it finds pool and queue both full
TestCommandRejection command1 = new TestCommandRejection(key, circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_SUCCESS);
TestCommandRejection command2 = new TestCommandRejection(key, circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_SUCCESS);
TestCommandRejection command3 = new TestCommandRejection(key, circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_SUCCESS);
Observable<Boolean> result1 = command1.observe();
Observable<Boolean> result2 = command2.observe();
Thread.sleep(100);
//command3 should find queue filled, and get rejected
assertFalse(command3.execute());
assertTrue(command3.isResponseRejected());
assertFalse(command1.isResponseRejected());
assertFalse(command2.isResponseRejected());
assertTrue(command3.isResponseFromFallback());
assertNotNull(command3.getExecutionException());
assertCommandExecutionEvents(command3, HystrixEventType.THREAD_POOL_REJECTED, HystrixEventType.FALLBACK_SUCCESS);
Observable.merge(result1, result2).toList().toBlocking().single(); //await the 2 latent commands
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertSaneHystrixRequestLog(3);
}
/**
* Test when a command fails to get queued up in the threadpool where the command implemented getFallback but it fails.
* <p>
* We specifically want to protect against developers getting random thread exceptions and instead just correctly receives an HystrixRuntimeException.
*/
@Test
public void testRejectedThreadWithFallbackFailure() throws ExecutionException, InterruptedException {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
SingleThreadedPoolWithQueue pool = new SingleThreadedPoolWithQueue(1);
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("Rejection-A");
TestCommandRejection command1 = new TestCommandRejection(key, circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_FAILURE); //this should pass through the queue and sit in the pool
TestCommandRejection command2 = new TestCommandRejection(key, circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_SUCCESS); //this should sit in the queue
TestCommandRejection command3 = new TestCommandRejection(key, circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_FAILURE); //this should observe full queue and get rejected
Future<Boolean> f1 = null;
Future<Boolean> f2 = null;
try {
f1 = command1.queue();
f2 = command2.queue();
assertEquals(false, command3.queue().get()); //should get thread-pool rejected
fail("we shouldn't get here");
} catch (Exception e) {
e.printStackTrace();
if (e instanceof HystrixRuntimeException && e.getCause() instanceof RejectedExecutionException) {
HystrixRuntimeException de = (HystrixRuntimeException) e;
assertNotNull(de.getFallbackException());
assertFalse(de.getFallbackException() instanceof UnsupportedOperationException);
assertNotNull(de.getImplementingClass());
assertNotNull(de.getCause());
assertTrue(de.getCause() instanceof RejectedExecutionException);
} else {
fail("the exception should be HystrixRuntimeException with cause as RejectedExecutionException");
}
}
assertCommandExecutionEvents(command1); //still in-flight, no events yet
assertCommandExecutionEvents(command2); //still in-flight, no events yet
assertCommandExecutionEvents(command3, HystrixEventType.THREAD_POOL_REJECTED, HystrixEventType.FALLBACK_FAILURE);
int numInFlight = circuitBreaker.metrics.getCurrentConcurrentExecutionCount();
assertTrue("Expected at most 1 in flight but got : " + numInFlight, numInFlight <= 1); //pool-filler still going
//This is a case where we knowingly walk away from executing Hystrix threads. They should have an in-flight status ("Executed"). You should avoid this in a production environment
HystrixRequestLog requestLog = HystrixRequestLog.getCurrentRequest();
assertEquals(3, requestLog.getAllExecutedCommands().size());
assertTrue(requestLog.getExecutedCommandsAsString().contains("Executed"));
//block on the outstanding work, so we don't inadvertently affect any other tests
long startTime = System.currentTimeMillis();
f1.get();
f2.get();
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
System.out.println("Time blocked : " + (System.currentTimeMillis() - startTime));
}
/**
* Test that we can reject a thread using isQueueSpaceAvailable() instead of just when the pool rejects.
* <p>
* For example, we have queue size set to 100 but want to reject when we hit 10.
* <p>
* This allows us to use FastProperties to control our rejection point whereas we can't resize a queue after it's created.
*/
@Test
public void testRejectedThreadUsingQueueSize() {
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("Rejection-B");
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
SingleThreadedPoolWithQueue pool = new SingleThreadedPoolWithQueue(10, 1);
// put 1 item in the queue
// the thread pool won't pick it up because we're bypassing the pool and adding to the queue directly so this will keep the queue full
pool.queue.add(new Runnable() {
@Override
public void run() {
System.out.println("**** queue filler1 ****");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
TestCommandRejection command = new TestCommandRejection(key, circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_NOT_IMPLEMENTED);
try {
// this should fail as we already have 1 in the queue
command.queue();
fail("we shouldn't get here");
} catch (Exception e) {
e.printStackTrace();
assertTrue(command.isResponseRejected());
assertFalse(command.isResponseShortCircuited());
assertFalse(command.isResponseTimedOut());
assertNotNull(command.getExecutionException());
if (e instanceof HystrixRuntimeException && e.getCause() instanceof RejectedExecutionException) {
HystrixRuntimeException de = (HystrixRuntimeException) e;
assertNotNull(de.getFallbackException());
assertTrue(de.getFallbackException() instanceof UnsupportedOperationException);
assertNotNull(de.getImplementingClass());
assertNotNull(de.getCause());
assertTrue(de.getCause() instanceof RejectedExecutionException);
} else {
fail("the exception should be HystrixRuntimeException with cause as RejectedExecutionException");
}
}
assertCommandExecutionEvents(command, HystrixEventType.THREAD_POOL_REJECTED, HystrixEventType.FALLBACK_MISSING);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
@Test
public void testDisabledTimeoutWorks() {
CommandWithDisabledTimeout cmd = new CommandWithDisabledTimeout(100, 900);
boolean result = cmd.execute();
assertEquals(true, result);
assertFalse(cmd.isResponseTimedOut());
assertNull(cmd.getExecutionException());
System.out.println("CMD : " + cmd.currentRequestLog.getExecutedCommandsAsString());
assertTrue(cmd.executionResult.getExecutionLatency() >= 900);
assertCommandExecutionEvents(cmd, HystrixEventType.SUCCESS);
}
@Test
public void testFallbackSemaphore() throws Exception {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
// single thread should work
TestSemaphoreCommandWithSlowFallback command1 = new TestSemaphoreCommandWithSlowFallback(circuitBreaker, 1, 200);
boolean result = command1.queue().get();
assertTrue(result);
// 2 threads, the second should be rejected by the fallback semaphore
boolean exceptionReceived = false;
Future<Boolean> result2 = null;
TestSemaphoreCommandWithSlowFallback command2 = null;
TestSemaphoreCommandWithSlowFallback command3 = null;
try {
System.out.println("c2 start: " + System.currentTimeMillis());
command2 = new TestSemaphoreCommandWithSlowFallback(circuitBreaker, 1, 800);
result2 = command2.queue();
System.out.println("c2 after queue: " + System.currentTimeMillis());
// make sure that thread gets a chance to run before queuing the next one
Thread.sleep(50);
System.out.println("c3 start: " + System.currentTimeMillis());
command3 = new TestSemaphoreCommandWithSlowFallback(circuitBreaker, 1, 200);
Future<Boolean> result3 = command3.queue();
System.out.println("c3 after queue: " + System.currentTimeMillis());
result3.get();
} catch (Exception e) {
e.printStackTrace();
exceptionReceived = true;
}
assertTrue(result2.get());
if (!exceptionReceived) {
fail("We expected an exception on the 2nd get");
}
assertCommandExecutionEvents(command1, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_SUCCESS);
assertCommandExecutionEvents(command3, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_REJECTION);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(3);
}
@Test
public void testExecutionSemaphoreWithQueue() throws Exception {
final TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
// single thread should work
TestSemaphoreCommand command1 = new TestSemaphoreCommand(circuitBreaker, 1, 200, TestSemaphoreCommand.RESULT_SUCCESS, TestSemaphoreCommand.FALLBACK_NOT_IMPLEMENTED);
boolean result = command1.queue().get();
assertTrue(result);
final AtomicBoolean exceptionReceived = new AtomicBoolean();
final TryableSemaphore semaphore =
new TryableSemaphoreActual(HystrixProperty.Factory.asProperty(1));
final TestSemaphoreCommand command2 = new TestSemaphoreCommand(circuitBreaker, semaphore, 200, TestSemaphoreCommand.RESULT_SUCCESS, TestSemaphoreCommand.FALLBACK_NOT_IMPLEMENTED);
Runnable r2 = new HystrixContextRunnable(HystrixPlugins.getInstance().getConcurrencyStrategy(), new Runnable() {
@Override
public void run() {
try {
command2.queue().get();
} catch (Exception e) {
e.printStackTrace();
exceptionReceived.set(true);
}
}
});
final TestSemaphoreCommand command3 = new TestSemaphoreCommand(circuitBreaker, semaphore, 200, TestSemaphoreCommand.RESULT_SUCCESS, TestSemaphoreCommand.FALLBACK_NOT_IMPLEMENTED);
Runnable r3 = new HystrixContextRunnable(HystrixPlugins.getInstance().getConcurrencyStrategy(), new Runnable() {
@Override
public void run() {
try {
command3.queue().get();
} catch (Exception e) {
e.printStackTrace();
exceptionReceived.set(true);
}
}
});
// 2 threads, the second should be rejected by the semaphore
Thread t2 = new Thread(r2);
Thread t3 = new Thread(r3);
t2.start();
// make sure that t2 gets a chance to run before queuing the next one
Thread.sleep(50);
t3.start();
t2.join();
t3.join();
if (!exceptionReceived.get()) {
fail("We expected an exception on the 2nd get");
}
assertCommandExecutionEvents(command1, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command3, HystrixEventType.SEMAPHORE_REJECTED, HystrixEventType.FALLBACK_MISSING);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(3);
}
@Test
public void testExecutionSemaphoreWithExecution() throws Exception {
final TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
// single thread should work
TestSemaphoreCommand command1 = new TestSemaphoreCommand(circuitBreaker, 1, 200, TestSemaphoreCommand.RESULT_SUCCESS, TestSemaphoreCommand.FALLBACK_NOT_IMPLEMENTED);
boolean result = command1.execute();
assertFalse(command1.isExecutedInThread());
assertTrue(result);
final ArrayBlockingQueue<Boolean> results = new ArrayBlockingQueue<Boolean>(2);
final AtomicBoolean exceptionReceived = new AtomicBoolean();
final TryableSemaphore semaphore =
new TryableSemaphoreActual(HystrixProperty.Factory.asProperty(1));
final TestSemaphoreCommand command2 = new TestSemaphoreCommand(circuitBreaker, semaphore, 200, TestSemaphoreCommand.RESULT_SUCCESS, TestSemaphoreCommand.FALLBACK_NOT_IMPLEMENTED);
Runnable r2 = new HystrixContextRunnable(HystrixPlugins.getInstance().getConcurrencyStrategy(), new Runnable() {
@Override
public void run() {
try {
results.add(command2.execute());
} catch (Exception e) {
e.printStackTrace();
exceptionReceived.set(true);
}
}
});
final TestSemaphoreCommand command3 = new TestSemaphoreCommand(circuitBreaker, semaphore, 200, TestSemaphoreCommand.RESULT_SUCCESS, TestSemaphoreCommand.FALLBACK_NOT_IMPLEMENTED);
Runnable r3 = new HystrixContextRunnable(HystrixPlugins.getInstance().getConcurrencyStrategy(), new Runnable() {
@Override
public void run() {
try {
results.add(command3.execute());
} catch (Exception e) {
e.printStackTrace();
exceptionReceived.set(true);
}
}
});
// 2 threads, the second should be rejected by the semaphore
Thread t2 = new Thread(r2);
Thread t3 = new Thread(r3);
t2.start();
// make sure that t2 gets a chance to run before queuing the next one
Thread.sleep(50);
t3.start();
t2.join();
t3.join();
if (!exceptionReceived.get()) {
fail("We expected an exception on the 2nd get");
}
// only 1 value is expected as the other should have thrown an exception
assertEquals(1, results.size());
// should contain only a true result
assertTrue(results.contains(Boolean.TRUE));
assertFalse(results.contains(Boolean.FALSE));
assertCommandExecutionEvents(command1, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command3, HystrixEventType.SEMAPHORE_REJECTED, HystrixEventType.FALLBACK_MISSING);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(3);
}
@Test
public void testRejectedExecutionSemaphoreWithFallbackViaExecute() throws Exception {
final TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
final ArrayBlockingQueue<Boolean> results = new ArrayBlockingQueue<Boolean>(2);
final AtomicBoolean exceptionReceived = new AtomicBoolean();
final TestSemaphoreCommandWithFallback command1 = new TestSemaphoreCommandWithFallback(circuitBreaker, 1, 200, false);
Runnable r1 = new HystrixContextRunnable(HystrixPlugins.getInstance().getConcurrencyStrategy(), new Runnable() {
@Override
public void run() {
try {
results.add(command1.execute());
} catch (Exception e) {
e.printStackTrace();
exceptionReceived.set(true);
}
}
});
final TestSemaphoreCommandWithFallback command2 = new TestSemaphoreCommandWithFallback(circuitBreaker, 1, 200, false);
Runnable r2 = new HystrixContextRunnable(HystrixPlugins.getInstance().getConcurrencyStrategy(), new Runnable() {
@Override
public void run() {
try {
results.add(command2.execute());
} catch (Exception e) {
e.printStackTrace();
exceptionReceived.set(true);
}
}
});
// 2 threads, the second should be rejected by the semaphore and return fallback
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
// make sure that t2 gets a chance to run before queuing the next one
Thread.sleep(50);
t2.start();
t1.join();
t2.join();
if (exceptionReceived.get()) {
fail("We should have received a fallback response");
}
// both threads should have returned values
assertEquals(2, results.size());
// should contain both a true and false result
assertTrue(results.contains(Boolean.TRUE));
assertTrue(results.contains(Boolean.FALSE));
assertCommandExecutionEvents(command1, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.SEMAPHORE_REJECTED, HystrixEventType.FALLBACK_SUCCESS);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(2);
}
@Test
public void testRejectedExecutionSemaphoreWithFallbackViaObserve() throws Exception {
final TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
final ArrayBlockingQueue<Observable<Boolean>> results = new ArrayBlockingQueue<Observable<Boolean>>(2);
final AtomicBoolean exceptionReceived = new AtomicBoolean();
final TestSemaphoreCommandWithFallback command1 = new TestSemaphoreCommandWithFallback(circuitBreaker, 1, 200, false);
Runnable r1 = new HystrixContextRunnable(HystrixPlugins.getInstance().getConcurrencyStrategy(), new Runnable() {
@Override
public void run() {
try {
results.add(command1.observe());
} catch (Exception e) {
e.printStackTrace();
exceptionReceived.set(true);
}
}
});
final TestSemaphoreCommandWithFallback command2 = new TestSemaphoreCommandWithFallback(circuitBreaker, 1, 200, false);
Runnable r2 = new HystrixContextRunnable(HystrixPlugins.getInstance().getConcurrencyStrategy(), new Runnable() {
@Override
public void run() {
try {
results.add(command2.observe());
} catch (Exception e) {
e.printStackTrace();
exceptionReceived.set(true);
}
}
});
// 2 threads, the second should be rejected by the semaphore and return fallback
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
// make sure that t2 gets a chance to run before queuing the next one
Thread.sleep(50);
t2.start();
t1.join();
t2.join();
if (exceptionReceived.get()) {
fail("We should have received a fallback response");
}
final List<Boolean> blockingList = Observable.merge(results).toList().toBlocking().single();
// both threads should have returned values
assertEquals(2, blockingList.size());
// should contain both a true and false result
assertTrue(blockingList.contains(Boolean.TRUE));
assertTrue(blockingList.contains(Boolean.FALSE));
assertCommandExecutionEvents(command1, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.SEMAPHORE_REJECTED, HystrixEventType.FALLBACK_SUCCESS);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(2);
}
/**
* Tests that semaphores are counted separately for commands with unique keys
*/
@Test
public void testSemaphorePermitsInUse() throws Exception {
final TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
// this semaphore will be shared across multiple command instances
final TryableSemaphoreActual sharedSemaphore =
new TryableSemaphoreActual(HystrixProperty.Factory.asProperty(3));
// used to wait until all commands have started
final CountDownLatch startLatch = new CountDownLatch((sharedSemaphore.numberOfPermits.get() * 2) + 1);
// used to signal that all command can finish
final CountDownLatch sharedLatch = new CountDownLatch(1);
// tracks failures to obtain semaphores
final AtomicInteger failureCount = new AtomicInteger();
final Runnable sharedSemaphoreRunnable = new HystrixContextRunnable(HystrixPlugins.getInstance().getConcurrencyStrategy(), new Runnable() {
public void run() {
try {
new LatchedSemaphoreCommand("Command-Shared", circuitBreaker, sharedSemaphore, startLatch, sharedLatch).execute();
} catch (Exception e) {
startLatch.countDown();
e.printStackTrace();
failureCount.incrementAndGet();
}
}
});
// creates group of threads each using command sharing a single semaphore
// I create extra threads and commands so that I can verify that some of them fail to obtain a semaphore
final int sharedThreadCount = sharedSemaphore.numberOfPermits.get() * 2;
final Thread[] sharedSemaphoreThreads = new Thread[sharedThreadCount];
for (int i = 0; i < sharedThreadCount; i++) {
sharedSemaphoreThreads[i] = new Thread(sharedSemaphoreRunnable);
}
// creates thread using isolated semaphore
final TryableSemaphoreActual isolatedSemaphore =
new TryableSemaphoreActual(HystrixProperty.Factory.asProperty(1));
final CountDownLatch isolatedLatch = new CountDownLatch(1);
final Thread isolatedThread = new Thread(new HystrixContextRunnable(HystrixPlugins.getInstance().getConcurrencyStrategy(), new Runnable() {
public void run() {
try {
new LatchedSemaphoreCommand("Command-Isolated", circuitBreaker, isolatedSemaphore, startLatch, isolatedLatch).execute();
} catch (Exception e) {
startLatch.countDown();
e.printStackTrace();
failureCount.incrementAndGet();
}
}
}));
// verifies no permits in use before starting threads
assertEquals("before threads start, shared semaphore should be unused", 0, sharedSemaphore.getNumberOfPermitsUsed());
assertEquals("before threads start, isolated semaphore should be unused", 0, isolatedSemaphore.getNumberOfPermitsUsed());
for (int i = 0; i < sharedThreadCount; i++) {
sharedSemaphoreThreads[i].start();
}
isolatedThread.start();
// waits until all commands have started
startLatch.await(1000, TimeUnit.MILLISECONDS);
// verifies that all semaphores are in use
assertEquals("immediately after command start, all shared semaphores should be in-use",
sharedSemaphore.numberOfPermits.get().longValue(), sharedSemaphore.getNumberOfPermitsUsed());
assertEquals("immediately after command start, isolated semaphore should be in-use",
isolatedSemaphore.numberOfPermits.get().longValue(), isolatedSemaphore.getNumberOfPermitsUsed());
// signals commands to finish
sharedLatch.countDown();
isolatedLatch.countDown();
for (int i = 0; i < sharedThreadCount; i++) {
sharedSemaphoreThreads[i].join();
}
isolatedThread.join();
// verifies no permits in use after finishing threads
System.out.println("REQLOG : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertEquals("after all threads have finished, no shared semaphores should be in-use", 0, sharedSemaphore.getNumberOfPermitsUsed());
assertEquals("after all threads have finished, isolated semaphore not in-use", 0, isolatedSemaphore.getNumberOfPermitsUsed());
// verifies that some executions failed
assertEquals("expected some of shared semaphore commands to get rejected", sharedSemaphore.numberOfPermits.get().longValue(), failureCount.get());
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
}
/**
* Test that HystrixOwner can be passed in dynamically.
*/
@Test
public void testDynamicOwner() {
TestHystrixCommand<Boolean> command = new DynamicOwnerTestCommand(InspectableBuilder.CommandGroupForUnitTest.OWNER_ONE);
assertEquals(true, command.execute());
assertCommandExecutionEvents(command, HystrixEventType.SUCCESS);
}
/**
* Test a successful command execution.
*/
@Test(expected = IllegalStateException.class)
public void testDynamicOwnerFails() {
TestHystrixCommand<Boolean> command = new DynamicOwnerTestCommand(null);
assertEquals(true, command.execute());
}
/**
* Test that HystrixCommandKey can be passed in dynamically.
*/
@Test
public void testDynamicKey() throws Exception {
DynamicOwnerAndKeyTestCommand command1 = new DynamicOwnerAndKeyTestCommand(InspectableBuilder.CommandGroupForUnitTest.OWNER_ONE, InspectableBuilder.CommandKeyForUnitTest.KEY_ONE);
assertEquals(true, command1.execute());
DynamicOwnerAndKeyTestCommand command2 = new DynamicOwnerAndKeyTestCommand(InspectableBuilder.CommandGroupForUnitTest.OWNER_ONE, InspectableBuilder.CommandKeyForUnitTest.KEY_TWO);
assertEquals(true, command2.execute());
// 2 different circuit breakers should be created
assertNotSame(command1.getCircuitBreaker(), command2.getCircuitBreaker());
}
/**
* Test Request scoped caching of commands so that a 2nd duplicate call doesn't execute but returns the previous Future
*/
@Test
public void testRequestCache1() throws Exception {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
SuccessfulCacheableCommand<String> command1 = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "A");
SuccessfulCacheableCommand<String> command2 = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "A");
assertTrue(command1.isCommandRunningInThread());
Future<String> f1 = command1.queue();
Future<String> f2 = command2.queue();
assertEquals("A", f1.get());
assertEquals("A", f2.get());
assertTrue(command1.executed);
// the second one should not have executed as it should have received the cached value instead
assertFalse(command2.executed);
assertTrue(command1.getExecutionTimeInMilliseconds() > -1);
assertFalse(command1.isResponseFromCache());
assertTrue(command2.isResponseFromCache());
assertCommandExecutionEvents(command1, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.SUCCESS, HystrixEventType.RESPONSE_FROM_CACHE);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(2);
}
/**
* Test Request scoped caching doesn't prevent different ones from executing
*/
@Test
public void testRequestCache2() throws Exception {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
SuccessfulCacheableCommand<String> command1 = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "A");
SuccessfulCacheableCommand<String> command2 = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "B");
assertTrue(command1.isCommandRunningInThread());
Future<String> f1 = command1.queue();
Future<String> f2 = command2.queue();
assertEquals("A", f1.get());
assertEquals("B", f2.get());
assertTrue(command1.executed);
// both should execute as they are different
assertTrue(command2.executed);
assertTrue(command2.getExecutionTimeInMilliseconds() > -1);
assertFalse(command2.isResponseFromCache());
assertCommandExecutionEvents(command1, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.SUCCESS);
assertNull(command1.getExecutionException());
assertFalse(command2.isResponseFromCache());
assertNull(command2.getExecutionException());
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(2);
}
/**
* Test Request scoped caching with a mixture of commands
*/
@Test
public void testRequestCache3() throws Exception {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
SuccessfulCacheableCommand<String> command1 = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "A");
SuccessfulCacheableCommand<String> command2 = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "B");
SuccessfulCacheableCommand<String> command3 = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "A");
assertTrue(command1.isCommandRunningInThread());
Future<String> f1 = command1.queue();
Future<String> f2 = command2.queue();
Future<String> f3 = command3.queue();
assertEquals("A", f1.get());
assertEquals("B", f2.get());
assertEquals("A", f3.get());
assertTrue(command1.executed);
// both should execute as they are different
assertTrue(command2.executed);
// but the 3rd should come from cache
assertFalse(command3.executed);
assertTrue(command3.isResponseFromCache());
assertCommandExecutionEvents(command1, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command3, HystrixEventType.SUCCESS, HystrixEventType.RESPONSE_FROM_CACHE);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertSaneHystrixRequestLog(3);
}
/**
* Test Request scoped caching of commands so that a 2nd duplicate call doesn't execute but returns the previous Future
*/
@Test
public void testRequestCacheWithSlowExecution() throws Exception {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
SlowCacheableCommand command1 = new SlowCacheableCommand(circuitBreaker, "A", 200);
SlowCacheableCommand command2 = new SlowCacheableCommand(circuitBreaker, "A", 100);
SlowCacheableCommand command3 = new SlowCacheableCommand(circuitBreaker, "A", 100);
SlowCacheableCommand command4 = new SlowCacheableCommand(circuitBreaker, "A", 100);
Future<String> f1 = command1.queue();
Future<String> f2 = command2.queue();
Future<String> f3 = command3.queue();
Future<String> f4 = command4.queue();
assertEquals("A", f2.get());
assertEquals("A", f3.get());
assertEquals("A", f4.get());
assertEquals("A", f1.get());
assertTrue(command1.executed);
// the second one should not have executed as it should have received the cached value instead
assertFalse(command2.executed);
assertFalse(command3.executed);
assertFalse(command4.executed);
assertTrue(command1.getExecutionTimeInMilliseconds() > -1);
assertFalse(command1.isResponseFromCache());
assertTrue(command2.getExecutionTimeInMilliseconds() == -1);
assertTrue(command2.isResponseFromCache());
assertTrue(command3.isResponseFromCache());
assertTrue(command3.getExecutionTimeInMilliseconds() == -1);
assertTrue(command4.isResponseFromCache());
assertTrue(command4.getExecutionTimeInMilliseconds() == -1);
assertCommandExecutionEvents(command1, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.SUCCESS, HystrixEventType.RESPONSE_FROM_CACHE);
assertCommandExecutionEvents(command3, HystrixEventType.SUCCESS, HystrixEventType.RESPONSE_FROM_CACHE);
assertCommandExecutionEvents(command4, HystrixEventType.SUCCESS, HystrixEventType.RESPONSE_FROM_CACHE);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(4);
System.out.println("HystrixRequestLog: " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
}
/**
* Test Request scoped caching with a mixture of commands
*/
@Test
public void testNoRequestCache3() throws Exception {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
SuccessfulCacheableCommand<String> command1 = new SuccessfulCacheableCommand<String>(circuitBreaker, false, "A");
SuccessfulCacheableCommand<String> command2 = new SuccessfulCacheableCommand<String>(circuitBreaker, false, "B");
SuccessfulCacheableCommand<String> command3 = new SuccessfulCacheableCommand<String>(circuitBreaker, false, "A");
assertTrue(command1.isCommandRunningInThread());
Future<String> f1 = command1.queue();
Future<String> f2 = command2.queue();
Future<String> f3 = command3.queue();
assertEquals("A", f1.get());
assertEquals("B", f2.get());
assertEquals("A", f3.get());
assertTrue(command1.executed);
// both should execute as they are different
assertTrue(command2.executed);
// this should also execute since we disabled the cache
assertTrue(command3.executed);
assertCommandExecutionEvents(command1, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command3, HystrixEventType.SUCCESS);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(3);
}
/**
* Test Request scoped caching with a mixture of commands
*/
@Test
public void testRequestCacheViaQueueSemaphore1() throws Exception {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
SuccessfulCacheableCommandViaSemaphore command1 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, true, "A");
SuccessfulCacheableCommandViaSemaphore command2 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, true, "B");
SuccessfulCacheableCommandViaSemaphore command3 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, true, "A");
assertFalse(command1.isCommandRunningInThread());
Future<String> f1 = command1.queue();
Future<String> f2 = command2.queue();
Future<String> f3 = command3.queue();
assertEquals("A", f1.get());
assertEquals("B", f2.get());
assertEquals("A", f3.get());
assertTrue(command1.executed);
// both should execute as they are different
assertTrue(command2.executed);
// but the 3rd should come from cache
assertFalse(command3.executed);
assertTrue(command3.isResponseFromCache());
assertTrue(command3.getExecutionTimeInMilliseconds() == -1);
assertCommandExecutionEvents(command1, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command3, HystrixEventType.SUCCESS, HystrixEventType.RESPONSE_FROM_CACHE);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(3);
}
/**
* Test Request scoped caching with a mixture of commands
*/
@Test
public void testNoRequestCacheViaQueueSemaphore1() throws Exception {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
SuccessfulCacheableCommandViaSemaphore command1 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, false, "A");
SuccessfulCacheableCommandViaSemaphore command2 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, false, "B");
SuccessfulCacheableCommandViaSemaphore command3 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, false, "A");
assertFalse(command1.isCommandRunningInThread());
Future<String> f1 = command1.queue();
Future<String> f2 = command2.queue();
Future<String> f3 = command3.queue();
assertEquals("A", f1.get());
assertEquals("B", f2.get());
assertEquals("A", f3.get());
assertTrue(command1.executed);
// both should execute as they are different
assertTrue(command2.executed);
// this should also execute because caching is disabled
assertTrue(command3.executed);
assertCommandExecutionEvents(command1, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command3, HystrixEventType.SUCCESS);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(3);
}
/**
* Test Request scoped caching with a mixture of commands
*/
@Test
public void testRequestCacheViaExecuteSemaphore1() {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
SuccessfulCacheableCommandViaSemaphore command1 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, true, "A");
SuccessfulCacheableCommandViaSemaphore command2 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, true, "B");
SuccessfulCacheableCommandViaSemaphore command3 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, true, "A");
assertFalse(command1.isCommandRunningInThread());
String f1 = command1.execute();
String f2 = command2.execute();
String f3 = command3.execute();
assertEquals("A", f1);
assertEquals("B", f2);
assertEquals("A", f3);
assertTrue(command1.executed);
// both should execute as they are different
assertTrue(command2.executed);
// but the 3rd should come from cache
assertFalse(command3.executed);
assertCommandExecutionEvents(command1, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command3, HystrixEventType.SUCCESS, HystrixEventType.RESPONSE_FROM_CACHE);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(3);
}
/**
* Test Request scoped caching with a mixture of commands
*/
@Test
public void testNoRequestCacheViaExecuteSemaphore1() {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
SuccessfulCacheableCommandViaSemaphore command1 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, false, "A");
SuccessfulCacheableCommandViaSemaphore command2 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, false, "B");
SuccessfulCacheableCommandViaSemaphore command3 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, false, "A");
assertFalse(command1.isCommandRunningInThread());
String f1 = command1.execute();
String f2 = command2.execute();
String f3 = command3.execute();
assertEquals("A", f1);
assertEquals("B", f2);
assertEquals("A", f3);
assertTrue(command1.executed);
// both should execute as they are different
assertTrue(command2.executed);
// this should also execute because caching is disabled
assertTrue(command3.executed);
assertCommandExecutionEvents(command1, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command3, HystrixEventType.SUCCESS);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(3);
}
@Test
public void testNoRequestCacheOnTimeoutThrowsException() throws Exception {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
NoRequestCacheTimeoutWithoutFallback r1 = new NoRequestCacheTimeoutWithoutFallback(circuitBreaker);
try {
System.out.println("r1 value: " + r1.execute());
// we should have thrown an exception
fail("expected a timeout");
} catch (HystrixRuntimeException e) {
assertTrue(r1.isResponseTimedOut());
// what we want
}
NoRequestCacheTimeoutWithoutFallback r2 = new NoRequestCacheTimeoutWithoutFallback(circuitBreaker);
try {
r2.execute();
// we should have thrown an exception
fail("expected a timeout");
} catch (HystrixRuntimeException e) {
assertTrue(r2.isResponseTimedOut());
// what we want
}
NoRequestCacheTimeoutWithoutFallback r3 = new NoRequestCacheTimeoutWithoutFallback(circuitBreaker);
Future<Boolean> f3 = r3.queue();
try {
f3.get();
// we should have thrown an exception
fail("expected a timeout");
} catch (ExecutionException e) {
e.printStackTrace();
assertTrue(r3.isResponseTimedOut());
// what we want
}
Thread.sleep(500); // timeout on command is set to 200ms
NoRequestCacheTimeoutWithoutFallback r4 = new NoRequestCacheTimeoutWithoutFallback(circuitBreaker);
try {
r4.execute();
// we should have thrown an exception
fail("expected a timeout");
} catch (HystrixRuntimeException e) {
assertTrue(r4.isResponseTimedOut());
assertFalse(r4.isResponseFromFallback());
// what we want
}
assertCommandExecutionEvents(r1, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING);
assertCommandExecutionEvents(r2, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING);
assertCommandExecutionEvents(r3, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING);
assertCommandExecutionEvents(r4, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(4);
}
@Test
public void testRequestCacheOnTimeoutCausesNullPointerException() throws Exception {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
RequestCacheNullPointerExceptionCase command1 = new RequestCacheNullPointerExceptionCase(circuitBreaker);
RequestCacheNullPointerExceptionCase command2 = new RequestCacheNullPointerExceptionCase(circuitBreaker);
RequestCacheNullPointerExceptionCase command3 = new RequestCacheNullPointerExceptionCase(circuitBreaker);
// Expect it to time out - all results should be false
assertFalse(command1.execute());
assertFalse(command2.execute()); // return from cache #1
assertFalse(command3.execute()); // return from cache #2
Thread.sleep(500); // timeout on command is set to 200ms
RequestCacheNullPointerExceptionCase command4 = new RequestCacheNullPointerExceptionCase(circuitBreaker);
Boolean value = command4.execute(); // return from cache #3
assertFalse(value);
RequestCacheNullPointerExceptionCase command5 = new RequestCacheNullPointerExceptionCase(circuitBreaker);
Future<Boolean> f = command5.queue(); // return from cache #4
// the bug is that we're getting a null Future back, rather than a Future that returns false
assertNotNull(f);
assertFalse(f.get());
assertTrue(command5.isResponseFromFallback());
assertTrue(command5.isResponseTimedOut());
assertFalse(command5.isFailedExecution());
assertFalse(command5.isResponseShortCircuited());
assertNotNull(command5.getExecutionException());
assertCommandExecutionEvents(command1, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_SUCCESS, HystrixEventType.RESPONSE_FROM_CACHE);
assertCommandExecutionEvents(command3, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_SUCCESS, HystrixEventType.RESPONSE_FROM_CACHE);
assertCommandExecutionEvents(command4, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_SUCCESS, HystrixEventType.RESPONSE_FROM_CACHE);
assertCommandExecutionEvents(command5, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_SUCCESS, HystrixEventType.RESPONSE_FROM_CACHE);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(5);
}
@Test
public void testRequestCacheOnTimeoutThrowsException() throws Exception {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
RequestCacheTimeoutWithoutFallback r1 = new RequestCacheTimeoutWithoutFallback(circuitBreaker);
try {
System.out.println("r1 value: " + r1.execute());
// we should have thrown an exception
fail("expected a timeout");
} catch (HystrixRuntimeException e) {
assertTrue(r1.isResponseTimedOut());
// what we want
}
RequestCacheTimeoutWithoutFallback r2 = new RequestCacheTimeoutWithoutFallback(circuitBreaker);
try {
r2.execute();
// we should have thrown an exception
fail("expected a timeout");
} catch (HystrixRuntimeException e) {
assertTrue(r2.isResponseTimedOut());
// what we want
}
RequestCacheTimeoutWithoutFallback r3 = new RequestCacheTimeoutWithoutFallback(circuitBreaker);
Future<Boolean> f3 = r3.queue();
try {
f3.get();
// we should have thrown an exception
fail("expected a timeout");
} catch (ExecutionException e) {
e.printStackTrace();
assertTrue(r3.isResponseTimedOut());
// what we want
}
Thread.sleep(500); // timeout on command is set to 200ms
RequestCacheTimeoutWithoutFallback r4 = new RequestCacheTimeoutWithoutFallback(circuitBreaker);
try {
r4.execute();
// we should have thrown an exception
fail("expected a timeout");
} catch (HystrixRuntimeException e) {
assertTrue(r4.isResponseTimedOut());
assertFalse(r4.isResponseFromFallback());
// what we want
}
assertCommandExecutionEvents(r1, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING);
assertCommandExecutionEvents(r2, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING, HystrixEventType.RESPONSE_FROM_CACHE);
assertCommandExecutionEvents(r3, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING, HystrixEventType.RESPONSE_FROM_CACHE);
assertCommandExecutionEvents(r4, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING, HystrixEventType.RESPONSE_FROM_CACHE);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(4);
}
@Test
public void testRequestCacheOnThreadRejectionThrowsException() throws Exception {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
CountDownLatch completionLatch = new CountDownLatch(1);
RequestCacheThreadRejectionWithoutFallback r1 = new RequestCacheThreadRejectionWithoutFallback(circuitBreaker, completionLatch);
try {
System.out.println("r1: " + r1.execute());
// we should have thrown an exception
fail("expected a rejection");
} catch (HystrixRuntimeException e) {
assertTrue(r1.isResponseRejected());
// what we want
}
RequestCacheThreadRejectionWithoutFallback r2 = new RequestCacheThreadRejectionWithoutFallback(circuitBreaker, completionLatch);
try {
System.out.println("r2: " + r2.execute());
// we should have thrown an exception
fail("expected a rejection");
} catch (HystrixRuntimeException e) {
// e.printStackTrace();
assertTrue(r2.isResponseRejected());
// what we want
}
RequestCacheThreadRejectionWithoutFallback r3 = new RequestCacheThreadRejectionWithoutFallback(circuitBreaker, completionLatch);
try {
System.out.println("f3: " + r3.queue().get());
// we should have thrown an exception
fail("expected a rejection");
} catch (HystrixRuntimeException e) {
// e.printStackTrace();
assertTrue(r3.isResponseRejected());
// what we want
}
// let the command finish (only 1 should actually be blocked on this due to the response cache)
completionLatch.countDown();
// then another after the command has completed
RequestCacheThreadRejectionWithoutFallback r4 = new RequestCacheThreadRejectionWithoutFallback(circuitBreaker, completionLatch);
try {
System.out.println("r4: " + r4.execute());
// we should have thrown an exception
fail("expected a rejection");
} catch (HystrixRuntimeException e) {
// e.printStackTrace();
assertTrue(r4.isResponseRejected());
assertFalse(r4.isResponseFromFallback());
// what we want
}
assertCommandExecutionEvents(r1, HystrixEventType.THREAD_POOL_REJECTED, HystrixEventType.FALLBACK_MISSING);
assertCommandExecutionEvents(r2, HystrixEventType.THREAD_POOL_REJECTED, HystrixEventType.FALLBACK_MISSING, HystrixEventType.RESPONSE_FROM_CACHE);
assertCommandExecutionEvents(r3, HystrixEventType.THREAD_POOL_REJECTED, HystrixEventType.FALLBACK_MISSING, HystrixEventType.RESPONSE_FROM_CACHE);
assertCommandExecutionEvents(r4, HystrixEventType.THREAD_POOL_REJECTED, HystrixEventType.FALLBACK_MISSING, HystrixEventType.RESPONSE_FROM_CACHE);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(4);
}
/**
* Test that we can do basic execution without a RequestVariable being initialized.
*/
@Test
public void testBasicExecutionWorksWithoutRequestVariable() throws Exception {
/* force the RequestVariable to not be initialized */
HystrixRequestContext.setContextOnCurrentThread(null);
TestHystrixCommand<Boolean> command = new SuccessfulTestCommand();
assertEquals(true, command.execute());
TestHystrixCommand<Boolean> command2 = new SuccessfulTestCommand();
assertEquals(true, command2.queue().get());
}
/**
* Test that if we try and execute a command with a cacheKey without initializing RequestVariable that it gives an error.
*/
@Test(expected = HystrixRuntimeException.class)
public void testCacheKeyExecutionRequiresRequestVariable() throws Exception {
/* force the RequestVariable to not be initialized */
HystrixRequestContext.setContextOnCurrentThread(null);
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
SuccessfulCacheableCommand command = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "one");
assertEquals("one", command.execute());
SuccessfulCacheableCommand command2 = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "two");
assertEquals("two", command2.queue().get());
}
/**
* Test that a BadRequestException can be thrown and not count towards errors and bypasses fallback.
*/
@Test
public void testBadRequestExceptionViaExecuteInThread() {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
BadRequestCommand command1 = null;
try {
command1 = new BadRequestCommand(circuitBreaker, ExecutionIsolationStrategy.THREAD);
command1.execute();
fail("we expect to receive a " + HystrixBadRequestException.class.getSimpleName());
} catch (HystrixBadRequestException e) {
// success
e.printStackTrace();
}
assertCommandExecutionEvents(command1, HystrixEventType.BAD_REQUEST);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test that a BadRequestException can be thrown and not count towards errors and bypasses fallback.
*/
@Test
public void testBadRequestExceptionViaQueueInThread() throws Exception {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
BadRequestCommand command1 = null;
try {
command1 = new BadRequestCommand(circuitBreaker, ExecutionIsolationStrategy.THREAD);
command1.queue().get();
fail("we expect to receive a " + HystrixBadRequestException.class.getSimpleName());
} catch (ExecutionException e) {
e.printStackTrace();
if (e.getCause() instanceof HystrixBadRequestException) {
// success
} else {
fail("We expect a " + HystrixBadRequestException.class.getSimpleName() + " but got a " + e.getClass().getSimpleName());
}
}
assertCommandExecutionEvents(command1, HystrixEventType.BAD_REQUEST);
assertNotNull(command1.getExecutionException());
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test that BadRequestException behavior works the same on a cached response.
*/
@Test
public void testBadRequestExceptionViaQueueInThreadOnResponseFromCache() throws Exception {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
// execute once to cache the value
BadRequestCommand command1 = null;
try {
command1 = new BadRequestCommand(circuitBreaker, ExecutionIsolationStrategy.THREAD);
command1.execute();
} catch (Throwable e) {
// ignore
}
BadRequestCommand command2 = null;
try {
command2 = new BadRequestCommand(circuitBreaker, ExecutionIsolationStrategy.THREAD);
command2.queue().get();
fail("we expect to receive a " + HystrixBadRequestException.class.getSimpleName());
} catch (ExecutionException e) {
e.printStackTrace();
if (e.getCause() instanceof HystrixBadRequestException) {
// success
} else {
fail("We expect a " + HystrixBadRequestException.class.getSimpleName() + " but got a " + e.getClass().getSimpleName());
}
}
assertCommandExecutionEvents(command1, HystrixEventType.BAD_REQUEST);
assertCommandExecutionEvents(command2, HystrixEventType.BAD_REQUEST, HystrixEventType.RESPONSE_FROM_CACHE);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(2);
}
/**
* Test that a BadRequestException can be thrown and not count towards errors and bypasses fallback.
*/
@Test
public void testBadRequestExceptionViaExecuteInSemaphore() {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
BadRequestCommand command1 = new BadRequestCommand(circuitBreaker, ExecutionIsolationStrategy.SEMAPHORE);
try {
command1.execute();
fail("we expect to receive a " + HystrixBadRequestException.class.getSimpleName());
} catch (HystrixBadRequestException e) {
// success
e.printStackTrace();
}
assertCommandExecutionEvents(command1, HystrixEventType.BAD_REQUEST);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test a checked Exception being thrown
*/
@Test
public void testCheckedExceptionViaExecute() {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
CommandWithCheckedException command = new CommandWithCheckedException(circuitBreaker);
try {
command.execute();
fail("we expect to receive a " + Exception.class.getSimpleName());
} catch (Exception e) {
assertEquals("simulated checked exception message", e.getCause().getMessage());
}
assertEquals("simulated checked exception message", command.getFailedExecutionException().getMessage());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isFailedExecution());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_MISSING);
assertNotNull(command.getExecutionException());
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test a java.lang.Error being thrown
*
* @throws InterruptedException
*/
@Test
public void testCheckedExceptionViaObserve() throws InterruptedException {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
CommandWithCheckedException command = new CommandWithCheckedException(circuitBreaker);
final AtomicReference<Throwable> t = new AtomicReference<Throwable>();
final CountDownLatch latch = new CountDownLatch(1);
try {
command.observe().subscribe(new Observer<Boolean>() {
@Override
public void onCompleted() {
latch.countDown();
}
@Override
public void onError(Throwable e) {
t.set(e);
latch.countDown();
}
@Override
public void onNext(Boolean args) {
}
});
} catch (Exception e) {
e.printStackTrace();
fail("we should not get anything thrown, it should be emitted via the Observer#onError method");
}
latch.await(1, TimeUnit.SECONDS);
assertNotNull(t.get());
t.get().printStackTrace();
assertTrue(t.get() instanceof HystrixRuntimeException);
assertEquals("simulated checked exception message", t.get().getCause().getMessage());
assertEquals("simulated checked exception message", command.getFailedExecutionException().getMessage());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isFailedExecution());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_MISSING);
assertNotNull(command.getExecutionException());
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
/**
* Test an Exception implementing NotWrappedByHystrix being thrown
*
* @throws InterruptedException
*/
@Test
public void testNotWrappedExceptionViaObserve() throws InterruptedException {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
CommandWithNotWrappedByHystrixException command = new CommandWithNotWrappedByHystrixException(circuitBreaker);
final AtomicReference<Throwable> t = new AtomicReference<Throwable>();
final CountDownLatch latch = new CountDownLatch(1);
try {
command.observe().subscribe(new Observer<Boolean>() {
@Override
public void onCompleted() {
latch.countDown();
}
@Override
public void onError(Throwable e) {
t.set(e);
latch.countDown();
}
@Override
public void onNext(Boolean args) {
}
});
} catch (Exception e) {
e.printStackTrace();
fail("we should not get anything thrown, it should be emitted via the Observer#onError method");
}
latch.await(1, TimeUnit.SECONDS);
assertNotNull(t.get());
t.get().printStackTrace();
assertTrue(t.get() instanceof NotWrappedByHystrixTestException);
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isFailedExecution());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_MISSING);
assertNotNull(command.getExecutionException());
assertTrue(command.getExecutionException() instanceof NotWrappedByHystrixTestException);
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
@Test
public void testSemaphoreExecutionWithTimeout() {
TestHystrixCommand<Boolean> cmd = new InterruptibleCommand(new TestCircuitBreaker(), false);
System.out.println("Starting command");
long timeMillis = System.currentTimeMillis();
try {
cmd.execute();
fail("Should throw");
} catch (Throwable t) {
assertNotNull(cmd.getExecutionException());
System.out.println("Unsuccessful Execution took : " + (System.currentTimeMillis() - timeMillis));
assertCommandExecutionEvents(cmd, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING);
assertEquals(0, cmd.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
}
/**
* Test a recoverable java.lang.Error being thrown with no fallback
*/
@Test
public void testRecoverableErrorWithNoFallbackThrowsError() {
TestHystrixCommand<Integer> command = getRecoverableErrorCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED);
try {
command.execute();
fail("we expect to receive a " + Error.class.getSimpleName());
} catch (Exception e) {
// the actual error is an extra cause level deep because Hystrix needs to wrap Throwable/Error as it's public
// methods only support Exception and it's not a strong enough reason to break backwards compatibility and jump to version 2.x
// so HystrixRuntimeException -> wrapper Exception -> actual Error
assertEquals("Execution ERROR for TestHystrixCommand", e.getCause().getCause().getMessage());
}
assertEquals("Execution ERROR for TestHystrixCommand", command.getFailedExecutionException().getCause().getMessage());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isFailedExecution());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_MISSING);
assertNotNull(command.getExecutionException());
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
@Test
public void testRecoverableErrorMaskedByFallbackButLogged() {
TestHystrixCommand<Integer> command = getRecoverableErrorCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.FallbackResult.SUCCESS);
assertEquals(FlexibleTestHystrixCommand.FALLBACK_VALUE, command.execute());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isFailedExecution());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_SUCCESS);
assertNotNull(command.getExecutionException());
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
@Test
public void testUnrecoverableErrorThrownWithNoFallback() {
TestHystrixCommand<Integer> command = getUnrecoverableErrorCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED);
try {
command.execute();
fail("we expect to receive a " + Error.class.getSimpleName());
} catch (Exception e) {
// the actual error is an extra cause level deep because Hystrix needs to wrap Throwable/Error as it's public
// methods only support Exception and it's not a strong enough reason to break backwards compatibility and jump to version 2.x
// so HystrixRuntimeException -> wrapper Exception -> actual Error
assertEquals("Unrecoverable Error for TestHystrixCommand", e.getCause().getCause().getMessage());
}
assertEquals("Unrecoverable Error for TestHystrixCommand", command.getFailedExecutionException().getCause().getMessage());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isFailedExecution());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE);
assertNotNull(command.getExecutionException());
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
@Test //even though fallback is implemented, that logic never fires, as this is an unrecoverable error and should be directly propagated to the caller
public void testUnrecoverableErrorThrownWithFallback() {
TestHystrixCommand<Integer> command = getUnrecoverableErrorCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.FallbackResult.SUCCESS);
try {
command.execute();
fail("we expect to receive a " + Error.class.getSimpleName());
} catch (Exception e) {
// the actual error is an extra cause level deep because Hystrix needs to wrap Throwable/Error as it's public
// methods only support Exception and it's not a strong enough reason to break backwards compatibility and jump to version 2.x
// so HystrixRuntimeException -> wrapper Exception -> actual Error
assertEquals("Unrecoverable Error for TestHystrixCommand", e.getCause().getCause().getMessage());
}
assertEquals("Unrecoverable Error for TestHystrixCommand", command.getFailedExecutionException().getCause().getMessage());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isFailedExecution());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE);
assertNotNull(command.getExecutionException());
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
static class EventCommand extends HystrixCommand {
public EventCommand() {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("eventGroup")).andCommandPropertiesDefaults(new HystrixCommandProperties.Setter().withFallbackIsolationSemaphoreMaxConcurrentRequests(3)));
}
@Override
protected String run() throws Exception {
System.out.println(Thread.currentThread().getName() + " : In run()");
throw new RuntimeException("run_exception");
}
@Override
public String getFallback() {
try {
System.out.println(Thread.currentThread().getName() + " : In fallback => " + getExecutionEvents());
Thread.sleep(30000L);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " : Interruption occurred");
}
System.out.println(Thread.currentThread().getName() + " : CMD Success Result");
return "fallback";
}
}
@Test
public void testNonBlockingCommandQueueFiresTimeout() throws Exception { //see https://github.com/Netflix/Hystrix/issues/514
final TestHystrixCommand<Integer> cmd = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 200, AbstractTestHystrixCommand.FallbackResult.SUCCESS, 50);
new Thread() {
@Override
public void run() {
cmd.queue();
}
}.start();
Thread.sleep(200);
//timeout should occur in 50ms, and underlying thread should run for 500ms
//therefore, after 200ms, the command should have finished with a fallback on timeout
assertTrue(cmd.isExecutionComplete());
assertTrue(cmd.isResponseTimedOut());
assertEquals(0, cmd.metrics.getCurrentConcurrentExecutionCount());
}
@Override
protected void assertHooksOnSuccess(Func0<TestHystrixCommand<Integer>> ctor, Action1<TestHystrixCommand<Integer>> assertion) {
assertExecute(ctor.call(), assertion, true);
assertBlockingQueue(ctor.call(), assertion, true);
assertNonBlockingQueue(ctor.call(), assertion, true, false);
assertBlockingObserve(ctor.call(), assertion, true);
assertNonBlockingObserve(ctor.call(), assertion, true);
}
@Override
protected void assertHooksOnFailure(Func0<TestHystrixCommand<Integer>> ctor, Action1<TestHystrixCommand<Integer>> assertion) {
assertExecute(ctor.call(), assertion, false);
assertBlockingQueue(ctor.call(), assertion, false);
assertNonBlockingQueue(ctor.call(), assertion, false, false);
assertBlockingObserve(ctor.call(), assertion, false);
assertNonBlockingObserve(ctor.call(), assertion, false);
}
@Override
protected void assertHooksOnFailure(Func0<TestHystrixCommand<Integer>> ctor, Action1<TestHystrixCommand<Integer>> assertion, boolean failFast) {
assertExecute(ctor.call(), assertion, false);
assertBlockingQueue(ctor.call(), assertion, false);
assertNonBlockingQueue(ctor.call(), assertion, false, failFast);
assertBlockingObserve(ctor.call(), assertion, false);
assertNonBlockingObserve(ctor.call(), assertion, false);
}
/**
* Run the command via {@link com.netflix.hystrix.HystrixCommand#execute()} and then assert
* @param command command to run
* @param assertion assertions to check
* @param isSuccess should the command succeedInteger
*/
private void assertExecute(TestHystrixCommand<Integer> command, Action1<TestHystrixCommand<Integer>> assertion, boolean isSuccess) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Running command.execute() and then assertions...");
if (isSuccess) {
command.execute();
} else {
try {
Object o = command.execute();
fail("Expected a command failure!");
} catch (Exception ex) {
System.out.println("Received expected ex : " + ex);
ex.printStackTrace();
}
}
assertion.call(command);
}
/**
* Run the command via {@link com.netflix.hystrix.HystrixCommand#queue()}, immediately block, and then assert
* @param command command to run
* @param assertion assertions to check
* @param isSuccess should the command succeedInteger
*/
private void assertBlockingQueue(TestHystrixCommand<Integer> command, Action1<TestHystrixCommand<Integer>> assertion, boolean isSuccess) {
System.out.println("Running command.queue(), immediately blocking and then running assertions...");
if (isSuccess) {
try {
command.queue().get();
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
try {
command.queue().get();
fail("Expected a command failure!");
} catch (InterruptedException ie) {
throw new RuntimeException(ie);
} catch (ExecutionException ee) {
System.out.println("Received expected ex : " + ee.getCause());
ee.getCause().printStackTrace();
} catch (Exception e) {
System.out.println("Received expected ex : " + e);
e.printStackTrace();
}
}
assertion.call(command);
}
/**
* Run the command via {@link com.netflix.hystrix.HystrixCommand#queue()}, then poll for the command to be finished.
* When it is finished, assert
* @param command command to run
* @param assertion assertions to check
* @param isSuccess should the command succeedInteger
*/
private void assertNonBlockingQueue(TestHystrixCommand<Integer> command, Action1<TestHystrixCommand<Integer>> assertion, boolean isSuccess, boolean failFast) {
System.out.println("Running command.queue(), sleeping the test thread until command is complete, and then running assertions...");
Future<Integer> f = null;
if (failFast) {
try {
f = command.queue();
fail("Expected a failure when queuing the command");
} catch (Exception ex) {
System.out.println("Received expected fail fast ex : " + ex);
ex.printStackTrace();
}
} else {
try {
f = command.queue();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
awaitCommandCompletion(command);
assertion.call(command);
if (isSuccess) {
try {
f.get();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
} else {
try {
f.get();
fail("Expected a command failure!");
} catch (InterruptedException ie) {
throw new RuntimeException(ie);
} catch (ExecutionException ee) {
System.out.println("Received expected ex : " + ee.getCause());
ee.getCause().printStackTrace();
} catch (Exception e) {
System.out.println("Received expected ex : " + e);
e.printStackTrace();
}
}
}
private <T> void awaitCommandCompletion(TestHystrixCommand<T> command) {
while (!command.isExecutionComplete()) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException("interrupted");
}
}
}
/**
* Test a command execution that fails but has a fallback.
*/
@Test
public void testExecutionFailureWithFallbackImplementedButDisabled() {
TestHystrixCommand<Boolean> commandEnabled = new KnownFailureTestCommandWithFallback(new TestCircuitBreaker(), true);
try {
assertEquals(false, commandEnabled.execute());
} catch (Exception e) {
e.printStackTrace();
fail("We should have received a response from the fallback.");
}
TestHystrixCommand<Boolean> commandDisabled = new KnownFailureTestCommandWithFallback(new TestCircuitBreaker(), false);
try {
assertEquals(false, commandDisabled.execute());
fail("expect exception thrown");
} catch (Exception e) {
// expected
}
assertEquals("we failed with a simulated issue", commandDisabled.getFailedExecutionException().getMessage());
assertTrue(commandDisabled.isFailedExecution());
assertCommandExecutionEvents(commandEnabled, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_SUCCESS);
assertCommandExecutionEvents(commandDisabled, HystrixEventType.FAILURE);
assertNotNull(commandDisabled.getExecutionException());
assertEquals(0, commandDisabled.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(2);
}
@Test
public void testExecutionTimeoutValue() {
HystrixCommand.Setter properties = HystrixCommand.Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("TestKey"))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withExecutionTimeoutInMilliseconds(50));
HystrixCommand<String> command = new HystrixCommand<String>(properties) {
@Override
protected String run() throws Exception {
Thread.sleep(3000);
// should never reach here
return "hello";
}
@Override
protected String getFallback() {
if (isResponseTimedOut()) {
return "timed-out";
} else {
return "abc";
}
}
};
String value = command.execute();
assertTrue(command.isResponseTimedOut());
assertEquals("expected fallback value", "timed-out", value);
}
/**
* See https://github.com/Netflix/Hystrix/issues/212
*/
@Test
public void testObservableTimeoutNoFallbackThreadContext() {
TestSubscriber<Object> ts = new TestSubscriber<Object>();
final AtomicReference<Thread> onErrorThread = new AtomicReference<Thread>();
final AtomicBoolean isRequestContextInitialized = new AtomicBoolean();
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 200, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED, 50);
command.toObservable().doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable t1) {
System.out.println("onError: " + t1);
System.out.println("onError Thread: " + Thread.currentThread());
System.out.println("ThreadContext in onError: " + HystrixRequestContext.isCurrentThreadInitialized());
onErrorThread.set(Thread.currentThread());
isRequestContextInitialized.set(HystrixRequestContext.isCurrentThreadInitialized());
}
}).subscribe(ts);
ts.awaitTerminalEvent();
assertTrue(isRequestContextInitialized.get());
assertTrue(onErrorThread.get().getName().startsWith("HystrixTimer"));
List<Throwable> errors = ts.getOnErrorEvents();
assertEquals(1, errors.size());
Throwable e = errors.get(0);
if (errors.get(0) instanceof HystrixRuntimeException) {
HystrixRuntimeException de = (HystrixRuntimeException) e;
assertNotNull(de.getFallbackException());
assertTrue(de.getFallbackException() instanceof UnsupportedOperationException);
assertNotNull(de.getImplementingClass());
assertNotNull(de.getCause());
assertTrue(de.getCause() instanceof TimeoutException);
} else {
fail("the exception should be ExecutionException with cause as HystrixRuntimeException");
}
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isResponseTimedOut());
assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING);
assertNotNull(command.getExecutionException());
assertEquals(0, command.getBuilder().metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
@Test
public void testExceptionConvertedToBadRequestExceptionInExecutionHookBypassesCircuitBreaker() {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
ExceptionToBadRequestByExecutionHookCommand command = new ExceptionToBadRequestByExecutionHookCommand(circuitBreaker, ExecutionIsolationStrategy.THREAD);
try {
command.execute();
fail("we expect to receive a " + HystrixBadRequestException.class.getSimpleName());
} catch (HystrixBadRequestException e) {
// success
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
fail("We expect a " + HystrixBadRequestException.class.getSimpleName() + " but got a " + e.getClass().getSimpleName());
}
assertCommandExecutionEvents(command, HystrixEventType.BAD_REQUEST);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
}
@Test
public void testInterruptFutureOnTimeout() throws InterruptedException, ExecutionException {
// given
InterruptibleCommand cmd = new InterruptibleCommand(new TestCircuitBreaker(), true);
// when
Future<Boolean> f = cmd.queue();
// then
Thread.sleep(500);
assertTrue(cmd.hasBeenInterrupted());
}
@Test
public void testInterruptObserveOnTimeout() throws InterruptedException {
// given
InterruptibleCommand cmd = new InterruptibleCommand(new TestCircuitBreaker(), true);
// when
cmd.observe().subscribe();
// then
Thread.sleep(500);
assertTrue(cmd.hasBeenInterrupted());
}
@Test
public void testInterruptToObservableOnTimeout() throws InterruptedException {
// given
InterruptibleCommand cmd = new InterruptibleCommand(new TestCircuitBreaker(), true);
// when
cmd.toObservable().subscribe();
// then
Thread.sleep(500);
assertTrue(cmd.hasBeenInterrupted());
}
@Test
public void testDoNotInterruptFutureOnTimeoutIfPropertySaysNotTo() throws InterruptedException, ExecutionException {
// given
InterruptibleCommand cmd = new InterruptibleCommand(new TestCircuitBreaker(), false);
// when
Future<Boolean> f = cmd.queue();
// then
Thread.sleep(500);
assertFalse(cmd.hasBeenInterrupted());
}
@Test
public void testDoNotInterruptObserveOnTimeoutIfPropertySaysNotTo() throws InterruptedException {
// given
InterruptibleCommand cmd = new InterruptibleCommand(new TestCircuitBreaker(), false);
// when
cmd.observe().subscribe();
// then
Thread.sleep(500);
assertFalse(cmd.hasBeenInterrupted());
}
@Test
public void testDoNotInterruptToObservableOnTimeoutIfPropertySaysNotTo() throws InterruptedException {
// given
InterruptibleCommand cmd = new InterruptibleCommand(new TestCircuitBreaker(), false);
// when
cmd.toObservable().subscribe();
// then
Thread.sleep(500);
assertFalse(cmd.hasBeenInterrupted());
}
@Test
public void testCancelFutureWithInterruptionWhenPropertySaysNotTo() throws InterruptedException, ExecutionException {
// given
InterruptibleCommand cmd = new InterruptibleCommand(new TestCircuitBreaker(), true, false, 1000);
// when
Future<Boolean> f = cmd.queue();
Thread.sleep(500);
f.cancel(true);
Thread.sleep(500);
// then
try {
f.get();
fail("Should have thrown a CancellationException");
} catch (CancellationException e) {
assertFalse(cmd.hasBeenInterrupted());
}
}
@Test
public void testCancelFutureWithInterruption() throws InterruptedException, ExecutionException {
// given
InterruptibleCommand cmd = new InterruptibleCommand(new TestCircuitBreaker(), true, true, 1000);
// when
Future<Boolean> f = cmd.queue();
Thread.sleep(500);
f.cancel(true);
Thread.sleep(500);
// then
try {
f.get();
fail("Should have thrown a CancellationException");
} catch (CancellationException e) {
assertTrue(cmd.hasBeenInterrupted());
}
}
@Test
public void testCancelFutureWithoutInterruption() throws InterruptedException, ExecutionException, TimeoutException {
// given
InterruptibleCommand cmd = new InterruptibleCommand(new TestCircuitBreaker(), true, true, 1000);
// when
Future<Boolean> f = cmd.queue();
Thread.sleep(500);
f.cancel(false);
Thread.sleep(500);
// then
try {
f.get();
fail("Should have thrown a CancellationException");
} catch (CancellationException e) {
assertFalse(cmd.hasBeenInterrupted());
}
}
@Test
public void testChainedCommand() {
class SubCommand extends TestHystrixCommand<Integer> {
public SubCommand(TestCircuitBreaker circuitBreaker) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics));
}
@Override
protected Integer run() throws Exception {
return 2;
}
}
class PrimaryCommand extends TestHystrixCommand<Integer> {
public PrimaryCommand(TestCircuitBreaker circuitBreaker) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics));
}
@Override
protected Integer run() throws Exception {
throw new RuntimeException("primary failure");
}
@Override
protected Integer getFallback() {
SubCommand subCmd = new SubCommand(new TestCircuitBreaker());
return subCmd.execute();
}
}
assertTrue(2 == new PrimaryCommand(new TestCircuitBreaker()).execute());
}
@Test
public void testSlowFallback() {
class PrimaryCommand extends TestHystrixCommand<Integer> {
public PrimaryCommand(TestCircuitBreaker circuitBreaker) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics));
}
@Override
protected Integer run() throws Exception {
throw new RuntimeException("primary failure");
}
@Override
protected Integer getFallback() {
try {
Thread.sleep(1500);
return 1;
} catch (InterruptedException ie) {
System.out.println("Caught Interrupted Exception");
ie.printStackTrace();
}
return -1;
}
}
assertTrue(1 == new PrimaryCommand(new TestCircuitBreaker()).execute());
}
@Test
public void testSemaphoreThreadSafety() {
final int NUM_PERMITS = 1;
final TryableSemaphoreActual s = new TryableSemaphoreActual(HystrixProperty.Factory.asProperty(NUM_PERMITS));
final int NUM_THREADS = 10;
ExecutorService threadPool = Executors.newFixedThreadPool(NUM_THREADS);
final int NUM_TRIALS = 100;
for (int t = 0; t < NUM_TRIALS; t++) {
System.out.println("TRIAL : " + t);
final AtomicInteger numAcquired = new AtomicInteger(0);
final CountDownLatch latch = new CountDownLatch(NUM_THREADS);
for (int i = 0; i < NUM_THREADS; i++) {
threadPool.submit(new Runnable() {
@Override
public void run() {
boolean acquired = s.tryAcquire();
if (acquired) {
try {
numAcquired.incrementAndGet();
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
} finally {
s.release();
}
}
latch.countDown();
}
});
}
try {
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
} catch (InterruptedException ex) {
fail(ex.getMessage());
}
assertEquals("Number acquired should be equal to the number of permits", NUM_PERMITS, numAcquired.get());
assertEquals("Semaphore should always get released back to 0", 0, s.getNumberOfPermitsUsed());
}
}
@Test
public void testCancelledTasksInQueueGetRemoved() throws Exception {
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("Cancellation-A");
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
SingleThreadedPoolWithQueue pool = new SingleThreadedPoolWithQueue(10, 1);
TestCommandRejection command1 = new TestCommandRejection(key, circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_NOT_IMPLEMENTED);
TestCommandRejection command2 = new TestCommandRejection(key, circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_NOT_IMPLEMENTED);
// this should go through the queue and into the thread pool
Future<Boolean> poolFiller = command1.queue();
// this command will stay in the queue until the thread pool is empty
Observable<Boolean> cmdInQueue = command2.observe();
Subscription s = cmdInQueue.subscribe();
assertEquals(1, pool.queue.size());
s.unsubscribe();
assertEquals(0, pool.queue.size());
//make sure we wait for the command to finish so the state is clean for next test
poolFiller.get();
assertCommandExecutionEvents(command1, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.CANCELLED);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertSaneHystrixRequestLog(2);
}
@Test
public void testOnRunStartHookThrowsSemaphoreIsolated() {
final AtomicBoolean exceptionEncountered = new AtomicBoolean(false);
final AtomicBoolean onThreadStartInvoked = new AtomicBoolean(false);
final AtomicBoolean onThreadCompleteInvoked = new AtomicBoolean(false);
final AtomicBoolean executionAttempted = new AtomicBoolean(false);
class FailureInjectionHook extends HystrixCommandExecutionHook {
@Override
public <T> void onExecutionStart(HystrixInvokable<T> commandInstance) {
throw new HystrixRuntimeException(HystrixRuntimeException.FailureType.COMMAND_EXCEPTION, commandInstance.getClass(), "Injected Failure", null, null);
}
@Override
public <T> void onThreadStart(HystrixInvokable<T> commandInstance) {
onThreadStartInvoked.set(true);
super.onThreadStart(commandInstance);
}
@Override
public <T> void onThreadComplete(HystrixInvokable<T> commandInstance) {
onThreadCompleteInvoked.set(true);
super.onThreadComplete(commandInstance);
}
}
final FailureInjectionHook failureInjectionHook = new FailureInjectionHook();
class FailureInjectedCommand extends TestHystrixCommand<Integer> {
public FailureInjectedCommand(ExecutionIsolationStrategy isolationStrategy) {
super(testPropsBuilder().setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(isolationStrategy)), failureInjectionHook);
}
@Override
protected Integer run() throws Exception {
executionAttempted.set(true);
return 3;
}
}
TestHystrixCommand<Integer> semaphoreCmd = new FailureInjectedCommand(ExecutionIsolationStrategy.SEMAPHORE);
try {
int result = semaphoreCmd.execute();
System.out.println("RESULT : " + result);
} catch (Throwable ex) {
ex.printStackTrace();
exceptionEncountered.set(true);
}
assertTrue(exceptionEncountered.get());
assertFalse(onThreadStartInvoked.get());
assertFalse(onThreadCompleteInvoked.get());
assertFalse(executionAttempted.get());
assertEquals(0, semaphoreCmd.metrics.getCurrentConcurrentExecutionCount());
}
@Test
public void testOnRunStartHookThrowsThreadIsolated() {
final AtomicBoolean exceptionEncountered = new AtomicBoolean(false);
final AtomicBoolean onThreadStartInvoked = new AtomicBoolean(false);
final AtomicBoolean onThreadCompleteInvoked = new AtomicBoolean(false);
final AtomicBoolean executionAttempted = new AtomicBoolean(false);
class FailureInjectionHook extends HystrixCommandExecutionHook {
@Override
public <T> void onExecutionStart(HystrixInvokable<T> commandInstance) {
throw new HystrixRuntimeException(HystrixRuntimeException.FailureType.COMMAND_EXCEPTION, commandInstance.getClass(), "Injected Failure", null, null);
}
@Override
public <T> void onThreadStart(HystrixInvokable<T> commandInstance) {
onThreadStartInvoked.set(true);
super.onThreadStart(commandInstance);
}
@Override
public <T> void onThreadComplete(HystrixInvokable<T> commandInstance) {
onThreadCompleteInvoked.set(true);
super.onThreadComplete(commandInstance);
}
}
final FailureInjectionHook failureInjectionHook = new FailureInjectionHook();
class FailureInjectedCommand extends TestHystrixCommand<Integer> {
public FailureInjectedCommand(ExecutionIsolationStrategy isolationStrategy) {
super(testPropsBuilder(new TestCircuitBreaker()).setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(isolationStrategy)), failureInjectionHook);
}
@Override
protected Integer run() throws Exception {
executionAttempted.set(true);
return 3;
}
}
TestHystrixCommand<Integer> threadCmd = new FailureInjectedCommand(ExecutionIsolationStrategy.THREAD);
try {
int result = threadCmd.execute();
System.out.println("RESULT : " + result);
} catch (Throwable ex) {
ex.printStackTrace();
exceptionEncountered.set(true);
}
assertTrue(exceptionEncountered.get());
assertTrue(onThreadStartInvoked.get());
assertTrue(onThreadCompleteInvoked.get());
assertFalse(executionAttempted.get());
assertEquals(0, threadCmd.metrics.getCurrentConcurrentExecutionCount());
}
@Test
public void testEarlyUnsubscribeDuringExecutionViaToObservable() {
class AsyncCommand extends HystrixCommand<Boolean> {
public AsyncCommand() {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ASYNC")));
}
@Override
protected Boolean run() {
try {
Thread.sleep(500);
return true;
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
}
HystrixCommand<Boolean> cmd = new AsyncCommand();
final CountDownLatch latch = new CountDownLatch(1);
Observable<Boolean> o = cmd.toObservable();
Subscription s = o.
doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println("OnUnsubscribe");
latch.countDown();
}
}).
subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
System.out.println("OnCompleted");
}
@Override
public void onError(Throwable e) {
System.out.println("OnError : " + e);
}
@Override
public void onNext(Boolean b) {
System.out.println("OnNext : " + b);
}
});
try {
Thread.sleep(10);
s.unsubscribe();
assertTrue(latch.await(200, TimeUnit.MILLISECONDS));
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertEquals("Number of execution semaphores in use", 0, cmd.getExecutionSemaphore().getNumberOfPermitsUsed());
assertEquals("Number of fallback semaphores in use", 0, cmd.getFallbackSemaphore().getNumberOfPermitsUsed());
assertFalse(cmd.isExecutionComplete());
assertEquals(null, cmd.getFailedExecutionException());
assertNull(cmd.getExecutionException());
System.out.println("Execution time : " + cmd.getExecutionTimeInMilliseconds());
assertTrue(cmd.getExecutionTimeInMilliseconds() > -1);
assertFalse(cmd.isSuccessfulExecution());
assertCommandExecutionEvents(cmd, HystrixEventType.CANCELLED);
assertEquals(0, cmd.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
@Test
public void testEarlyUnsubscribeDuringExecutionViaObserve() {
class AsyncCommand extends HystrixCommand<Boolean> {
public AsyncCommand() {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ASYNC")));
}
@Override
protected Boolean run() {
try {
Thread.sleep(500);
return true;
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
}
HystrixCommand<Boolean> cmd = new AsyncCommand();
final CountDownLatch latch = new CountDownLatch(1);
Observable<Boolean> o = cmd.observe();
Subscription s = o.
doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println("OnUnsubscribe");
latch.countDown();
}
}).
subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
System.out.println("OnCompleted");
}
@Override
public void onError(Throwable e) {
System.out.println("OnError : " + e);
}
@Override
public void onNext(Boolean b) {
System.out.println("OnNext : " + b);
}
});
try {
Thread.sleep(10);
s.unsubscribe();
assertTrue(latch.await(200, TimeUnit.MILLISECONDS));
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertEquals("Number of execution semaphores in use", 0, cmd.getExecutionSemaphore().getNumberOfPermitsUsed());
assertEquals("Number of fallback semaphores in use", 0, cmd.getFallbackSemaphore().getNumberOfPermitsUsed());
assertFalse(cmd.isExecutionComplete());
assertEquals(null, cmd.getFailedExecutionException());
assertNull(cmd.getExecutionException());
assertTrue(cmd.getExecutionTimeInMilliseconds() > -1);
assertFalse(cmd.isSuccessfulExecution());
assertCommandExecutionEvents(cmd, HystrixEventType.CANCELLED);
assertEquals(0, cmd.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
@Test
public void testEarlyUnsubscribeDuringFallback() {
class AsyncCommand extends HystrixCommand<Boolean> {
public AsyncCommand() {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ASYNC")));
}
@Override
protected Boolean run() {
throw new RuntimeException("run failure");
}
@Override
protected Boolean getFallback() {
try {
Thread.sleep(500);
return false;
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
}
HystrixCommand<Boolean> cmd = new AsyncCommand();
final CountDownLatch latch = new CountDownLatch(1);
Observable<Boolean> o = cmd.toObservable();
Subscription s = o.
doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println("OnUnsubscribe");
latch.countDown();
}
}).
subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
System.out.println("OnCompleted");
latch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println("OnError : " + e);
}
@Override
public void onNext(Boolean b) {
System.out.println("OnNext : " + b);
}
});
try {
Thread.sleep(10); //give fallback a chance to fire
s.unsubscribe();
assertTrue(latch.await(200, TimeUnit.MILLISECONDS));
assertEquals("Number of execution semaphores in use", 0, cmd.getExecutionSemaphore().getNumberOfPermitsUsed());
assertEquals("Number of fallback semaphores in use", 0, cmd.getFallbackSemaphore().getNumberOfPermitsUsed());
assertEquals(0, cmd.metrics.getCurrentConcurrentExecutionCount());
assertFalse(cmd.isExecutionComplete());
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
@Test
public void testRequestThenCacheHitAndCacheHitUnsubscribed() {
AsyncCacheableCommand original = new AsyncCacheableCommand("foo");
AsyncCacheableCommand fromCache = new AsyncCacheableCommand("foo");
final AtomicReference<Boolean> originalValue = new AtomicReference<Boolean>(null);
final AtomicReference<Boolean> fromCacheValue = new AtomicReference<Boolean>(null);
final CountDownLatch originalLatch = new CountDownLatch(1);
final CountDownLatch fromCacheLatch = new CountDownLatch(1);
Observable<Boolean> originalObservable = original.toObservable();
Observable<Boolean> fromCacheObservable = fromCache.toObservable();
Subscription originalSubscription = originalObservable.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.Original Unsubscribe");
originalLatch.countDown();
}
}).subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.Original OnCompleted");
originalLatch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.Original OnError : " + e);
originalLatch.countDown();
}
@Override
public void onNext(Boolean b) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.Original OnNext : " + b);
originalValue.set(b);
}
});
Subscription fromCacheSubscription = fromCacheObservable.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " FromCache Unsubscribe");
fromCacheLatch.countDown();
}
}).subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " FromCache OnCompleted");
fromCacheLatch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " FromCache OnError : " + e);
fromCacheLatch.countDown();
}
@Override
public void onNext(Boolean b) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " FromCache OnNext : " + b);
fromCacheValue.set(b);
}
});
try {
fromCacheSubscription.unsubscribe();
assertTrue(fromCacheLatch.await(600, TimeUnit.MILLISECONDS));
assertTrue(originalLatch.await(600, TimeUnit.MILLISECONDS));
assertEquals("Number of execution semaphores in use (original)", 0, original.getExecutionSemaphore().getNumberOfPermitsUsed());
assertEquals("Number of fallback semaphores in use (original)", 0, original.getFallbackSemaphore().getNumberOfPermitsUsed());
assertTrue(original.isExecutionComplete());
assertTrue(original.isExecutedInThread());
assertEquals(null, original.getFailedExecutionException());
assertNull(original.getExecutionException());
assertTrue(original.getExecutionTimeInMilliseconds() > -1);
assertTrue(original.isSuccessfulExecution());
assertCommandExecutionEvents(original, HystrixEventType.SUCCESS);
assertTrue(originalValue.get());
assertEquals(0, original.metrics.getCurrentConcurrentExecutionCount());
assertEquals("Number of execution semaphores in use (fromCache)", 0, fromCache.getExecutionSemaphore().getNumberOfPermitsUsed());
assertEquals("Number of fallback semaphores in use (fromCache)", 0, fromCache.getFallbackSemaphore().getNumberOfPermitsUsed());
assertFalse(fromCache.isExecutionComplete());
assertFalse(fromCache.isExecutedInThread());
assertEquals(null, fromCache.getFailedExecutionException());
assertNull(fromCache.getExecutionException());
assertCommandExecutionEvents(fromCache, HystrixEventType.RESPONSE_FROM_CACHE, HystrixEventType.CANCELLED);
assertTrue(fromCache.getExecutionTimeInMilliseconds() == -1);
assertFalse(fromCache.isSuccessfulExecution());
assertEquals(0, fromCache.metrics.getCurrentConcurrentExecutionCount());
assertFalse(original.isCancelled()); //underlying work
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertSaneHystrixRequestLog(2);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
@Test
public void testRequestThenCacheHitAndOriginalUnsubscribed() {
AsyncCacheableCommand original = new AsyncCacheableCommand("foo");
AsyncCacheableCommand fromCache = new AsyncCacheableCommand("foo");
final AtomicReference<Boolean> originalValue = new AtomicReference<Boolean>(null);
final AtomicReference<Boolean> fromCacheValue = new AtomicReference<Boolean>(null);
final CountDownLatch originalLatch = new CountDownLatch(1);
final CountDownLatch fromCacheLatch = new CountDownLatch(1);
Observable<Boolean> originalObservable = original.toObservable();
Observable<Boolean> fromCacheObservable = fromCache.toObservable();
Subscription originalSubscription = originalObservable.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.Original Unsubscribe");
originalLatch.countDown();
}
}).subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.Original OnCompleted");
originalLatch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.Original OnError : " + e);
originalLatch.countDown();
}
@Override
public void onNext(Boolean b) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.Original OnNext : " + b);
originalValue.set(b);
}
});
Subscription fromCacheSubscription = fromCacheObservable.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.FromCache Unsubscribe");
fromCacheLatch.countDown();
}
}).subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.FromCache OnCompleted");
fromCacheLatch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.FromCache OnError : " + e);
fromCacheLatch.countDown();
}
@Override
public void onNext(Boolean b) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.FromCache OnNext : " + b);
fromCacheValue.set(b);
}
});
try {
Thread.sleep(10);
originalSubscription.unsubscribe();
assertTrue(originalLatch.await(600, TimeUnit.MILLISECONDS));
assertTrue(fromCacheLatch.await(600, TimeUnit.MILLISECONDS));
assertEquals("Number of execution semaphores in use (original)", 0, original.getExecutionSemaphore().getNumberOfPermitsUsed());
assertEquals("Number of fallback semaphores in use (original)", 0, original.getFallbackSemaphore().getNumberOfPermitsUsed());
assertFalse(original.isExecutionComplete());
assertTrue(original.isExecutedInThread());
assertEquals(null, original.getFailedExecutionException());
assertNull(original.getExecutionException());
assertTrue(original.getExecutionTimeInMilliseconds() > -1);
assertFalse(original.isSuccessfulExecution());
assertCommandExecutionEvents(original, HystrixEventType.CANCELLED);
assertNull(originalValue.get());
assertEquals(0, original.metrics.getCurrentConcurrentExecutionCount());
assertEquals("Number of execution semaphores in use (fromCache)", 0, fromCache.getExecutionSemaphore().getNumberOfPermitsUsed());
assertEquals("Number of fallback semaphores in use (fromCache)", 0, fromCache.getFallbackSemaphore().getNumberOfPermitsUsed());
assertTrue(fromCache.isExecutionComplete());
assertFalse(fromCache.isExecutedInThread());
assertEquals(null, fromCache.getFailedExecutionException());
assertNull(fromCache.getExecutionException());
assertCommandExecutionEvents(fromCache, HystrixEventType.SUCCESS, HystrixEventType.RESPONSE_FROM_CACHE);
assertTrue(fromCache.getExecutionTimeInMilliseconds() == -1);
assertTrue(fromCache.isSuccessfulExecution());
assertEquals(0, fromCache.metrics.getCurrentConcurrentExecutionCount());
assertFalse(original.isCancelled()); //underlying work
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertSaneHystrixRequestLog(2);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
@Test
public void testRequestThenTwoCacheHitsOriginalAndOneCacheHitUnsubscribed() {
AsyncCacheableCommand original = new AsyncCacheableCommand("foo");
AsyncCacheableCommand fromCache1 = new AsyncCacheableCommand("foo");
AsyncCacheableCommand fromCache2 = new AsyncCacheableCommand("foo");
final AtomicReference<Boolean> originalValue = new AtomicReference<Boolean>(null);
final AtomicReference<Boolean> fromCache1Value = new AtomicReference<Boolean>(null);
final AtomicReference<Boolean> fromCache2Value = new AtomicReference<Boolean>(null);
final CountDownLatch originalLatch = new CountDownLatch(1);
final CountDownLatch fromCache1Latch = new CountDownLatch(1);
final CountDownLatch fromCache2Latch = new CountDownLatch(1);
Observable<Boolean> originalObservable = original.toObservable();
Observable<Boolean> fromCache1Observable = fromCache1.toObservable();
Observable<Boolean> fromCache2Observable = fromCache2.toObservable();
Subscription originalSubscription = originalObservable.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.Original Unsubscribe");
originalLatch.countDown();
}
}).subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.Original OnCompleted");
originalLatch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.Original OnError : " + e);
originalLatch.countDown();
}
@Override
public void onNext(Boolean b) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.Original OnNext : " + b);
originalValue.set(b);
}
});
Subscription fromCache1Subscription = fromCache1Observable.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.FromCache1 Unsubscribe");
fromCache1Latch.countDown();
}
}).subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.FromCache1 OnCompleted");
fromCache1Latch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.FromCache1 OnError : " + e);
fromCache1Latch.countDown();
}
@Override
public void onNext(Boolean b) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.FromCache1 OnNext : " + b);
fromCache1Value.set(b);
}
});
Subscription fromCache2Subscription = fromCache2Observable.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.FromCache2 Unsubscribe");
fromCache2Latch.countDown();
}
}).subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.FromCache2 OnCompleted");
fromCache2Latch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.FromCache2 OnError : " + e);
fromCache2Latch.countDown();
}
@Override
public void onNext(Boolean b) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.FromCache2 OnNext : " + b);
fromCache2Value.set(b);
}
});
try {
Thread.sleep(10);
originalSubscription.unsubscribe();
//fromCache1Subscription.unsubscribe();
fromCache2Subscription.unsubscribe();
assertTrue(originalLatch.await(600, TimeUnit.MILLISECONDS));
assertTrue(fromCache1Latch.await(600, TimeUnit.MILLISECONDS));
assertTrue(fromCache2Latch.await(600, TimeUnit.MILLISECONDS));
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertEquals("Number of execution semaphores in use (original)", 0, original.getExecutionSemaphore().getNumberOfPermitsUsed());
assertEquals("Number of fallback semaphores in use (original)", 0, original.getFallbackSemaphore().getNumberOfPermitsUsed());
assertFalse(original.isExecutionComplete());
assertTrue(original.isExecutedInThread());
assertEquals(null, original.getFailedExecutionException());
assertNull(original.getExecutionException());
assertTrue(original.getExecutionTimeInMilliseconds() > -1);
assertFalse(original.isSuccessfulExecution());
assertCommandExecutionEvents(original, HystrixEventType.CANCELLED);
assertNull(originalValue.get());
assertFalse(original.isCancelled()); //underlying work
assertEquals(0, original.metrics.getCurrentConcurrentExecutionCount());
assertEquals("Number of execution semaphores in use (fromCache1)", 0, fromCache1.getExecutionSemaphore().getNumberOfPermitsUsed());
assertEquals("Number of fallback semaphores in use (fromCache1)", 0, fromCache1.getFallbackSemaphore().getNumberOfPermitsUsed());
assertTrue(fromCache1.isExecutionComplete());
assertFalse(fromCache1.isExecutedInThread());
assertEquals(null, fromCache1.getFailedExecutionException());
assertNull(fromCache1.getExecutionException());
assertCommandExecutionEvents(fromCache1, HystrixEventType.SUCCESS, HystrixEventType.RESPONSE_FROM_CACHE);
assertTrue(fromCache1.getExecutionTimeInMilliseconds() == -1);
assertTrue(fromCache1.isSuccessfulExecution());
assertTrue(fromCache1Value.get());
assertEquals(0, fromCache1.metrics.getCurrentConcurrentExecutionCount());
assertEquals("Number of execution semaphores in use (fromCache2)", 0, fromCache2.getExecutionSemaphore().getNumberOfPermitsUsed());
assertEquals("Number of fallback semaphores in use (fromCache2)", 0, fromCache2.getFallbackSemaphore().getNumberOfPermitsUsed());
assertFalse(fromCache2.isExecutionComplete());
assertFalse(fromCache2.isExecutedInThread());
assertEquals(null, fromCache2.getFailedExecutionException());
assertNull(fromCache2.getExecutionException());
assertCommandExecutionEvents(fromCache2, HystrixEventType.RESPONSE_FROM_CACHE, HystrixEventType.CANCELLED);
assertTrue(fromCache2.getExecutionTimeInMilliseconds() == -1);
assertFalse(fromCache2.isSuccessfulExecution());
assertNull(fromCache2Value.get());
assertEquals(0, fromCache2.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(3);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
@Test
public void testRequestThenTwoCacheHitsAllUnsubscribed() {
AsyncCacheableCommand original = new AsyncCacheableCommand("foo");
AsyncCacheableCommand fromCache1 = new AsyncCacheableCommand("foo");
AsyncCacheableCommand fromCache2 = new AsyncCacheableCommand("foo");
final CountDownLatch originalLatch = new CountDownLatch(1);
final CountDownLatch fromCache1Latch = new CountDownLatch(1);
final CountDownLatch fromCache2Latch = new CountDownLatch(1);
Observable<Boolean> originalObservable = original.toObservable();
Observable<Boolean> fromCache1Observable = fromCache1.toObservable();
Observable<Boolean> fromCache2Observable = fromCache2.toObservable();
Subscription originalSubscription = originalObservable.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.Original Unsubscribe");
originalLatch.countDown();
}
}).subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.Original OnCompleted");
originalLatch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.Original OnError : " + e);
originalLatch.countDown();
}
@Override
public void onNext(Boolean b) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.Original OnNext : " + b);
}
});
Subscription fromCache1Subscription = fromCache1Observable.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.FromCache1 Unsubscribe");
fromCache1Latch.countDown();
}
}).subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.FromCache1 OnCompleted");
fromCache1Latch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.FromCache1 OnError : " + e);
fromCache1Latch.countDown();
}
@Override
public void onNext(Boolean b) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.FromCache1 OnNext : " + b);
}
});
Subscription fromCache2Subscription = fromCache2Observable.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.FromCache2 Unsubscribe");
fromCache2Latch.countDown();
}
}).subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.FromCache2 OnCompleted");
fromCache2Latch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.FromCache2 OnError : " + e);
fromCache2Latch.countDown();
}
@Override
public void onNext(Boolean b) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Test.FromCache2 OnNext : " + b);
}
});
try {
Thread.sleep(10);
originalSubscription.unsubscribe();
fromCache1Subscription.unsubscribe();
fromCache2Subscription.unsubscribe();
assertTrue(originalLatch.await(200, TimeUnit.MILLISECONDS));
assertTrue(fromCache1Latch.await(200, TimeUnit.MILLISECONDS));
assertTrue(fromCache2Latch.await(200, TimeUnit.MILLISECONDS));
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertEquals("Number of execution semaphores in use (original)", 0, original.getExecutionSemaphore().getNumberOfPermitsUsed());
assertEquals("Number of fallback semaphores in use (original)", 0, original.getFallbackSemaphore().getNumberOfPermitsUsed());
assertFalse(original.isExecutionComplete());
assertTrue(original.isExecutedInThread());
System.out.println("FEE : " + original.getFailedExecutionException());
if (original.getFailedExecutionException() != null) {
original.getFailedExecutionException().printStackTrace();
}
assertNull(original.getFailedExecutionException());
assertNull(original.getExecutionException());
assertTrue(original.getExecutionTimeInMilliseconds() > -1);
assertFalse(original.isSuccessfulExecution());
assertCommandExecutionEvents(original, HystrixEventType.CANCELLED);
//assertTrue(original.isCancelled()); //underlying work This doesn't work yet
assertEquals(0, original.metrics.getCurrentConcurrentExecutionCount());
assertEquals("Number of execution semaphores in use (fromCache1)", 0, fromCache1.getExecutionSemaphore().getNumberOfPermitsUsed());
assertEquals("Number of fallback semaphores in use (fromCache1)", 0, fromCache1.getFallbackSemaphore().getNumberOfPermitsUsed());
assertFalse(fromCache1.isExecutionComplete());
assertFalse(fromCache1.isExecutedInThread());
assertEquals(null, fromCache1.getFailedExecutionException());
assertNull(fromCache1.getExecutionException());
assertCommandExecutionEvents(fromCache1, HystrixEventType.RESPONSE_FROM_CACHE, HystrixEventType.CANCELLED);
assertTrue(fromCache1.getExecutionTimeInMilliseconds() == -1);
assertFalse(fromCache1.isSuccessfulExecution());
assertEquals(0, fromCache1.metrics.getCurrentConcurrentExecutionCount());
assertEquals("Number of execution semaphores in use (fromCache2)", 0, fromCache2.getExecutionSemaphore().getNumberOfPermitsUsed());
assertEquals("Number of fallback semaphores in use (fromCache2)", 0, fromCache2.getFallbackSemaphore().getNumberOfPermitsUsed());
assertFalse(fromCache2.isExecutionComplete());
assertFalse(fromCache2.isExecutedInThread());
assertEquals(null, fromCache2.getFailedExecutionException());
assertNull(fromCache2.getExecutionException());
assertCommandExecutionEvents(fromCache2, HystrixEventType.RESPONSE_FROM_CACHE, HystrixEventType.CANCELLED);
assertTrue(fromCache2.getExecutionTimeInMilliseconds() == -1);
assertFalse(fromCache2.isSuccessfulExecution());
assertEquals(0, fromCache2.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(3);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
/**
* Some RxJava operators like take(n), zip receive data in an onNext from upstream and immediately unsubscribe.
* When upstream is a HystrixCommand, Hystrix may get that unsubscribe before it gets to its onCompleted.
* This should still be marked as a HystrixEventType.SUCCESS.
*/
@Test
public void testUnsubscribingDownstreamOperatorStillResultsInSuccessEventType() throws InterruptedException {
HystrixCommand<Integer> cmd = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 100, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED);
Observable<Integer> o = cmd.toObservable()
.doOnNext(new Action1<Integer>() {
@Override
public void call(Integer i) {
System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis() + " CMD OnNext : " + i);
}
})
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis() + " CMD OnError : " + throwable);
}
})
.doOnCompleted(new Action0() {
@Override
public void call() {
System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis() + " CMD OnCompleted");
}
})
.doOnSubscribe(new Action0() {
@Override
public void call() {
System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis() + " CMD OnSubscribe");
}
})
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis() + " CMD OnUnsubscribe");
}
})
.take(1)
.observeOn(Schedulers.io())
.map(new Func1<Integer, Integer>() {
@Override
public Integer call(Integer i) {
System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis() + " : Doing some more computation in the onNext!!");
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
return i;
}
});
final CountDownLatch latch = new CountDownLatch(1);
o.doOnSubscribe(new Action0() {
@Override
public void call() {
System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis() + " : OnSubscribe");
}
}).doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis() + " : OnUnsubscribe");
}
}).subscribe(new Subscriber<Integer>() {
@Override
public void onCompleted() {
System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis() + " : OnCompleted");
latch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis() + " : OnError : " + e);
latch.countDown();
}
@Override
public void onNext(Integer i) {
System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis() + " : OnNext : " + i);
}
});
latch.await(1000, TimeUnit.MILLISECONDS);
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertTrue(cmd.isExecutedInThread());
assertCommandExecutionEvents(cmd, HystrixEventType.SUCCESS);
}
@Test
public void testUnsubscribeBeforeSubscribe() throws Exception {
//this may happen in Observable chain, so Hystrix should make sure that command never executes/allocates in this situation
Observable<String> error = Observable.error(new RuntimeException("foo"));
HystrixCommand<Integer> cmd = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 100);
Observable<Integer> cmdResult = cmd.toObservable()
.doOnNext(new Action1<Integer>() {
@Override
public void call(Integer integer) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : OnNext : " + integer);
}
})
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable ex) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : OnError : " + ex);
}
})
.doOnCompleted(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : OnCompleted");
}
})
.doOnSubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : OnSubscribe");
}
})
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : OnUnsubscribe");
}
});
//the zip operator will subscribe to each observable. there is a race between the error of the first
//zipped observable terminating the zip and the subscription to the command's observable
Observable<String> zipped = Observable.zip(error, cmdResult, new Func2<String, Integer, String>() {
@Override
public String call(String s, Integer integer) {
return s + integer;
}
});
final CountDownLatch latch = new CountDownLatch(1);
zipped.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " OnCompleted");
latch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " OnError : " + e);
latch.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " OnNext : " + s);
}
});
latch.await(1000, TimeUnit.MILLISECONDS);
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
}
@Test
public void testRxRetry() throws Exception {
// see https://github.com/Netflix/Hystrix/issues/1100
// Since each command instance is single-use, the expectation is that applying the .retry() operator
// results in only a single execution and propagation out of that error
HystrixCommand<Integer> cmd = getLatentCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.FAILURE, 300,
AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED, 100);
final CountDownLatch latch = new CountDownLatch(1);
System.out.println(System.currentTimeMillis() + " : Starting");
Observable<Integer> o = cmd.toObservable().retry(2);
System.out.println(System.currentTimeMillis() + " Created retried command : " + o);
o.subscribe(new Subscriber<Integer>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : OnCompleted");
latch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : OnError : " + e);
latch.countDown();
}
@Override
public void onNext(Integer integer) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : OnNext : " + integer);
}
});
latch.await(1000, TimeUnit.MILLISECONDS);
System.out.println(System.currentTimeMillis() + " ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
}
/**
*********************** THREAD-ISOLATED Execution Hook Tests **************************************
*/
/**
* Short-circuit? : NO
* Thread/semaphore: THREAD
* Thread Pool full? : NO
* Thread Pool Queue full?: NO
* Timeout: NO
* Execution Result: SUCCESS
*/
@Test
public void testExecutionHookThreadSuccess() {
assertHooksOnSuccess(
new Func0<TestHystrixCommand<Integer>>() {
@Override
public TestHystrixCommand<Integer> call() {
return getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS);
}
},
new Action1<TestHystrixCommand<Integer>>() {
@Override
public void call(TestHystrixCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(1, 0, 1));
assertTrue(hook.executionEventsMatch(1, 0, 1));
assertTrue(hook.fallbackEventsMatch(0, 0, 0));
assertEquals("onStart - onThreadStart - !onRunStart - onExecutionStart - onExecutionEmit - !onRunSuccess - !onComplete - onEmit - onExecutionSuccess - onThreadComplete - onSuccess - ", hook.executionSequence.toString());
}
});
}
@Test
public void testExecutionHookEarlyUnsubscribe() {
System.out.println("Running command.observe(), awaiting terminal state of Observable, then running assertions...");
final CountDownLatch latch = new CountDownLatch(1);
TestHystrixCommand<Integer> command = getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 1000);
Observable<Integer> o = command.observe();
Subscription s = o.
doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : OnUnsubscribe");
latch.countDown();
}
}).
subscribe(new Subscriber<Integer>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : OnCompleted");
latch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : OnError : " + e);
latch.countDown();
}
@Override
public void onNext(Integer i) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : OnNext : " + i);
}
});
try {
Thread.sleep(15);
s.unsubscribe();
latch.await(3, TimeUnit.SECONDS);
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 0, 0));
assertTrue(hook.executionEventsMatch(0, 0, 0));
assertTrue(hook.fallbackEventsMatch(0, 0, 0));
assertEquals("onStart - onThreadStart - !onRunStart - onExecutionStart - onUnsubscribe - onThreadComplete - ", hook.executionSequence.toString());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Short-circuit? : NO
* Thread/semaphore: THREAD
* Thread Pool full? : NO
* Thread Pool Queue full?: NO
* Timeout: NO
* Execution Result: synchronous HystrixBadRequestException
*/
@Test
public void testExecutionHookThreadBadRequestException() {
assertHooksOnFailure(
new Func0<TestHystrixCommand<Integer>>() {
@Override
public TestHystrixCommand<Integer> call() {
return getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.BAD_REQUEST);
}
},
new Action1<TestHystrixCommand<Integer>>() {
@Override
public void call(TestHystrixCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 1, 0));
assertTrue(hook.fallbackEventsMatch(0, 0, 0));
assertEquals(HystrixBadRequestException.class, hook.getCommandException().getClass());
assertEquals(HystrixBadRequestException.class, hook.getExecutionException().getClass());
assertEquals("onStart - onThreadStart - !onRunStart - onExecutionStart - onExecutionError - !onRunError - onThreadComplete - onError - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : NO
* Thread/semaphore: THREAD
* Thread Pool full? : NO
* Thread Pool Queue full?: NO
* Timeout: NO
* Execution Result: synchronous HystrixRuntimeException
* Fallback: UnsupportedOperationException
*/
@Test
public void testExecutionHookThreadExceptionNoFallback() {
assertHooksOnFailure(
new Func0<TestHystrixCommand<Integer>>() {
@Override
public TestHystrixCommand<Integer> call() {
return getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.FAILURE, 0, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED);
}
},
new Action1<TestHystrixCommand<Integer>>() {
@Override
public void call(TestHystrixCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 1, 0));
assertTrue(hook.fallbackEventsMatch(0, 0, 0));
assertEquals(RuntimeException.class, hook.getCommandException().getClass());
assertEquals(RuntimeException.class, hook.getExecutionException().getClass());
assertNull(hook.getFallbackException());
assertEquals("onStart - onThreadStart - !onRunStart - onExecutionStart - onExecutionError - !onRunError - onThreadComplete - onError - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : NO
* Thread/semaphore: THREAD
* Thread Pool full? : NO
* Thread Pool Queue full?: NO
* Timeout: NO
* Execution Result: synchronous HystrixRuntimeException
* Fallback: SUCCESS
*/
@Test
public void testExecutionHookThreadExceptionSuccessfulFallback() {
assertHooksOnSuccess(
new Func0<TestHystrixCommand<Integer>>() {
@Override
public TestHystrixCommand<Integer> call() {
return getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.FAILURE, 0, AbstractTestHystrixCommand.FallbackResult.SUCCESS);
}
},
new Action1<TestHystrixCommand<Integer>>() {
@Override
public void call(TestHystrixCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(1, 0, 1));
assertTrue(hook.executionEventsMatch(0, 1, 0));
assertTrue(hook.fallbackEventsMatch(1, 0, 1));
assertEquals(RuntimeException.class, hook.getExecutionException().getClass());
assertEquals("onStart - onThreadStart - !onRunStart - onExecutionStart - onExecutionError - !onRunError - onThreadComplete - onFallbackStart - onFallbackEmit - !onFallbackSuccess - !onComplete - onEmit - onFallbackSuccess - onSuccess - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : NO
* Thread/semaphore: THREAD
* Thread Pool full? : NO
* Thread Pool Queue full?: NO
* Timeout: NO
* Execution Result: synchronous HystrixRuntimeException
* Fallback: HystrixRuntimeException
*/
@Test
public void testExecutionHookThreadExceptionUnsuccessfulFallback() {
assertHooksOnFailure(
new Func0<TestHystrixCommand<Integer>>() {
@Override
public TestHystrixCommand<Integer> call() {
return getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.FAILURE, 0, AbstractTestHystrixCommand.FallbackResult.FAILURE);
}
},
new Action1<TestHystrixCommand<Integer>>() {
@Override
public void call(TestHystrixCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 1, 0));
assertTrue(hook.fallbackEventsMatch(0, 1, 0));
assertEquals(RuntimeException.class, hook.getCommandException().getClass());
assertEquals(RuntimeException.class, hook.getExecutionException().getClass());
assertEquals(RuntimeException.class, hook.getFallbackException().getClass());
assertEquals("onStart - onThreadStart - !onRunStart - onExecutionStart - onExecutionError - !onRunError - onThreadComplete - onFallbackStart - onFallbackError - onError - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : NO
* Thread/semaphore: THREAD
* Thread Pool full? : NO
* Thread Pool Queue full?: NO
* Timeout: YES
* Execution Result: SUCCESS (but timeout prior)
* Fallback: UnsupportedOperationException
*/
@Test
public void testExecutionHookThreadTimeoutNoFallbackRunSuccess() {
assertHooksOnFailure(
new Func0<TestHystrixCommand<Integer>>() {
@Override
public TestHystrixCommand<Integer> call() {
return getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 500, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED, 200);
}
},
new Action1<TestHystrixCommand<Integer>>() {
@Override
public void call(TestHystrixCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 0, 0));
assertTrue(hook.fallbackEventsMatch(0, 0, 0));
assertEquals(TimeoutException.class, hook.getCommandException().getClass());
assertNull(hook.getFallbackException());
System.out.println("RequestLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertEquals("onStart - onThreadStart - !onRunStart - onExecutionStart - onThreadComplete - onError - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : NO
* Thread/semaphore: THREAD
* Thread Pool full? : NO
* Thread Pool Queue full?: NO
* Timeout: YES
* Execution Result: SUCCESS (but timeout prior)
* Fallback: SUCCESS
*/
@Test
public void testExecutionHookThreadTimeoutSuccessfulFallbackRunSuccess() {
assertHooksOnSuccess(
new Func0<TestHystrixCommand<Integer>>() {
@Override
public TestHystrixCommand<Integer> call() {
return getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 500, AbstractTestHystrixCommand.FallbackResult.SUCCESS, 200);
}
},
new Action1<TestHystrixCommand<Integer>>() {
@Override
public void call(TestHystrixCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(1, 0, 1));
assertTrue(hook.executionEventsMatch(0, 0, 0));
assertTrue(hook.fallbackEventsMatch(1, 0, 1));
System.out.println("RequestLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertEquals("onStart - onThreadStart - !onRunStart - onExecutionStart - onThreadComplete - onFallbackStart - onFallbackEmit - !onFallbackSuccess - !onComplete - onEmit - onFallbackSuccess - onSuccess - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : NO
* Thread/semaphore: THREAD
* Thread Pool full? : NO
* Thread Pool Queue full?: NO
* Timeout: YES
* Execution Result: SUCCESS (but timeout prior)
* Fallback: synchronous HystrixRuntimeException
*/
@Test
public void testExecutionHookThreadTimeoutUnsuccessfulFallbackRunSuccess() {
assertHooksOnFailure(
new Func0<TestHystrixCommand<Integer>>() {
@Override
public TestHystrixCommand<Integer> call() {
return getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 500, AbstractTestHystrixCommand.FallbackResult.FAILURE, 200);
}
},
new Action1<TestHystrixCommand<Integer>>() {
@Override
public void call(TestHystrixCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 0, 0));
assertTrue(hook.fallbackEventsMatch(0, 1, 0));
assertEquals(TimeoutException.class, hook.getCommandException().getClass());
assertEquals(RuntimeException.class, hook.getFallbackException().getClass());
assertEquals("onStart - onThreadStart - !onRunStart - onExecutionStart - onThreadComplete - onFallbackStart - onFallbackError - onError - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : NO
* Thread/semaphore: THREAD
* Thread Pool full? : NO
* Thread Pool Queue full?: NO
* Timeout: YES
* Execution Result: HystrixRuntimeException (but timeout prior)
* Fallback: UnsupportedOperationException
*/
@Test
public void testExecutionHookThreadTimeoutNoFallbackRunFailure() {
assertHooksOnFailure(
new Func0<TestHystrixCommand<Integer>>() {
@Override
public TestHystrixCommand<Integer> call() {
return getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.FAILURE, 500, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED, 200);
}
},
new Action1<TestHystrixCommand<Integer>>() {
@Override
public void call(TestHystrixCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 0, 0));
assertTrue(hook.fallbackEventsMatch(0, 0, 0));
assertEquals(TimeoutException.class, hook.getCommandException().getClass());
assertNull(hook.getFallbackException());
assertEquals("onStart - onThreadStart - !onRunStart - onExecutionStart - onThreadComplete - onError - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : NO
* Thread/semaphore: THREAD
* Thread Pool full? : NO
* Thread Pool Queue full?: NO
* Timeout: YES
* Execution Result: HystrixRuntimeException (but timeout prior)
* Fallback: SUCCESS
*/
@Test
public void testExecutionHookThreadTimeoutSuccessfulFallbackRunFailure() {
assertHooksOnSuccess(
new Func0<TestHystrixCommand<Integer>>() {
@Override
public TestHystrixCommand<Integer> call() {
return getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.FAILURE, 500, AbstractTestHystrixCommand.FallbackResult.SUCCESS, 200);
}
},
new Action1<TestHystrixCommand<Integer>>() {
@Override
public void call(TestHystrixCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertTrue(hook.commandEmissionsMatch(1, 0, 1));
assertTrue(hook.executionEventsMatch(0, 0, 0));
assertTrue(hook.fallbackEventsMatch(1, 0, 1));
assertEquals("onStart - onThreadStart - !onRunStart - onExecutionStart - onThreadComplete - onFallbackStart - onFallbackEmit - !onFallbackSuccess - !onComplete - onEmit - onFallbackSuccess - onSuccess - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : NO
* Thread/semaphore: THREAD
* Thread Pool full? : NO
* Thread Pool Queue full?: NO
* Timeout: YES
* Execution Result: HystrixRuntimeException (but timeout prior)
* Fallback: synchronous HystrixRuntimeException
*/
@Test
public void testExecutionHookThreadTimeoutUnsuccessfulFallbackRunFailure() {
assertHooksOnFailure(
new Func0<TestHystrixCommand<Integer>>() {
@Override
public TestHystrixCommand<Integer> call() {
return getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.FAILURE, 500, AbstractTestHystrixCommand.FallbackResult.FAILURE, 200);
}
},
new Action1<TestHystrixCommand<Integer>>() {
@Override
public void call(TestHystrixCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 0, 0));
assertTrue(hook.fallbackEventsMatch(0, 1, 0));
assertEquals(TimeoutException.class, hook.getCommandException().getClass());
assertEquals(RuntimeException.class, hook.getFallbackException().getClass());
assertEquals("onStart - onThreadStart - !onRunStart - onExecutionStart - onThreadComplete - onFallbackStart - onFallbackError - onError - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : NO
* Thread/semaphore: THREAD
* Thread Pool full? : YES
* Thread Pool Queue full?: YES
* Fallback: UnsupportedOperationException
*/
@Test
public void testExecutionHookThreadPoolQueueFullNoFallback() {
assertHooksOnFailFast(
new Func0<TestHystrixCommand<Integer>>() {
@Override
public TestHystrixCommand<Integer> call() {
HystrixCircuitBreakerTest.TestCircuitBreaker circuitBreaker = new HystrixCircuitBreakerTest.TestCircuitBreaker();
HystrixThreadPool pool = new SingleThreadedPoolWithQueue(1);
try {
// fill the pool
getLatentCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 500, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED, circuitBreaker, pool, 600).observe();
// fill the queue
getLatentCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 500, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED, circuitBreaker, pool, 600).observe();
} catch (Exception e) {
// ignore
}
return getLatentCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 500, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED, circuitBreaker, pool, 600);
}
},
new Action1<TestHystrixCommand<Integer>>() {
@Override
public void call(TestHystrixCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 0, 0));
assertTrue(hook.fallbackEventsMatch(0, 0, 0));
assertEquals(RejectedExecutionException.class, hook.getCommandException().getClass());
assertNull(hook.getFallbackException());
assertEquals("onStart - onError - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : NO
* Thread/semaphore: THREAD
* Thread Pool full? : YES
* Thread Pool Queue full?: YES
* Fallback: SUCCESS
*/
@Test
public void testExecutionHookThreadPoolQueueFullSuccessfulFallback() {
assertHooksOnSuccess(
new Func0<TestHystrixCommand<Integer>>() {
@Override
public TestHystrixCommand<Integer> call() {
HystrixCircuitBreakerTest.TestCircuitBreaker circuitBreaker = new HystrixCircuitBreakerTest.TestCircuitBreaker();
HystrixThreadPool pool = new SingleThreadedPoolWithQueue(1);
try {
// fill the pool
getLatentCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 500, AbstractTestHystrixCommand.FallbackResult.SUCCESS, circuitBreaker, pool, 600).observe();
// fill the queue
getLatentCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 500, AbstractTestHystrixCommand.FallbackResult.SUCCESS, circuitBreaker, pool, 600).observe();
} catch (Exception e) {
// ignore
}
return getLatentCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 500, AbstractTestHystrixCommand.FallbackResult.SUCCESS, circuitBreaker, pool, 600);
}
},
new Action1<TestHystrixCommand<Integer>>() {
@Override
public void call(TestHystrixCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(1, 0, 1));
assertTrue(hook.executionEventsMatch(0, 0, 0));
assertTrue(hook.fallbackEventsMatch(1, 0, 1));
assertEquals("onStart - onFallbackStart - onFallbackEmit - !onFallbackSuccess - !onComplete - onEmit - onFallbackSuccess - onSuccess - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : NO
* Thread/semaphore: THREAD
* Thread Pool full? : YES
* Thread Pool Queue full?: YES
* Fallback: synchronous HystrixRuntimeException
*/
@Test
public void testExecutionHookThreadPoolQueueFullUnsuccessfulFallback() {
assertHooksOnFailFast(
new Func0<TestHystrixCommand<Integer>>() {
@Override
public TestHystrixCommand<Integer> call() {
HystrixCircuitBreakerTest.TestCircuitBreaker circuitBreaker = new HystrixCircuitBreakerTest.TestCircuitBreaker();
HystrixThreadPool pool = new SingleThreadedPoolWithQueue(1);
try {
// fill the pool
getLatentCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 500, AbstractTestHystrixCommand.FallbackResult.FAILURE, circuitBreaker, pool, 600).observe();
// fill the queue
getLatentCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 500, AbstractTestHystrixCommand.FallbackResult.FAILURE, circuitBreaker, pool, 600).observe();
} catch (Exception e) {
// ignore
}
return getLatentCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 500, AbstractTestHystrixCommand.FallbackResult.FAILURE, circuitBreaker, pool, 600);
}
},
new Action1<TestHystrixCommand<Integer>>() {
@Override
public void call(TestHystrixCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 0, 0));
assertTrue(hook.fallbackEventsMatch(0, 1, 0));
assertEquals(RejectedExecutionException.class, hook.getCommandException().getClass());
assertEquals(RuntimeException.class, hook.getFallbackException().getClass());
assertEquals("onStart - onFallbackStart - onFallbackError - onError - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : NO
* Thread/semaphore: THREAD
* Thread Pool full? : YES
* Thread Pool Queue full?: N/A
* Fallback: UnsupportedOperationException
*/
@Test
public void testExecutionHookThreadPoolFullNoFallback() {
assertHooksOnFailFast(
new Func0<TestHystrixCommand<Integer>>() {
@Override
public TestHystrixCommand<Integer> call() {
HystrixCircuitBreakerTest.TestCircuitBreaker circuitBreaker = new HystrixCircuitBreakerTest.TestCircuitBreaker();
HystrixThreadPool pool = new SingleThreadedPoolWithNoQueue();
try {
// fill the pool
getLatentCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 500, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED, circuitBreaker, pool, 600).observe();
} catch (Exception e) {
// ignore
}
return getLatentCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 500, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED, circuitBreaker, pool, 600);
}
},
new Action1<TestHystrixCommand<Integer>>() {
@Override
public void call(TestHystrixCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 0, 0));
assertTrue(hook.fallbackEventsMatch(0, 0, 0));
assertEquals(RejectedExecutionException.class, hook.getCommandException().getClass());
assertNull(hook.getFallbackException());
assertEquals("onStart - onError - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : NO
* Thread/semaphore: THREAD
* Thread Pool full? : YES
* Thread Pool Queue full?: N/A
* Fallback: SUCCESS
*/
@Test
public void testExecutionHookThreadPoolFullSuccessfulFallback() {
assertHooksOnSuccess(
new Func0<TestHystrixCommand<Integer>>() {
@Override
public TestHystrixCommand<Integer> call() {
HystrixCircuitBreakerTest.TestCircuitBreaker circuitBreaker = new HystrixCircuitBreakerTest.TestCircuitBreaker();
HystrixThreadPool pool = new SingleThreadedPoolWithNoQueue();
try {
// fill the pool
getLatentCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 500, AbstractTestHystrixCommand.FallbackResult.SUCCESS, circuitBreaker, pool, 600).observe();
} catch (Exception e) {
// ignore
}
return getLatentCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 500, AbstractTestHystrixCommand.FallbackResult.SUCCESS, circuitBreaker, pool, 600);
}
},
new Action1<TestHystrixCommand<Integer>>() {
@Override
public void call(TestHystrixCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(1, 0, 1));
assertTrue(hook.executionEventsMatch(0, 0, 0));
assertEquals("onStart - onFallbackStart - onFallbackEmit - !onFallbackSuccess - !onComplete - onEmit - onFallbackSuccess - onSuccess - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : NO
* Thread/semaphore: THREAD
* Thread Pool full? : YES
* Thread Pool Queue full?: N/A
* Fallback: synchronous HystrixRuntimeException
*/
@Test
public void testExecutionHookThreadPoolFullUnsuccessfulFallback() {
assertHooksOnFailFast(
new Func0<TestHystrixCommand<Integer>>() {
@Override
public TestHystrixCommand<Integer> call() {
HystrixCircuitBreakerTest.TestCircuitBreaker circuitBreaker = new HystrixCircuitBreakerTest.TestCircuitBreaker();
HystrixThreadPool pool = new SingleThreadedPoolWithNoQueue();
try {
// fill the pool
getLatentCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 500, AbstractTestHystrixCommand.FallbackResult.FAILURE, circuitBreaker, pool, 600).observe();
} catch (Exception e) {
// ignore
}
return getLatentCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 500, AbstractTestHystrixCommand.FallbackResult.FAILURE, circuitBreaker, pool, 600);
}
},
new Action1<TestHystrixCommand<Integer>>() {
@Override
public void call(TestHystrixCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 0, 0));
assertTrue(hook.fallbackEventsMatch(0, 1, 0));
assertEquals(RejectedExecutionException.class, hook.getCommandException().getClass());
assertEquals(RuntimeException.class, hook.getFallbackException().getClass());
assertEquals("onStart - onFallbackStart - onFallbackError - onError - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : YES
* Thread/semaphore: THREAD
* Fallback: UnsupportedOperationException
*/
@Test
public void testExecutionHookThreadShortCircuitNoFallback() {
assertHooksOnFailFast(
new Func0<TestHystrixCommand<Integer>>() {
@Override
public TestHystrixCommand<Integer> call() {
return getCircuitOpenCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED);
}
},
new Action1<TestHystrixCommand<Integer>>() {
@Override
public void call(TestHystrixCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 0, 0));
assertTrue(hook.fallbackEventsMatch(0, 0, 0));
assertEquals(RuntimeException.class, hook.getCommandException().getClass());
assertNull(hook.getFallbackException());
assertEquals("onStart - onError - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : YES
* Thread/semaphore: THREAD
* Fallback: SUCCESS
*/
@Test
public void testExecutionHookThreadShortCircuitSuccessfulFallback() {
assertHooksOnSuccess(
new Func0<TestHystrixCommand<Integer>>() {
@Override
public TestHystrixCommand<Integer> call() {
return getCircuitOpenCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.FallbackResult.SUCCESS);
}
},
new Action1<TestHystrixCommand<Integer>>() {
@Override
public void call(TestHystrixCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(1, 0, 1));
assertTrue(hook.executionEventsMatch(0, 0, 0));
assertTrue(hook.fallbackEventsMatch(1, 0, 1));
assertEquals("onStart - onFallbackStart - onFallbackEmit - !onFallbackSuccess - !onComplete - onEmit - onFallbackSuccess - onSuccess - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : YES
* Thread/semaphore: THREAD
* Fallback: synchronous HystrixRuntimeException
*/
@Test
public void testExecutionHookThreadShortCircuitUnsuccessfulFallback() {
assertHooksOnFailFast(
new Func0<TestHystrixCommand<Integer>>() {
@Override
public TestHystrixCommand<Integer> call() {
HystrixCircuitBreakerTest.TestCircuitBreaker circuitBreaker = new HystrixCircuitBreakerTest.TestCircuitBreaker().setForceShortCircuit(true);
return getCircuitOpenCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.FallbackResult.FAILURE);
}
},
new Action1<TestHystrixCommand<Integer>>() {
@Override
public void call(TestHystrixCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 0, 0));
assertTrue(hook.fallbackEventsMatch(0, 1, 0));
assertEquals(RuntimeException.class, hook.getCommandException().getClass());
assertEquals(RuntimeException.class, hook.getFallbackException().getClass());
assertEquals("onStart - onFallbackStart - onFallbackError - onError - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : NO
* Request-cache? : YES
*/
@Test
public void testExecutionHookResponseFromCache() {
final HystrixCommandKey key = HystrixCommandKey.Factory.asKey("Hook-Cache");
getCommand(key, ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 0, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED, 0, new HystrixCircuitBreakerTest.TestCircuitBreaker(), null, 100, AbstractTestHystrixCommand.CacheEnabled.YES, 42, 10, 10).observe();
assertHooksOnSuccess(
new Func0<TestHystrixCommand<Integer>>() {
@Override
public TestHystrixCommand<Integer> call() {
return getCommand(key, ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 0, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED, 0, new HystrixCircuitBreakerTest.TestCircuitBreaker(), null, 100, AbstractTestHystrixCommand.CacheEnabled.YES, 42, 10, 10);
}
},
new Action1<TestHystrixCommand<Integer>>() {
@Override
public void call(TestHystrixCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 0, 0));
assertTrue(hook.executionEventsMatch(0, 0, 0));
assertTrue(hook.fallbackEventsMatch(0, 0, 0));
assertEquals("onCacheHit - ", hook.executionSequence.toString());
}
});
}
/**
*********************** END THREAD-ISOLATED Execution Hook Tests **************************************
*/
/* ******************************************************************************** */
/* ******************************************************************************** */
/* private HystrixCommand class implementations for unit testing */
/* ******************************************************************************** */
/* ******************************************************************************** */
static AtomicInteger uniqueNameCounter = new AtomicInteger(1);
@Override
TestHystrixCommand<Integer> getCommand(ExecutionIsolationStrategy isolationStrategy, AbstractTestHystrixCommand.ExecutionResult executionResult, int executionLatency, AbstractTestHystrixCommand.FallbackResult fallbackResult, int fallbackLatency, TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int timeout, AbstractTestHystrixCommand.CacheEnabled cacheEnabled, Object value, TryableSemaphore executionSemaphore, TryableSemaphore fallbackSemaphore, boolean circuitBreakerDisabled) {
HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey("Flexible-" + uniqueNameCounter.getAndIncrement());
return FlexibleTestHystrixCommand.from(commandKey, isolationStrategy, executionResult, executionLatency, fallbackResult, fallbackLatency, circuitBreaker, threadPool, timeout, cacheEnabled, value, executionSemaphore, fallbackSemaphore, circuitBreakerDisabled);
}
@Override
TestHystrixCommand<Integer> getCommand(HystrixCommandKey commandKey, ExecutionIsolationStrategy isolationStrategy, AbstractTestHystrixCommand.ExecutionResult executionResult, int executionLatency, AbstractTestHystrixCommand.FallbackResult fallbackResult, int fallbackLatency, TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int timeout, AbstractTestHystrixCommand.CacheEnabled cacheEnabled, Object value, TryableSemaphore executionSemaphore, TryableSemaphore fallbackSemaphore, boolean circuitBreakerDisabled) {
return FlexibleTestHystrixCommand.from(commandKey, isolationStrategy, executionResult, executionLatency, fallbackResult, fallbackLatency, circuitBreaker, threadPool, timeout, cacheEnabled, value, executionSemaphore, fallbackSemaphore, circuitBreakerDisabled);
}
private static class FlexibleTestHystrixCommand {
public static Integer EXECUTE_VALUE = 1;
public static Integer FALLBACK_VALUE = 11;
public static AbstractFlexibleTestHystrixCommand from(HystrixCommandKey commandKey, ExecutionIsolationStrategy isolationStrategy, AbstractTestHystrixCommand.ExecutionResult executionResult, int executionLatency, AbstractTestHystrixCommand.FallbackResult fallbackResult, int fallbackLatency, TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int timeout, AbstractTestHystrixCommand.CacheEnabled cacheEnabled, Object value, TryableSemaphore executionSemaphore, TryableSemaphore fallbackSemaphore, boolean circuitBreakerDisabled) {
if (fallbackResult.equals(AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED)) {
return new FlexibleTestHystrixCommandNoFallback(commandKey, isolationStrategy, executionResult, executionLatency, circuitBreaker, threadPool, timeout, cacheEnabled, value, executionSemaphore, fallbackSemaphore, circuitBreakerDisabled);
} else {
return new FlexibleTestHystrixCommandWithFallback(commandKey, isolationStrategy, executionResult, executionLatency, fallbackResult, fallbackLatency, circuitBreaker, threadPool, timeout, cacheEnabled, value, executionSemaphore, fallbackSemaphore, circuitBreakerDisabled);
}
}
}
private static class AbstractFlexibleTestHystrixCommand extends TestHystrixCommand<Integer> {
protected final AbstractTestHystrixCommand.ExecutionResult executionResult;
protected final int executionLatency;
protected final CacheEnabled cacheEnabled;
protected final Object value;
AbstractFlexibleTestHystrixCommand(HystrixCommandKey commandKey, ExecutionIsolationStrategy isolationStrategy, AbstractTestHystrixCommand.ExecutionResult executionResult, int executionLatency, TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int timeout, CacheEnabled cacheEnabled, Object value, TryableSemaphore executionSemaphore, TryableSemaphore fallbackSemaphore, boolean circuitBreakerDisabled) {
super(testPropsBuilder(circuitBreaker)
.setCommandKey(commandKey)
.setCircuitBreaker(circuitBreaker)
.setMetrics(circuitBreaker.metrics)
.setThreadPool(threadPool)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter()
.withExecutionIsolationStrategy(isolationStrategy)
.withExecutionTimeoutInMilliseconds(timeout)
.withCircuitBreakerEnabled(!circuitBreakerDisabled))
.setExecutionSemaphore(executionSemaphore)
.setFallbackSemaphore(fallbackSemaphore));
this.executionResult = executionResult;
this.executionLatency = executionLatency;
this.cacheEnabled = cacheEnabled;
this.value = value;
}
@Override
protected Integer run() throws Exception {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " starting the run() method");
addLatency(executionLatency);
if (executionResult == AbstractTestHystrixCommand.ExecutionResult.SUCCESS) {
return FlexibleTestHystrixCommand.EXECUTE_VALUE;
} else if (executionResult == AbstractTestHystrixCommand.ExecutionResult.FAILURE) {
throw new RuntimeException("Execution Failure for TestHystrixCommand");
} else if (executionResult == AbstractTestHystrixCommand.ExecutionResult.NOT_WRAPPED_FAILURE) {
throw new NotWrappedByHystrixTestRuntimeException();
} else if (executionResult == AbstractTestHystrixCommand.ExecutionResult.HYSTRIX_FAILURE) {
throw new HystrixRuntimeException(HystrixRuntimeException.FailureType.COMMAND_EXCEPTION, AbstractFlexibleTestHystrixCommand.class, "Execution Hystrix Failure for TestHystrixCommand", new RuntimeException("Execution Failure for TestHystrixCommand"), new RuntimeException("Fallback Failure for TestHystrixCommand"));
} else if (executionResult == AbstractTestHystrixCommand.ExecutionResult.RECOVERABLE_ERROR) {
throw new java.lang.Error("Execution ERROR for TestHystrixCommand");
} else if (executionResult == AbstractTestHystrixCommand.ExecutionResult.UNRECOVERABLE_ERROR) {
throw new StackOverflowError("Unrecoverable Error for TestHystrixCommand");
} else if (executionResult == AbstractTestHystrixCommand.ExecutionResult.BAD_REQUEST) {
throw new HystrixBadRequestException("Execution BadRequestException for TestHystrixCommand");
} else if (executionResult == AbstractTestHystrixCommand.ExecutionResult.BAD_REQUEST_NOT_WRAPPED) {
throw new HystrixBadRequestException("Execution BadRequestException for TestHystrixCommand", new NotWrappedByHystrixTestRuntimeException());
} else {
throw new RuntimeException("You passed in a executionResult enum that can't be represented in HystrixCommand: " + executionResult);
}
}
@Override
public String getCacheKey() {
if (cacheEnabled == CacheEnabled.YES)
return value.toString();
else
return null;
}
protected void addLatency(int latency) {
if (latency > 0) {
try {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " About to sleep for : " + latency);
Thread.sleep(latency);
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Woke up from sleep!");
} catch (InterruptedException e) {
e.printStackTrace();
// ignore and sleep some more to simulate a dependency that doesn't obey interrupts
try {
Thread.sleep(latency);
} catch (Exception e2) {
// ignore
}
System.out.println("after interruption with extra sleep");
}
}
}
}
private static class FlexibleTestHystrixCommandWithFallback extends AbstractFlexibleTestHystrixCommand {
protected final AbstractTestHystrixCommand.FallbackResult fallbackResult;
protected final int fallbackLatency;
FlexibleTestHystrixCommandWithFallback(HystrixCommandKey commandKey, ExecutionIsolationStrategy isolationStrategy, AbstractTestHystrixCommand.ExecutionResult executionResult, int executionLatency, FallbackResult fallbackResult, int fallbackLatency, TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int timeout, CacheEnabled cacheEnabled, Object value, TryableSemaphore executionSemaphore, TryableSemaphore fallbackSemaphore, boolean circuitBreakerDisabled) {
super(commandKey, isolationStrategy, executionResult, executionLatency, circuitBreaker, threadPool, timeout, cacheEnabled, value, executionSemaphore, fallbackSemaphore, circuitBreakerDisabled);
this.fallbackResult = fallbackResult;
this.fallbackLatency = fallbackLatency;
}
@Override
protected Integer getFallback() {
addLatency(fallbackLatency);
if (fallbackResult == AbstractTestHystrixCommand.FallbackResult.SUCCESS) {
return FlexibleTestHystrixCommand.FALLBACK_VALUE;
} else if (fallbackResult == AbstractTestHystrixCommand.FallbackResult.FAILURE) {
throw new RuntimeException("Fallback Failure for TestHystrixCommand");
} else if (fallbackResult == FallbackResult.UNIMPLEMENTED) {
return super.getFallback();
} else {
throw new RuntimeException("You passed in a fallbackResult enum that can't be represented in HystrixCommand: " + fallbackResult);
}
}
}
private static class FlexibleTestHystrixCommandNoFallback extends AbstractFlexibleTestHystrixCommand {
FlexibleTestHystrixCommandNoFallback(HystrixCommandKey commandKey, ExecutionIsolationStrategy isolationStrategy, AbstractTestHystrixCommand.ExecutionResult executionResult, int executionLatency, TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int timeout, CacheEnabled cacheEnabled, Object value, TryableSemaphore executionSemaphore, TryableSemaphore fallbackSemaphore, boolean circuitBreakerDisabled) {
super(commandKey, isolationStrategy, executionResult, executionLatency, circuitBreaker, threadPool, timeout, cacheEnabled, value, executionSemaphore, fallbackSemaphore, circuitBreakerDisabled);
}
}
/**
* Successful execution - no fallback implementation.
*/
private static class SuccessfulTestCommand extends TestHystrixCommand<Boolean> {
public SuccessfulTestCommand() {
this(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter());
}
public SuccessfulTestCommand(HystrixCommandProperties.Setter properties) {
super(testPropsBuilder().setCommandPropertiesDefaults(properties));
}
@Override
protected Boolean run() {
return true;
}
}
/**
* Successful execution - no fallback implementation.
*/
private static class DynamicOwnerTestCommand extends TestHystrixCommand<Boolean> {
public DynamicOwnerTestCommand(HystrixCommandGroupKey owner) {
super(testPropsBuilder().setOwner(owner));
}
@Override
protected Boolean run() {
System.out.println("successfully executed");
return true;
}
}
/**
* Successful execution - no fallback implementation.
*/
private static class DynamicOwnerAndKeyTestCommand extends TestHystrixCommand<Boolean> {
public DynamicOwnerAndKeyTestCommand(HystrixCommandGroupKey owner, HystrixCommandKey key) {
super(testPropsBuilder().setOwner(owner).setCommandKey(key).setCircuitBreaker(null).setMetrics(null));
// we specifically are NOT passing in a circuit breaker here so we test that it creates a new one correctly based on the dynamic key
}
@Override
protected Boolean run() {
System.out.println("successfully executed");
return true;
}
}
/**
* Failed execution with known exception (HystrixException) - no fallback implementation.
*/
private static class KnownFailureTestCommandWithoutFallback extends TestHystrixCommand<Boolean> {
private KnownFailureTestCommandWithoutFallback(TestCircuitBreaker circuitBreaker) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics));
}
@Override
protected Boolean run() {
System.out.println("*** simulated failed execution *** ==> " + Thread.currentThread());
throw new RuntimeException("we failed with a simulated issue");
}
}
/**
* Failed execution - fallback implementation successfully returns value.
*/
private static class KnownFailureTestCommandWithFallback extends TestHystrixCommand<Boolean> {
public KnownFailureTestCommandWithFallback(TestCircuitBreaker circuitBreaker) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics));
}
public KnownFailureTestCommandWithFallback(TestCircuitBreaker circuitBreaker, boolean fallbackEnabled) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withFallbackEnabled(fallbackEnabled)));
}
@Override
protected Boolean run() {
System.out.println("*** simulated failed execution ***");
throw new RuntimeException("we failed with a simulated issue");
}
@Override
protected Boolean getFallback() {
return false;
}
}
/**
* A Command implementation that supports caching.
*/
private static class SuccessfulCacheableCommand<T> extends TestHystrixCommand<T> {
private final boolean cacheEnabled;
private volatile boolean executed = false;
private final T value;
public SuccessfulCacheableCommand(TestCircuitBreaker circuitBreaker, boolean cacheEnabled, T value) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics));
this.value = value;
this.cacheEnabled = cacheEnabled;
}
@Override
protected T run() {
executed = true;
System.out.println("successfully executed");
return value;
}
public boolean isCommandRunningInThread() {
return super.getProperties().executionIsolationStrategy().get().equals(ExecutionIsolationStrategy.THREAD);
}
@Override
public String getCacheKey() {
if (cacheEnabled)
return value.toString();
else
return null;
}
}
/**
* A Command implementation that supports caching.
*/
private static class SuccessfulCacheableCommandViaSemaphore extends TestHystrixCommand<String> {
private final boolean cacheEnabled;
private volatile boolean executed = false;
private final String value;
public SuccessfulCacheableCommandViaSemaphore(TestCircuitBreaker circuitBreaker, boolean cacheEnabled, String value) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)));
this.value = value;
this.cacheEnabled = cacheEnabled;
}
@Override
protected String run() {
executed = true;
System.out.println("successfully executed");
return value;
}
public boolean isCommandRunningInThread() {
return super.getProperties().executionIsolationStrategy().get().equals(ExecutionIsolationStrategy.THREAD);
}
@Override
public String getCacheKey() {
if (cacheEnabled)
return value;
else
return null;
}
}
/**
* A Command implementation that supports caching and execution takes a while.
* <p>
* Used to test scenario where Futures are returned with a backing call still executing.
*/
private static class SlowCacheableCommand extends TestHystrixCommand<String> {
private final String value;
private final int duration;
private volatile boolean executed = false;
public SlowCacheableCommand(TestCircuitBreaker circuitBreaker, String value, int duration) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics));
this.value = value;
this.duration = duration;
}
@Override
protected String run() {
executed = true;
try {
Thread.sleep(duration);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("successfully executed");
return value;
}
@Override
public String getCacheKey() {
return value;
}
}
/**
* This has a ThreadPool that has a single thread and queueSize of 1.
*/
private static class TestCommandRejection extends TestHystrixCommand<Boolean> {
private final static int FALLBACK_NOT_IMPLEMENTED = 1;
private final static int FALLBACK_SUCCESS = 2;
private final static int FALLBACK_FAILURE = 3;
private final int fallbackBehavior;
private final int sleepTime;
private TestCommandRejection(HystrixCommandKey key, TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int sleepTime, int timeout, int fallbackBehavior) {
super(testPropsBuilder()
.setCommandKey(key)
.setThreadPool(threadPool)
.setCircuitBreaker(circuitBreaker)
.setMetrics(circuitBreaker.metrics)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionTimeoutInMilliseconds(timeout)));
this.fallbackBehavior = fallbackBehavior;
this.sleepTime = sleepTime;
}
@Override
protected Boolean run() {
System.out.println(">>> TestCommandRejection running");
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}
@Override
protected Boolean getFallback() {
if (fallbackBehavior == FALLBACK_SUCCESS) {
return false;
} else if (fallbackBehavior == FALLBACK_FAILURE) {
throw new RuntimeException("failed on fallback");
} else {
// FALLBACK_NOT_IMPLEMENTED
return super.getFallback();
}
}
}
/**
* Command that receives a custom thread-pool, sleepTime, timeout
*/
private static class CommandWithCustomThreadPool extends TestHystrixCommand<Boolean> {
public boolean didExecute = false;
private final int sleepTime;
private CommandWithCustomThreadPool(TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int sleepTime, HystrixCommandProperties.Setter properties) {
super(testPropsBuilder().setThreadPool(threadPool).setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics).setCommandPropertiesDefaults(properties));
this.sleepTime = sleepTime;
}
@Override
protected Boolean run() {
System.out.println("**** Executing CommandWithCustomThreadPool. Execution => " + sleepTime);
didExecute = true;
try {
Thread.sleep(sleepTime);
System.out.println("Woke up");
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}
}
/**
* The run() will fail and getFallback() take a long time.
*/
private static class TestSemaphoreCommandWithSlowFallback extends TestHystrixCommand<Boolean> {
private final long fallbackSleep;
private TestSemaphoreCommandWithSlowFallback(TestCircuitBreaker circuitBreaker, int fallbackSemaphoreExecutionCount, long fallbackSleep) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withFallbackIsolationSemaphoreMaxConcurrentRequests(fallbackSemaphoreExecutionCount).withExecutionIsolationThreadInterruptOnTimeout(false)));
this.fallbackSleep = fallbackSleep;
}
@Override
protected Boolean run() {
throw new RuntimeException("run fails");
}
@Override
protected Boolean getFallback() {
try {
Thread.sleep(fallbackSleep);
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}
}
private static class NoRequestCacheTimeoutWithoutFallback extends TestHystrixCommand<Boolean> {
public NoRequestCacheTimeoutWithoutFallback(TestCircuitBreaker circuitBreaker) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionTimeoutInMilliseconds(200).withCircuitBreakerEnabled(false)));
// we want it to timeout
}
@Override
protected Boolean run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(">>>> Sleep Interrupted: " + e.getMessage());
// e.printStackTrace();
}
return true;
}
@Override
public String getCacheKey() {
return null;
}
}
/**
* The run() will take time. Configurable fallback implementation.
*/
private static class TestSemaphoreCommand extends TestHystrixCommand<Boolean> {
private final long executionSleep;
private final static int RESULT_SUCCESS = 1;
private final static int RESULT_FAILURE = 2;
private final static int RESULT_BAD_REQUEST_EXCEPTION = 3;
private final int resultBehavior;
private final static int FALLBACK_SUCCESS = 10;
private final static int FALLBACK_NOT_IMPLEMENTED = 11;
private final static int FALLBACK_FAILURE = 12;
private final int fallbackBehavior;
private TestSemaphoreCommand(TestCircuitBreaker circuitBreaker, int executionSemaphoreCount, long executionSleep, int resultBehavior, int fallbackBehavior) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter()
.withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)
.withExecutionIsolationSemaphoreMaxConcurrentRequests(executionSemaphoreCount)));
this.executionSleep = executionSleep;
this.resultBehavior = resultBehavior;
this.fallbackBehavior = fallbackBehavior;
}
private TestSemaphoreCommand(TestCircuitBreaker circuitBreaker, TryableSemaphore semaphore, long executionSleep, int resultBehavior, int fallbackBehavior) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter()
.withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE))
.setExecutionSemaphore(semaphore));
this.executionSleep = executionSleep;
this.resultBehavior = resultBehavior;
this.fallbackBehavior = fallbackBehavior;
}
@Override
protected Boolean run() {
try {
Thread.sleep(executionSleep);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (resultBehavior == RESULT_SUCCESS) {
return true;
} else if (resultBehavior == RESULT_FAILURE) {
throw new RuntimeException("TestSemaphoreCommand failure");
} else if (resultBehavior == RESULT_BAD_REQUEST_EXCEPTION) {
throw new HystrixBadRequestException("TestSemaphoreCommand BadRequestException");
} else {
throw new IllegalStateException("Didn't use a proper enum for result behavior");
}
}
@Override
protected Boolean getFallback() {
if (fallbackBehavior == FALLBACK_SUCCESS) {
return false;
} else if (fallbackBehavior == FALLBACK_FAILURE) {
throw new RuntimeException("fallback failure");
} else { //FALLBACK_NOT_IMPLEMENTED
return super.getFallback();
}
}
}
/**
* Semaphore based command that allows caller to use latches to know when it has started and signal when it
* would like the command to finish
*/
private static class LatchedSemaphoreCommand extends TestHystrixCommand<Boolean> {
private final CountDownLatch startLatch, waitLatch;
/**
*
* @param circuitBreaker circuit breaker (passed in so it may be shared)
* @param semaphore semaphore (passed in so it may be shared)
* @param startLatch
* this command calls {@link java.util.concurrent.CountDownLatch#countDown()} immediately
* upon running
* @param waitLatch
* this command calls {@link java.util.concurrent.CountDownLatch#await()} once it starts
* to run. The caller can use the latch to signal the command to finish
*/
private LatchedSemaphoreCommand(TestCircuitBreaker circuitBreaker, TryableSemaphore semaphore, CountDownLatch startLatch, CountDownLatch waitLatch) {
this("Latched", circuitBreaker, semaphore, startLatch, waitLatch);
}
private LatchedSemaphoreCommand(String commandName, TestCircuitBreaker circuitBreaker, TryableSemaphore semaphore,
CountDownLatch startLatch, CountDownLatch waitLatch) {
super(testPropsBuilder()
.setCommandKey(HystrixCommandKey.Factory.asKey(commandName))
.setCircuitBreaker(circuitBreaker)
.setMetrics(circuitBreaker.metrics)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter()
.withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)
.withCircuitBreakerEnabled(false))
.setExecutionSemaphore(semaphore));
this.startLatch = startLatch;
this.waitLatch = waitLatch;
}
@Override
protected Boolean run() {
// signals caller that run has started
this.startLatch.countDown();
try {
// waits for caller to countDown latch
this.waitLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
return false;
}
return true;
}
}
/**
* The run() will take time. Contains fallback.
*/
private static class TestSemaphoreCommandWithFallback extends TestHystrixCommand<Boolean> {
private final long executionSleep;
private final Boolean fallback;
private TestSemaphoreCommandWithFallback(TestCircuitBreaker circuitBreaker, int executionSemaphoreCount, long executionSleep, Boolean fallback) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE).withExecutionIsolationSemaphoreMaxConcurrentRequests(executionSemaphoreCount)));
this.executionSleep = executionSleep;
this.fallback = fallback;
}
@Override
protected Boolean run() {
try {
Thread.sleep(executionSleep);
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}
@Override
protected Boolean getFallback() {
return fallback;
}
}
private static class RequestCacheNullPointerExceptionCase extends TestHystrixCommand<Boolean> {
public RequestCacheNullPointerExceptionCase(TestCircuitBreaker circuitBreaker) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionTimeoutInMilliseconds(200)));
// we want it to timeout
}
@Override
protected Boolean run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}
@Override
protected Boolean getFallback() {
return false;
}
@Override
public String getCacheKey() {
return "A";
}
}
private static class RequestCacheTimeoutWithoutFallback extends TestHystrixCommand<Boolean> {
public RequestCacheTimeoutWithoutFallback(TestCircuitBreaker circuitBreaker) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionTimeoutInMilliseconds(200).withCircuitBreakerEnabled(false)));
// we want it to timeout
}
@Override
protected Boolean run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(">>>> Sleep Interrupted: " + e.getMessage());
// e.printStackTrace();
}
return true;
}
@Override
public String getCacheKey() {
return "A";
}
}
private static class RequestCacheThreadRejectionWithoutFallback extends TestHystrixCommand<Boolean> {
final CountDownLatch completionLatch;
public RequestCacheThreadRejectionWithoutFallback(TestCircuitBreaker circuitBreaker, CountDownLatch completionLatch) {
super(testPropsBuilder()
.setCircuitBreaker(circuitBreaker)
.setMetrics(circuitBreaker.metrics)
.setThreadPool(new HystrixThreadPool() {
@Override
public ThreadPoolExecutor getExecutor() {
return null;
}
@Override
public void markThreadExecution() {
}
@Override
public void markThreadCompletion() {
}
@Override
public void markThreadRejection() {
}
@Override
public boolean isQueueSpaceAvailable() {
// always return false so we reject everything
return false;
}
@Override
public Scheduler getScheduler() {
return new HystrixContextScheduler(HystrixPlugins.getInstance().getConcurrencyStrategy(), this);
}
@Override
public Scheduler getScheduler(Func0<Boolean> shouldInterruptThread) {
return new HystrixContextScheduler(HystrixPlugins.getInstance().getConcurrencyStrategy(), this, shouldInterruptThread);
}
}));
this.completionLatch = completionLatch;
}
@Override
protected Boolean run() {
try {
if (completionLatch.await(1000, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("timed out waiting on completionLatch");
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return true;
}
@Override
public String getCacheKey() {
return "A";
}
}
private static class BadRequestCommand extends TestHystrixCommand<Boolean> {
public BadRequestCommand(TestCircuitBreaker circuitBreaker, ExecutionIsolationStrategy isolationType) {
super(testPropsBuilder()
.setCircuitBreaker(circuitBreaker)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(isolationType))
.setMetrics(circuitBreaker.metrics));
}
@Override
protected Boolean run() {
throw new HystrixBadRequestException("Message to developer that they passed in bad data or something like that.");
}
@Override
protected Boolean getFallback() {
return false;
}
@Override
protected String getCacheKey() {
return "one";
}
}
private static class AsyncCacheableCommand extends HystrixCommand<Boolean> {
private final String arg;
private final AtomicBoolean cancelled = new AtomicBoolean(false);
public AsyncCacheableCommand(String arg) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ASYNC")));
this.arg = arg;
}
@Override
protected Boolean run() {
try {
Thread.sleep(500);
return true;
} catch (InterruptedException ex) {
cancelled.set(true);
throw new RuntimeException(ex);
}
}
@Override
protected String getCacheKey() {
return arg;
}
public boolean isCancelled() {
return cancelled.get();
}
}
private static class BusinessException extends Exception {
public BusinessException(String msg) {
super(msg);
}
}
private static class ExceptionToBadRequestByExecutionHookCommand extends TestHystrixCommand<Boolean> {
public ExceptionToBadRequestByExecutionHookCommand(TestCircuitBreaker circuitBreaker, ExecutionIsolationStrategy isolationType) {
super(testPropsBuilder()
.setCircuitBreaker(circuitBreaker)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(isolationType))
.setMetrics(circuitBreaker.metrics)
.setExecutionHook(new TestableExecutionHook(){
@Override
public <T> Exception onRunError(HystrixInvokable<T> commandInstance, Exception e) {
super.onRunError(commandInstance, e);
return new HystrixBadRequestException("autoconverted exception", e);
}
}));
}
@Override
protected Boolean run() throws BusinessException {
throw new BusinessException("invalid input by the user");
}
@Override
protected String getCacheKey() {
return "nein";
}
}
private static class CommandWithCheckedException extends TestHystrixCommand<Boolean> {
public CommandWithCheckedException(TestCircuitBreaker circuitBreaker) {
super(testPropsBuilder()
.setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics));
}
@Override
protected Boolean run() throws Exception {
throw new IOException("simulated checked exception message");
}
}
private static class CommandWithNotWrappedByHystrixException extends TestHystrixCommand<Boolean> {
public CommandWithNotWrappedByHystrixException(TestCircuitBreaker circuitBreaker) {
super(testPropsBuilder()
.setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics));
}
@Override
protected Boolean run() throws Exception {
throw new NotWrappedByHystrixTestException();
}
}
private static class InterruptibleCommand extends TestHystrixCommand<Boolean> {
public InterruptibleCommand(TestCircuitBreaker circuitBreaker, boolean shouldInterrupt, boolean shouldInterruptOnCancel, int timeoutInMillis) {
super(testPropsBuilder()
.setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter()
.withExecutionIsolationThreadInterruptOnFutureCancel(shouldInterruptOnCancel)
.withExecutionIsolationThreadInterruptOnTimeout(shouldInterrupt)
.withExecutionTimeoutInMilliseconds(timeoutInMillis)));
}
public InterruptibleCommand(TestCircuitBreaker circuitBreaker, boolean shouldInterrupt) {
this(circuitBreaker, shouldInterrupt, false, 100);
}
private volatile boolean hasBeenInterrupted;
public boolean hasBeenInterrupted() {
return hasBeenInterrupted;
}
@Override
protected Boolean run() throws Exception {
try {
Thread.sleep(2000);
}
catch (InterruptedException e) {
System.out.println("Interrupted!");
e.printStackTrace();
hasBeenInterrupted = true;
}
return hasBeenInterrupted;
}
}
private static class CommandWithDisabledTimeout extends TestHystrixCommand<Boolean> {
private final int latency;
public CommandWithDisabledTimeout(int timeout, int latency) {
super(testPropsBuilder().setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter()
.withExecutionTimeoutInMilliseconds(timeout)
.withExecutionTimeoutEnabled(false)));
this.latency = latency;
}
@Override
protected Boolean run() throws Exception {
try {
Thread.sleep(latency);
return true;
} catch (InterruptedException ex) {
return false;
}
}
@Override
protected Boolean getFallback() {
return false;
}
}
}
| 4,564 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/HystrixObservableCollapserTest.java | /**
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix;
import com.hystrix.junit.HystrixRequestContextRule;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import com.netflix.hystrix.collapser.CollapserTimer;
import com.netflix.hystrix.collapser.RealCollapserTimer;
import com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable;
import com.netflix.hystrix.strategy.concurrency.HystrixContextScheduler;
import com.netflix.hystrix.strategy.properties.HystrixPropertiesCollapserDefault;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import rx.Observable;
import rx.Observable.OnSubscribe;
import rx.Subscriber;
import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.observers.TestSubscriber;
import rx.schedulers.Schedulers;
import com.netflix.hystrix.HystrixCollapser.CollapsedRequest;
import com.netflix.hystrix.HystrixCollapserTest.TestCollapserTimer;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import static org.junit.Assert.*;
public class HystrixObservableCollapserTest {
private static Action1<CollapsedRequest<String, String>> onMissingError = new Action1<CollapsedRequest<String, String>>() {
@Override
public void call(CollapsedRequest<String, String> collapsedReq) {
collapsedReq.setException(new IllegalStateException("must have a value"));
}
};
private static Action1<CollapsedRequest<String, String>> onMissingThrow = new Action1<CollapsedRequest<String, String>>() {
@Override
public void call(CollapsedRequest<String, String> collapsedReq) {
throw new RuntimeException("synchronous error in onMissingResponse handler");
}
};
private static Action1<CollapsedRequest<String, String>> onMissingComplete = new Action1<CollapsedRequest<String, String>>() {
@Override
public void call(CollapsedRequest<String, String> collapsedReq) {
collapsedReq.setComplete();
}
};
private static Action1<CollapsedRequest<String, String>> onMissingIgnore = new Action1<CollapsedRequest<String, String>>() {
@Override
public void call(CollapsedRequest<String, String> collapsedReq) {
//do nothing
}
};
private static Action1<CollapsedRequest<String, String>> onMissingFillIn = new Action1<CollapsedRequest<String, String>>() {
@Override
public void call(CollapsedRequest<String, String> collapsedReq) {
collapsedReq.setResponse("fillin");
}
};
private static Func1<String, String> prefixMapper = new Func1<String, String>() {
@Override
public String call(String s) {
return s.substring(0, s.indexOf(":"));
}
};
private static Func1<String, String> map1To3And2To2 = new Func1<String, String>() {
@Override
public String call(String s) {
String prefix = s.substring(0, s.indexOf(":"));
if (prefix.equals("2")) {
return "2";
} else {
return "3";
}
}
};
private static Func1<String, String> mapWithErrorOn1 = new Func1<String, String>() {
@Override
public String call(String s) {
String prefix = s.substring(0, s.indexOf(":"));
if (prefix.equals("1")) {
throw new RuntimeException("poorly implemented demultiplexer");
} else {
return "2";
}
}
};
@Rule
public HystrixRequestContextRule ctx = new HystrixRequestContextRule();
private static ExecutorService threadPool = new ThreadPoolExecutor(100, 100, 10, TimeUnit.MINUTES, new SynchronousQueue<Runnable>());
@Before
public void init() {
// since we're going to modify properties of the same class between tests, wipe the cache each time
HystrixCollapser.reset();
}
@Test
public void testTwoRequests() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixObservableCollapser<String, String, String, String> collapser1 = new TestRequestCollapser(timer, 1);
HystrixObservableCollapser<String, String, String, String> collapser2 = new TestRequestCollapser(timer, 2);
Future<String> response1 = collapser1.observe().toBlocking().toFuture();
Future<String> response2 = collapser2.observe().toBlocking().toFuture();
timer.incrementTime(10); // let time pass that equals the default delay/period
assertEquals("1", response1.get());
assertEquals("2", response2.get());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
Iterator<HystrixInvokableInfo<?>> cmdIterator = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator();
assertEquals(2, cmdIterator.next().getNumberCollapsed());
}
@Test
public void stressTestRequestCollapser() throws Exception {
for(int i = 0; i < 10; i++) {
init();
testTwoRequests();
ctx.reset();
}
}
@Test
public void testTwoRequestsWhichShouldEachEmitTwice() throws Exception {
//TestCollapserTimer timer = new TestCollapserTimer();
CollapserTimer timer = new RealCollapserTimer();
HystrixObservableCollapser<String, String, String, String> collapser1 = new TestCollapserWithMultipleResponses(timer, 1, 3, false, false, prefixMapper, onMissingComplete);
HystrixObservableCollapser<String, String, String, String> collapser2 = new TestCollapserWithMultipleResponses(timer, 2, 3, false, false, prefixMapper, onMissingComplete);
TestSubscriber<String> testSubscriber1 = new TestSubscriber<String>();
TestSubscriber<String> testSubscriber2 = new TestSubscriber<String>();
System.out.println(System.currentTimeMillis() + "Starting to observe collapser1");
collapser1.observe().subscribe(testSubscriber1);
collapser2.observe().subscribe(testSubscriber2);
System.out.println(System.currentTimeMillis() + "Done with collapser observe()s");
//Note that removing these awaits breaks the unit test. That implies that the above subscribe does not wait for a terminal event
testSubscriber1.awaitTerminalEvent();
testSubscriber2.awaitTerminalEvent();
testSubscriber1.assertCompleted();
testSubscriber1.assertNoErrors();
testSubscriber1.assertValues("1:1", "1:2", "1:3");
testSubscriber2.assertCompleted();
testSubscriber2.assertNoErrors();
testSubscriber2.assertValues("2:2", "2:4", "2:6");
}
@Test
public void testTwoRequestsWithErrorProducingBatchCommand() {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixObservableCollapser<String, String, String, String> collapser1 = new TestCollapserWithMultipleResponses(timer, 1, 3, true);
HystrixObservableCollapser<String, String, String, String> collapser2 = new TestCollapserWithMultipleResponses(timer, 2, 3, true);
System.out.println("Starting to observe collapser1");
Observable<String> result1 = collapser1.observe();
Observable<String> result2 = collapser2.observe();
timer.incrementTime(10); // let time pass that equals the default delay/period
TestSubscriber<String> testSubscriber1 = new TestSubscriber<String>();
result1.subscribe(testSubscriber1);
TestSubscriber<String> testSubscriber2 = new TestSubscriber<String>();
result2.subscribe(testSubscriber2);
testSubscriber1.awaitTerminalEvent();
testSubscriber2.awaitTerminalEvent();
testSubscriber1.assertError(RuntimeException.class);
testSubscriber1.assertNoValues();
testSubscriber2.assertError(RuntimeException.class);
testSubscriber2.assertNoValues();
}
@Test
public void testTwoRequestsWithErrorInDemultiplex() {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixObservableCollapser<String, String, String, String> collapser1 = new TestCollapserWithMultipleResponses(timer, 1, 3, false, false, mapWithErrorOn1, onMissingError);
HystrixObservableCollapser<String, String, String, String> collapser2 = new TestCollapserWithMultipleResponses(timer, 2, 3, false, false, mapWithErrorOn1, onMissingError);
System.out.println("Starting to observe collapser1");
Observable<String> result1 = collapser1.observe();
Observable<String> result2 = collapser2.observe();
timer.incrementTime(10); // let time pass that equals the default delay/period
TestSubscriber<String> testSubscriber1 = new TestSubscriber<String>();
result1.subscribe(testSubscriber1);
TestSubscriber<String> testSubscriber2 = new TestSubscriber<String>();
result2.subscribe(testSubscriber2);
testSubscriber1.awaitTerminalEvent();
testSubscriber2.awaitTerminalEvent();
testSubscriber1.assertError(RuntimeException.class);
testSubscriber1.assertNoValues();
testSubscriber2.assertCompleted();
testSubscriber2.assertNoErrors();
testSubscriber2.assertValues("2:2", "2:4", "2:6");
}
@Test
public void testTwoRequestsWithEmptyResponseAndOnMissingError() {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixObservableCollapser<String, String, String, String> collapser1 = new TestCollapserWithMultipleResponses(timer, 1, 0, onMissingError);
HystrixObservableCollapser<String, String, String, String> collapser2 = new TestCollapserWithMultipleResponses(timer, 2, 0, onMissingError);
System.out.println("Starting to observe collapser1");
Observable<String> result1 = collapser1.observe();
Observable<String> result2 = collapser2.observe();
timer.incrementTime(10); // let time pass that equals the default delay/period
TestSubscriber<String> testSubscriber1 = new TestSubscriber<String>();
result1.subscribe(testSubscriber1);
TestSubscriber<String> testSubscriber2 = new TestSubscriber<String>();
result2.subscribe(testSubscriber2);
testSubscriber1.awaitTerminalEvent();
testSubscriber2.awaitTerminalEvent();
testSubscriber1.assertError(IllegalStateException.class);
testSubscriber1.assertNoValues();
testSubscriber2.assertError(IllegalStateException.class);
testSubscriber2.assertNoValues();
}
@Test
public void testTwoRequestsWithEmptyResponseAndOnMissingThrow() {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixObservableCollapser<String, String, String, String> collapser1 = new TestCollapserWithMultipleResponses(timer, 1, 0, onMissingThrow);
HystrixObservableCollapser<String, String, String, String> collapser2 = new TestCollapserWithMultipleResponses(timer, 2, 0, onMissingThrow);
System.out.println("Starting to observe collapser1");
Observable<String> result1 = collapser1.observe();
Observable<String> result2 = collapser2.observe();
timer.incrementTime(10); // let time pass that equals the default delay/period
TestSubscriber<String> testSubscriber1 = new TestSubscriber<String>();
result1.subscribe(testSubscriber1);
TestSubscriber<String> testSubscriber2 = new TestSubscriber<String>();
result2.subscribe(testSubscriber2);
testSubscriber1.awaitTerminalEvent();
testSubscriber2.awaitTerminalEvent();
testSubscriber1.assertError(RuntimeException.class);
testSubscriber1.assertNoValues();
testSubscriber2.assertError(RuntimeException.class);
testSubscriber2.assertNoValues();
}
@Test
public void testTwoRequestsWithEmptyResponseAndOnMissingComplete() {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixObservableCollapser<String, String, String, String> collapser1 = new TestCollapserWithMultipleResponses(timer, 1, 0, onMissingComplete);
HystrixObservableCollapser<String, String, String, String> collapser2 = new TestCollapserWithMultipleResponses(timer, 2, 0, onMissingComplete);
System.out.println("Starting to observe collapser1");
Observable<String> result1 = collapser1.observe();
Observable<String> result2 = collapser2.observe();
timer.incrementTime(10); // let time pass that equals the default delay/period
TestSubscriber<String> testSubscriber1 = new TestSubscriber<String>();
result1.subscribe(testSubscriber1);
TestSubscriber<String> testSubscriber2 = new TestSubscriber<String>();
result2.subscribe(testSubscriber2);
testSubscriber1.awaitTerminalEvent();
testSubscriber2.awaitTerminalEvent();
testSubscriber1.assertCompleted();
testSubscriber1.assertNoErrors();
testSubscriber1.assertNoValues();
testSubscriber2.assertCompleted();
testSubscriber2.assertNoErrors();
testSubscriber2.assertNoValues();
}
@Test
public void testTwoRequestsWithEmptyResponseAndOnMissingIgnore() {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixObservableCollapser<String, String, String, String> collapser1 = new TestCollapserWithMultipleResponses(timer, 1, 0, onMissingIgnore);
HystrixObservableCollapser<String, String, String, String> collapser2 = new TestCollapserWithMultipleResponses(timer, 2, 0, onMissingIgnore);
System.out.println("Starting to observe collapser1");
Observable<String> result1 = collapser1.observe();
Observable<String> result2 = collapser2.observe();
timer.incrementTime(10); // let time pass that equals the default delay/period
TestSubscriber<String> testSubscriber1 = new TestSubscriber<String>();
result1.subscribe(testSubscriber1);
TestSubscriber<String> testSubscriber2 = new TestSubscriber<String>();
result2.subscribe(testSubscriber2);
testSubscriber1.awaitTerminalEvent();
testSubscriber2.awaitTerminalEvent();
testSubscriber1.assertCompleted();
testSubscriber1.assertNoErrors();
testSubscriber1.assertNoValues();
testSubscriber2.assertCompleted();
testSubscriber2.assertNoErrors();
testSubscriber2.assertNoValues();
}
@Test
public void testTwoRequestsWithEmptyResponseAndOnMissingFillInStaticValue() {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixObservableCollapser<String, String, String, String> collapser1 = new TestCollapserWithMultipleResponses(timer, 1, 0, onMissingFillIn);
HystrixObservableCollapser<String, String, String, String> collapser2 = new TestCollapserWithMultipleResponses(timer, 2, 0, onMissingFillIn);
System.out.println("Starting to observe collapser1");
Observable<String> result1 = collapser1.observe();
Observable<String> result2 = collapser2.observe();
timer.incrementTime(10); // let time pass that equals the default delay/period
TestSubscriber<String> testSubscriber1 = new TestSubscriber<String>();
result1.subscribe(testSubscriber1);
TestSubscriber<String> testSubscriber2 = new TestSubscriber<String>();
result2.subscribe(testSubscriber2);
testSubscriber1.awaitTerminalEvent();
testSubscriber2.awaitTerminalEvent();
testSubscriber1.assertCompleted();
testSubscriber1.assertNoErrors();
testSubscriber1.assertValues("fillin");
testSubscriber2.assertCompleted();
testSubscriber2.assertNoErrors();
testSubscriber2.assertValues("fillin");
}
@Test
public void testTwoRequestsWithValuesForOneArgOnlyAndOnMissingComplete() {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixObservableCollapser<String, String, String, String> collapser1 = new TestCollapserWithMultipleResponses(timer, 1, 0, onMissingComplete);
HystrixObservableCollapser<String, String, String, String> collapser2 = new TestCollapserWithMultipleResponses(timer, 2, 5, onMissingComplete);
System.out.println("Starting to observe collapser1");
Observable<String> result1 = collapser1.observe();
Observable<String> result2 = collapser2.observe();
timer.incrementTime(10); // let time pass that equals the default delay/period
TestSubscriber<String> testSubscriber1 = new TestSubscriber<String>();
result1.subscribe(testSubscriber1);
TestSubscriber<String> testSubscriber2 = new TestSubscriber<String>();
result2.subscribe(testSubscriber2);
testSubscriber1.awaitTerminalEvent();
testSubscriber2.awaitTerminalEvent();
testSubscriber1.assertCompleted();
testSubscriber1.assertNoErrors();
testSubscriber1.assertNoValues();
testSubscriber2.assertCompleted();
testSubscriber2.assertNoErrors();
testSubscriber2.assertValues("2:2", "2:4", "2:6", "2:8", "2:10");
}
@Test
public void testTwoRequestsWithValuesForOneArgOnlyAndOnMissingFillInStaticValue() {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixObservableCollapser<String, String, String, String> collapser1 = new TestCollapserWithMultipleResponses(timer, 1, 0, onMissingFillIn);
HystrixObservableCollapser<String, String, String, String> collapser2 = new TestCollapserWithMultipleResponses(timer, 2, 5, onMissingFillIn);
System.out.println("Starting to observe collapser1");
Observable<String> result1 = collapser1.observe();
Observable<String> result2 = collapser2.observe();
timer.incrementTime(10); // let time pass that equals the default delay/period
TestSubscriber<String> testSubscriber1 = new TestSubscriber<String>();
result1.subscribe(testSubscriber1);
TestSubscriber<String> testSubscriber2 = new TestSubscriber<String>();
result2.subscribe(testSubscriber2);
testSubscriber1.awaitTerminalEvent();
testSubscriber2.awaitTerminalEvent();
testSubscriber1.assertCompleted();
testSubscriber1.assertNoErrors();
testSubscriber1.assertValues("fillin");
testSubscriber2.assertCompleted();
testSubscriber2.assertNoErrors();
testSubscriber2.assertValues("2:2", "2:4", "2:6", "2:8", "2:10");
}
@Test
public void testTwoRequestsWithValuesForOneArgOnlyAndOnMissingIgnore() {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixObservableCollapser<String, String, String, String> collapser1 = new TestCollapserWithMultipleResponses(timer, 1, 0, onMissingIgnore);
HystrixObservableCollapser<String, String, String, String> collapser2 = new TestCollapserWithMultipleResponses(timer, 2, 5, onMissingIgnore);
System.out.println("Starting to observe collapser1");
Observable<String> result1 = collapser1.observe();
Observable<String> result2 = collapser2.observe();
timer.incrementTime(10); // let time pass that equals the default delay/period
TestSubscriber<String> testSubscriber1 = new TestSubscriber<String>();
result1.subscribe(testSubscriber1);
TestSubscriber<String> testSubscriber2 = new TestSubscriber<String>();
result2.subscribe(testSubscriber2);
testSubscriber1.awaitTerminalEvent();
testSubscriber2.awaitTerminalEvent();
testSubscriber1.assertCompleted();
testSubscriber1.assertNoErrors();
testSubscriber1.assertNoValues();
testSubscriber2.assertCompleted();
testSubscriber2.assertNoErrors();
testSubscriber2.assertValues("2:2", "2:4", "2:6", "2:8", "2:10");
}
@Test
public void testTwoRequestsWithValuesForOneArgOnlyAndOnMissingError() {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixObservableCollapser<String, String, String, String> collapser1 = new TestCollapserWithMultipleResponses(timer, 1, 0, onMissingError);
HystrixObservableCollapser<String, String, String, String> collapser2 = new TestCollapserWithMultipleResponses(timer, 2, 5, onMissingError);
System.out.println("Starting to observe collapser1");
Observable<String> result1 = collapser1.observe();
Observable<String> result2 = collapser2.observe();
timer.incrementTime(10); // let time pass that equals the default delay/period
TestSubscriber<String> testSubscriber1 = new TestSubscriber<String>();
result1.subscribe(testSubscriber1);
TestSubscriber<String> testSubscriber2 = new TestSubscriber<String>();
result2.subscribe(testSubscriber2);
testSubscriber1.awaitTerminalEvent();
testSubscriber2.awaitTerminalEvent();
testSubscriber1.assertError(IllegalStateException.class);
testSubscriber1.assertNoValues();
testSubscriber2.assertCompleted();
testSubscriber2.assertNoErrors();
testSubscriber2.assertValues("2:2", "2:4", "2:6", "2:8", "2:10");
}
@Test
public void testTwoRequestsWithValuesForOneArgOnlyAndOnMissingThrow() {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixObservableCollapser<String, String, String, String> collapser1 = new TestCollapserWithMultipleResponses(timer, 1, 0, onMissingThrow);
HystrixObservableCollapser<String, String, String, String> collapser2 = new TestCollapserWithMultipleResponses(timer, 2, 5, onMissingThrow);
System.out.println("Starting to observe collapser1");
Observable<String> result1 = collapser1.observe();
Observable<String> result2 = collapser2.observe();
timer.incrementTime(10); // let time pass that equals the default delay/period
TestSubscriber<String> testSubscriber1 = new TestSubscriber<String>();
result1.subscribe(testSubscriber1);
TestSubscriber<String> testSubscriber2 = new TestSubscriber<String>();
result2.subscribe(testSubscriber2);
testSubscriber1.awaitTerminalEvent();
testSubscriber2.awaitTerminalEvent();
testSubscriber1.assertError(RuntimeException.class);
testSubscriber1.assertNoValues();
testSubscriber2.assertCompleted();
testSubscriber2.assertNoErrors();
testSubscriber2.assertValues("2:2", "2:4", "2:6", "2:8", "2:10");
}
@Test
public void testTwoRequestsWithValuesForWrongArgs() {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixObservableCollapser<String, String, String, String> collapser1 = new TestCollapserWithMultipleResponses(timer, 1, 3, false, false, map1To3And2To2, onMissingError);
HystrixObservableCollapser<String, String, String, String> collapser2 = new TestCollapserWithMultipleResponses(timer, 2, 3, false, false, map1To3And2To2, onMissingError);
System.out.println("Starting to observe collapser1");
Observable<String> result1 = collapser1.observe();
Observable<String> result2 = collapser2.observe();
timer.incrementTime(10); // let time pass that equals the default delay/period
TestSubscriber<String> testSubscriber1 = new TestSubscriber<String>();
result1.subscribe(testSubscriber1);
TestSubscriber<String> testSubscriber2 = new TestSubscriber<String>();
result2.subscribe(testSubscriber2);
testSubscriber1.awaitTerminalEvent();
testSubscriber2.awaitTerminalEvent();
testSubscriber1.assertError(RuntimeException.class);
testSubscriber1.assertNoValues();
testSubscriber2.assertCompleted();
testSubscriber2.assertNoErrors();
testSubscriber2.assertValues("2:2", "2:4", "2:6");
}
@Test
public void testTwoRequestsWhenBatchCommandFails() {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixObservableCollapser<String, String, String, String> collapser1 = new TestCollapserWithMultipleResponses(timer, 1, 3, false, true, map1To3And2To2, onMissingError);
HystrixObservableCollapser<String, String, String, String> collapser2 = new TestCollapserWithMultipleResponses(timer, 2, 3, false, true, map1To3And2To2, onMissingError);
System.out.println("Starting to observe collapser1");
Observable<String> result1 = collapser1.observe();
Observable<String> result2 = collapser2.observe();
timer.incrementTime(10); // let time pass that equals the default delay/period
TestSubscriber<String> testSubscriber1 = new TestSubscriber<String>();
result1.subscribe(testSubscriber1);
TestSubscriber<String> testSubscriber2 = new TestSubscriber<String>();
result2.subscribe(testSubscriber2);
testSubscriber1.awaitTerminalEvent();
testSubscriber2.awaitTerminalEvent();
testSubscriber1.assertError(RuntimeException.class);
testSubscriber1.getOnErrorEvents().get(0).printStackTrace();
testSubscriber1.assertNoValues();
testSubscriber2.assertError(RuntimeException.class);
testSubscriber2.assertNoValues();
}
@Test
public void testCollapserUnderConcurrency() throws InterruptedException {
final CollapserTimer timer = new RealCollapserTimer();
final int NUM_THREADS_SUBMITTING_WORK = 8;
final int NUM_REQUESTS_PER_THREAD = 8;
final CountDownLatch latch = new CountDownLatch(NUM_THREADS_SUBMITTING_WORK);
List<Runnable> runnables = new ArrayList<Runnable>();
final ConcurrentLinkedQueue<TestSubscriber<String>> subscribers = new ConcurrentLinkedQueue<TestSubscriber<String>>();
HystrixRequestContext context = HystrixRequestContext.initializeContext();
final AtomicInteger uniqueInt = new AtomicInteger(0);
for (int i = 0; i < NUM_THREADS_SUBMITTING_WORK; i++) {
runnables.add(new Runnable() {
@Override
public void run() {
try {
//System.out.println("Runnable starting on thread : " + Thread.currentThread().getName());
for (int j = 0; j < NUM_REQUESTS_PER_THREAD; j++) {
HystrixObservableCollapser<String, String, String, String> collapser =
new TestCollapserWithMultipleResponses(timer, uniqueInt.getAndIncrement(), 3, false);
Observable<String> o = collapser.toObservable();
TestSubscriber<String> subscriber = new TestSubscriber<String>();
o.subscribe(subscriber);
subscribers.offer(subscriber);
}
//System.out.println("Runnable done on thread : " + Thread.currentThread().getName());
} finally {
latch.countDown();
}
}
});
}
for (Runnable r: runnables) {
threadPool.submit(new HystrixContextRunnable(r));
}
assertTrue(latch.await(1000, TimeUnit.MILLISECONDS));
for (TestSubscriber<String> subscriber: subscribers) {
subscriber.awaitTerminalEvent();
if (subscriber.getOnErrorEvents().size() > 0) {
System.out.println("ERROR : " + subscriber.getOnErrorEvents());
for (Throwable ex: subscriber.getOnErrorEvents()) {
ex.printStackTrace();
}
}
subscriber.assertCompleted();
subscriber.assertNoErrors();
System.out.println("Received : " + subscriber.getOnNextEvents());
subscriber.assertValueCount(3);
}
context.shutdown();
}
@Test
public void testConcurrencyInLoop() throws InterruptedException {
for (int i = 0; i < 10; i++) {
System.out.println("TRIAL : " + i);
testCollapserUnderConcurrency();
}
}
@Test
public void testEarlyUnsubscribeExecutedViaToObservable() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixObservableCollapser<String, String, String, String> collapser1 = new TestRequestCollapser(timer, 1);
Observable<String> response1 = collapser1.toObservable();
HystrixObservableCollapser<String, String, String, String> collapser2 = new TestRequestCollapser(timer, 2);
Observable<String> response2 = collapser2.toObservable();
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final AtomicReference<String> value1 = new AtomicReference<String>(null);
final AtomicReference<String> value2 = new AtomicReference<String>(null);
Subscription s1 = response1
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s1 Unsubscribed!");
latch1.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s1 OnCompleted");
latch1.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s1 OnError : " + e);
latch1.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s1 OnNext : " + s);
value1.set(s);
}
});
Subscription s2 = response2
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s2 Unsubscribed!");
latch2.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s2 OnCompleted");
latch2.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s2 OnError : " + e);
latch2.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s2 OnNext : " + s);
value2.set(s);
}
});
s1.unsubscribe();
timer.incrementTime(10); // let time pass that equals the default delay/period
assertTrue(latch1.await(1000, TimeUnit.MILLISECONDS));
assertTrue(latch2.await(1000, TimeUnit.MILLISECONDS));
assertNull(value1.get());
assertEquals("2", value2.get());
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixCollapserMetrics metrics = collapser1.getMetrics();
assertSame(metrics, collapser2.getMetrics());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator().next();
assertEquals(1, command.getNumberCollapsed()); //1 should have been removed from batch
}
@Test
public void testEarlyUnsubscribeExecutedViaObserve() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixObservableCollapser<String, String, String, String> collapser1 = new TestRequestCollapser(timer, 1);
Observable<String> response1 = collapser1.observe();
HystrixObservableCollapser<String, String, String, String> collapser2 = new TestRequestCollapser(timer, 2);
Observable<String> response2 = collapser2.observe();
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final AtomicReference<String> value1 = new AtomicReference<String>(null);
final AtomicReference<String> value2 = new AtomicReference<String>(null);
Subscription s1 = response1
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s1 Unsubscribed!");
latch1.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s1 OnCompleted");
latch1.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s1 OnError : " + e);
latch1.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s1 OnNext : " + s);
value1.set(s);
}
});
Subscription s2 = response2
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s2 Unsubscribed!");
latch2.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s2 OnCompleted");
latch2.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s2 OnError : " + e);
latch2.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s2 OnNext : " + s);
value2.set(s);
}
});
s1.unsubscribe();
timer.incrementTime(10); // let time pass that equals the default delay/period
assertTrue(latch1.await(1000, TimeUnit.MILLISECONDS));
assertTrue(latch2.await(1000, TimeUnit.MILLISECONDS));
assertNull(value1.get());
assertEquals("2", value2.get());
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixCollapserMetrics metrics = collapser1.getMetrics();
assertSame(metrics, collapser2.getMetrics());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator().next();
assertEquals(1, command.getNumberCollapsed()); //1 should have been removed from batch
}
@Test
public void testEarlyUnsubscribeFromAllCancelsBatch() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixObservableCollapser<String, String, String, String> collapser1 = new TestRequestCollapser(timer, 1);
Observable<String> response1 = collapser1.observe();
HystrixObservableCollapser<String, String, String, String> collapser2 = new TestRequestCollapser(timer, 2);
Observable<String> response2 = collapser2.observe();
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final AtomicReference<String> value1 = new AtomicReference<String>(null);
final AtomicReference<String> value2 = new AtomicReference<String>(null);
Subscription s1 = response1
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s1 Unsubscribed!");
latch1.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s1 OnCompleted");
latch1.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s1 OnError : " + e);
latch1.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s1 OnNext : " + s);
value1.set(s);
}
});
Subscription s2 = response2
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s2 Unsubscribed!");
latch2.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s2 OnCompleted");
latch2.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s2 OnError : " + e);
latch2.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s2 OnNext : " + s);
value2.set(s);
}
});
s1.unsubscribe();
s2.unsubscribe();
timer.incrementTime(10); // let time pass that equals the default delay/period
assertTrue(latch1.await(1000, TimeUnit.MILLISECONDS));
assertTrue(latch2.await(1000, TimeUnit.MILLISECONDS));
assertNull(value1.get());
assertNull(value2.get());
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertEquals(0, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
}
@Test
public void testRequestThenCacheHitAndCacheHitUnsubscribed() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixObservableCollapser<String, String, String, String> collapser1 = new SuccessfulCacheableCollapsedCommand(timer, "foo", true);
Observable<String> response1 = collapser1.observe();
HystrixObservableCollapser<String, String, String, String> collapser2 = new SuccessfulCacheableCollapsedCommand(timer, "foo", true);
Observable<String> response2 = collapser2.observe();
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final AtomicReference<String> value1 = new AtomicReference<String>(null);
final AtomicReference<String> value2 = new AtomicReference<String>(null);
Subscription s1 = response1
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s1 Unsubscribed!");
latch1.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s1 OnCompleted");
latch1.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s1 OnError : " + e);
latch1.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s1 OnNext : " + s);
value1.set(s);
}
});
Subscription s2 = response2
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s2 Unsubscribed!");
latch2.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s2 OnCompleted");
latch2.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s2 OnError : " + e);
latch2.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s2 OnNext : " + s);
value2.set(s);
}
});
s2.unsubscribe();
timer.incrementTime(10); // let time pass that equals the default delay/period
assertTrue(latch1.await(1000, TimeUnit.MILLISECONDS));
assertTrue(latch2.await(1000, TimeUnit.MILLISECONDS));
assertEquals("foo", value1.get());
assertNull(value2.get());
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator().next();
assertCommandExecutionEvents(command, HystrixEventType.EMIT, HystrixEventType.SUCCESS, HystrixEventType.COLLAPSED);
assertEquals(1, command.getNumberCollapsed()); //should only be 1 collapsed - other came from cache, then was cancelled
}
@Test
public void testRequestThenCacheHitAndOriginalUnsubscribed() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixObservableCollapser<String, String, String, String> collapser1 = new SuccessfulCacheableCollapsedCommand(timer, "foo", true);
Observable<String> response1 = collapser1.observe();
HystrixObservableCollapser<String, String, String, String> collapser2 = new SuccessfulCacheableCollapsedCommand(timer, "foo", true);
Observable<String> response2 = collapser2.observe();
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final AtomicReference<String> value1 = new AtomicReference<String>(null);
final AtomicReference<String> value2 = new AtomicReference<String>(null);
Subscription s1 = response1
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s1 Unsubscribed!");
latch1.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s1 OnCompleted");
latch1.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s1 OnError : " + e);
latch1.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s1 OnNext : " + s);
value1.set(s);
}
});
Subscription s2 = response2
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s2 Unsubscribed!");
latch2.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s2 OnCompleted");
latch2.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s2 OnError : " + e);
latch2.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s2 OnNext : " + s);
value2.set(s);
}
});
s1.unsubscribe();
timer.incrementTime(10); // let time pass that equals the default delay/period
assertTrue(latch1.await(1000, TimeUnit.MILLISECONDS));
assertTrue(latch2.await(1000, TimeUnit.MILLISECONDS));
assertNull(value1.get());
assertEquals("foo", value2.get());
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator().next();
assertCommandExecutionEvents(command, HystrixEventType.EMIT, HystrixEventType.SUCCESS, HystrixEventType.COLLAPSED);
assertEquals(1, command.getNumberCollapsed()); //should only be 1 collapsed - other came from cache, then was cancelled
}
@Test
public void testRequestThenTwoCacheHitsOriginalAndOneCacheHitUnsubscribed() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixObservableCollapser<String, String, String, String> collapser1 = new SuccessfulCacheableCollapsedCommand(timer, "foo", true);
Observable<String> response1 = collapser1.observe();
HystrixObservableCollapser<String, String, String, String> collapser2 = new SuccessfulCacheableCollapsedCommand(timer, "foo", true);
Observable<String> response2 = collapser2.observe();
HystrixObservableCollapser<String, String, String, String> collapser3 = new SuccessfulCacheableCollapsedCommand(timer, "foo", true);
Observable<String> response3 = collapser3.observe();
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final CountDownLatch latch3 = new CountDownLatch(1);
final AtomicReference<String> value1 = new AtomicReference<String>(null);
final AtomicReference<String> value2 = new AtomicReference<String>(null);
final AtomicReference<String> value3 = new AtomicReference<String>(null);
Subscription s1 = response1
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s1 Unsubscribed!");
latch1.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s1 OnCompleted");
latch1.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s1 OnError : " + e);
latch1.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s1 OnNext : " + s);
value1.set(s);
}
});
Subscription s2 = response2
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s2 Unsubscribed!");
latch2.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s2 OnCompleted");
latch2.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s2 OnError : " + e);
latch2.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s2 OnNext : " + s);
value2.set(s);
}
});
Subscription s3 = response3
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s3 Unsubscribed!");
latch3.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s3 OnCompleted");
latch3.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s3 OnError : " + e);
latch3.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s3 OnNext : " + s);
value3.set(s);
}
});
s1.unsubscribe();
s3.unsubscribe();
timer.incrementTime(10); // let time pass that equals the default delay/period
assertTrue(latch1.await(1000, TimeUnit.MILLISECONDS));
assertTrue(latch2.await(1000, TimeUnit.MILLISECONDS));
assertNull(value1.get());
assertEquals("foo", value2.get());
assertNull(value3.get());
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
HystrixInvokableInfo<?> command = HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().iterator().next();
assertCommandExecutionEvents(command, HystrixEventType.EMIT, HystrixEventType.SUCCESS, HystrixEventType.COLLAPSED);
assertEquals(1, command.getNumberCollapsed()); //should only be 1 collapsed - other came from cache, then was cancelled
}
@Test
public void testRequestThenTwoCacheHitsAllUnsubscribed() throws Exception {
TestCollapserTimer timer = new TestCollapserTimer();
HystrixObservableCollapser<String, String, String, String> collapser1 = new SuccessfulCacheableCollapsedCommand(timer, "foo", true);
Observable<String> response1 = collapser1.observe();
HystrixObservableCollapser<String, String, String, String> collapser2 = new SuccessfulCacheableCollapsedCommand(timer, "foo", true);
Observable<String> response2 = collapser2.observe();
HystrixObservableCollapser<String, String, String, String> collapser3 = new SuccessfulCacheableCollapsedCommand(timer, "foo", true);
Observable<String> response3 = collapser3.observe();
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final CountDownLatch latch3 = new CountDownLatch(1);
final AtomicReference<String> value1 = new AtomicReference<String>(null);
final AtomicReference<String> value2 = new AtomicReference<String>(null);
final AtomicReference<String> value3 = new AtomicReference<String>(null);
Subscription s1 = response1
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s1 Unsubscribed!");
latch1.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s1 OnCompleted");
latch1.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s1 OnError : " + e);
latch1.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s1 OnNext : " + s);
value1.set(s);
}
});
Subscription s2 = response2
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s2 Unsubscribed!");
latch2.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s2 OnCompleted");
latch2.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s2 OnError : " + e);
latch2.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s2 OnNext : " + s);
value2.set(s);
}
});
Subscription s3 = response3
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println(System.currentTimeMillis() + " : s3 Unsubscribed!");
latch3.countDown();
}
})
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : s3 OnCompleted");
latch3.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : s3 OnError : " + e);
latch3.countDown();
}
@Override
public void onNext(String s) {
System.out.println(System.currentTimeMillis() + " : s3 OnNext : " + s);
value3.set(s);
}
});
s1.unsubscribe();
s2.unsubscribe();
s3.unsubscribe();
timer.incrementTime(10); // let time pass that equals the default delay/period
assertTrue(latch1.await(1000, TimeUnit.MILLISECONDS));
assertTrue(latch2.await(1000, TimeUnit.MILLISECONDS));
assertNull(value1.get());
assertNull(value2.get());
assertNull(value3.get());
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertEquals(0, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
}
class Pair<A, B> {
final A a;
final B b;
Pair(A a, B b) {
this.a = a;
this.b = b;
}
}
class MyCommand extends HystrixObservableCommand<Pair<String, Integer>> {
private final List<String> args;
public MyCommand(List<String> args) {
super(HystrixObservableCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("BATCH")));
this.args = args;
}
@Override
protected Observable<Pair<String, Integer>> construct() {
return Observable.from(args).map(new Func1<String, Pair<String, Integer>>() {
@Override
public Pair<String, Integer> call(String s) {
return new Pair<String, Integer>(s, Integer.parseInt(s));
}
});
}
}
class MyCollapser extends HystrixObservableCollapser<String, Pair<String, Integer>, Integer, String> {
private final String arg;
public MyCollapser(String arg, boolean requestCachingOn) {
super(HystrixCollapserKey.Factory.asKey("UNITTEST"),
HystrixObservableCollapser.Scope.REQUEST,
new RealCollapserTimer(),
HystrixCollapserProperties.Setter().withRequestCacheEnabled(requestCachingOn),
HystrixCollapserMetrics.getInstance(HystrixCollapserKey.Factory.asKey("UNITTEST"),
new HystrixPropertiesCollapserDefault(HystrixCollapserKey.Factory.asKey("UNITTEST"),
HystrixCollapserProperties.Setter())));
this.arg = arg;
}
@Override
public String getRequestArgument() {
return arg;
}
@Override
protected HystrixObservableCommand<Pair<String, Integer>> createCommand(Collection<CollapsedRequest<Integer, String>> collapsedRequests) {
List<String> args = new ArrayList<String>();
for (CollapsedRequest<Integer, String> req: collapsedRequests) {
args.add(req.getArgument());
}
return new MyCommand(args);
}
@Override
protected Func1<Pair<String, Integer>, String> getBatchReturnTypeKeySelector() {
return new Func1<Pair<String, Integer>, String>() {
@Override
public String call(Pair<String, Integer> pair) {
return pair.a;
}
};
}
@Override
protected Func1<String, String> getRequestArgumentKeySelector() {
return new Func1<String, String>() {
@Override
public String call(String s) {
return s;
}
};
}
@Override
protected void onMissingResponse(CollapsedRequest<Integer, String> r) {
r.setException(new RuntimeException("missing"));
}
@Override
protected Func1<Pair<String, Integer>, Integer> getBatchReturnTypeToResponseTypeMapper() {
return new Func1<Pair<String, Integer>, Integer>() {
@Override
public Integer call(Pair<String, Integer> pair) {
return pair.b;
}
};
}
}
@Test
public void testDuplicateArgumentsWithRequestCachingOn() throws Exception {
final int NUM = 10;
List<Observable<Integer>> observables = new ArrayList<Observable<Integer>>();
for (int i = 0; i < NUM; i++) {
MyCollapser c = new MyCollapser("5", true);
observables.add(c.toObservable());
}
List<TestSubscriber<Integer>> subscribers = new ArrayList<TestSubscriber<Integer>>();
for (final Observable<Integer> o: observables) {
final TestSubscriber<Integer> sub = new TestSubscriber<Integer>();
subscribers.add(sub);
o.subscribe(sub);
}
Thread.sleep(100);
//all subscribers should receive the same value
for (TestSubscriber<Integer> sub: subscribers) {
sub.awaitTerminalEvent(1000, TimeUnit.MILLISECONDS);
System.out.println("Subscriber received : " + sub.getOnNextEvents());
sub.assertCompleted();
sub.assertNoErrors();
sub.assertValues(5);
}
}
@Test
public void testDuplicateArgumentsWithRequestCachingOff() throws Exception {
final int NUM = 10;
List<Observable<Integer>> observables = new ArrayList<Observable<Integer>>();
for (int i = 0; i < NUM; i++) {
MyCollapser c = new MyCollapser("5", false);
observables.add(c.toObservable());
}
List<TestSubscriber<Integer>> subscribers = new ArrayList<TestSubscriber<Integer>>();
for (final Observable<Integer> o: observables) {
final TestSubscriber<Integer> sub = new TestSubscriber<Integer>();
subscribers.add(sub);
o.subscribe(sub);
}
Thread.sleep(100);
AtomicInteger numErrors = new AtomicInteger(0);
AtomicInteger numValues = new AtomicInteger(0);
// only the first subscriber should receive the value.
// the others should get an error that the batch contains duplicates
for (TestSubscriber<Integer> sub: subscribers) {
sub.awaitTerminalEvent(1000, TimeUnit.MILLISECONDS);
if (sub.getOnCompletedEvents().isEmpty()) {
System.out.println(Thread.currentThread().getName() + " Error : " + sub.getOnErrorEvents());
sub.assertError(IllegalArgumentException.class);
sub.assertNoValues();
numErrors.getAndIncrement();
} else {
System.out.println(Thread.currentThread().getName() + " OnNext : " + sub.getOnNextEvents());
sub.assertValues(5);
sub.assertCompleted();
sub.assertNoErrors();
numValues.getAndIncrement();
}
}
assertEquals(1, numValues.get());
assertEquals(NUM - 1, numErrors.get());
}
protected void assertCommandExecutionEvents(HystrixInvokableInfo<?> command, HystrixEventType... expectedEventTypes) {
boolean emitExpected = false;
int expectedEmitCount = 0;
boolean fallbackEmitExpected = false;
int expectedFallbackEmitCount = 0;
List<HystrixEventType> condensedEmitExpectedEventTypes = new ArrayList<HystrixEventType>();
for (HystrixEventType expectedEventType: expectedEventTypes) {
if (expectedEventType.equals(HystrixEventType.EMIT)) {
if (!emitExpected) {
//first EMIT encountered, add it to condensedEmitExpectedEventTypes
condensedEmitExpectedEventTypes.add(HystrixEventType.EMIT);
}
emitExpected = true;
expectedEmitCount++;
} else if (expectedEventType.equals(HystrixEventType.FALLBACK_EMIT)) {
if (!fallbackEmitExpected) {
//first FALLBACK_EMIT encountered, add it to condensedEmitExpectedEventTypes
condensedEmitExpectedEventTypes.add(HystrixEventType.FALLBACK_EMIT);
}
fallbackEmitExpected = true;
expectedFallbackEmitCount++;
} else {
condensedEmitExpectedEventTypes.add(expectedEventType);
}
}
List<HystrixEventType> actualEventTypes = command.getExecutionEvents();
assertEquals(expectedEmitCount, command.getNumberEmissions());
assertEquals(expectedFallbackEmitCount, command.getNumberFallbackEmissions());
assertEquals(condensedEmitExpectedEventTypes, actualEventTypes);
}
private static class TestRequestCollapser extends HystrixObservableCollapser<String, String, String, String> {
private final String value;
private ConcurrentLinkedQueue<HystrixObservableCommand<String>> commandsExecuted;
public TestRequestCollapser(TestCollapserTimer timer, int value) {
this(timer, String.valueOf(value));
}
public TestRequestCollapser(TestCollapserTimer timer, String value) {
this(timer, value, 10000, 10);
}
public TestRequestCollapser(TestCollapserTimer timer, String value, ConcurrentLinkedQueue<HystrixObservableCommand<String>> executionLog) {
this(timer, value, 10000, 10, executionLog);
}
public TestRequestCollapser(TestCollapserTimer timer, int value, int defaultMaxRequestsInBatch, int defaultTimerDelayInMilliseconds) {
this(timer, String.valueOf(value), defaultMaxRequestsInBatch, defaultTimerDelayInMilliseconds);
}
public TestRequestCollapser(TestCollapserTimer timer, String value, int defaultMaxRequestsInBatch, int defaultTimerDelayInMilliseconds) {
this(timer, value, defaultMaxRequestsInBatch, defaultTimerDelayInMilliseconds, null);
}
public TestRequestCollapser(Scope scope, TestCollapserTimer timer, String value, int defaultMaxRequestsInBatch, int defaultTimerDelayInMilliseconds) {
this(scope, timer, value, defaultMaxRequestsInBatch, defaultTimerDelayInMilliseconds, null);
}
public TestRequestCollapser(TestCollapserTimer timer, String value, int defaultMaxRequestsInBatch, int defaultTimerDelayInMilliseconds, ConcurrentLinkedQueue<HystrixObservableCommand<String>> executionLog) {
this(Scope.REQUEST, timer, value, defaultMaxRequestsInBatch, defaultTimerDelayInMilliseconds, executionLog);
}
private static HystrixCollapserMetrics createMetrics() {
HystrixCollapserKey key = HystrixCollapserKey.Factory.asKey("COLLAPSER_ONE");
return HystrixCollapserMetrics.getInstance(key, new HystrixPropertiesCollapserDefault(key, HystrixCollapserProperties.Setter()));
}
public TestRequestCollapser(Scope scope, TestCollapserTimer timer, String value, int defaultMaxRequestsInBatch, int defaultTimerDelayInMilliseconds, ConcurrentLinkedQueue<HystrixObservableCommand<String>> executionLog) {
// use a CollapserKey based on the CollapserTimer object reference so it's unique for each timer as we don't want caching
// of properties to occur and we're using the default HystrixProperty which typically does caching
super(collapserKeyFromString(timer), scope, timer, HystrixCollapserProperties.Setter().withMaxRequestsInBatch(defaultMaxRequestsInBatch).withTimerDelayInMilliseconds(defaultTimerDelayInMilliseconds), createMetrics());
this.value = value;
this.commandsExecuted = executionLog;
}
@Override
public String getRequestArgument() {
return value;
}
@Override
public HystrixObservableCommand<String> createCommand(final Collection<CollapsedRequest<String, String>> requests) {
/* return a mocked command */
HystrixObservableCommand<String> command = new TestCollapserCommand(requests);
if (commandsExecuted != null) {
commandsExecuted.add(command);
}
return command;
}
@Override
protected Func1<String, String> getBatchReturnTypeToResponseTypeMapper() {
return new Func1<String, String>() {
@Override
public String call(String s) {
return s;
}
};
}
@Override
protected Func1<String, String> getBatchReturnTypeKeySelector() {
return new Func1<String, String>() {
@Override
public String call(String s) {
return s;
}
};
}
@Override
protected Func1<String, String> getRequestArgumentKeySelector() {
return new Func1<String, String>() {
@Override
public String call(String s) {
return s;
}
};
}
@Override
protected void onMissingResponse(CollapsedRequest<String, String> r) {
r.setException(new RuntimeException("missing value!"));
}
}
private static HystrixCollapserKey collapserKeyFromString(final Object o) {
return new HystrixCollapserKey() {
@Override
public String name() {
return String.valueOf(o);
}
};
}
private static class TestCollapserCommand extends TestHystrixObservableCommand<String> {
private final Collection<CollapsedRequest<String, String>> requests;
TestCollapserCommand(Collection<CollapsedRequest<String, String>> requests) {
super(testPropsBuilder().setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionTimeoutInMilliseconds(1000)));
this.requests = requests;
}
@Override
protected Observable<String> construct() {
return Observable.create(new OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> s) {
System.out.println(">>> TestCollapserCommand run() ... batch size: " + requests.size());
// simulate a batch request
for (CollapsedRequest<String, String> request : requests) {
if (request.getArgument() == null) {
throw new NullPointerException("Simulated Error");
}
if (request.getArgument().equals("TIMEOUT")) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
s.onNext(request.getArgument());
}
s.onCompleted();
}
}).subscribeOn(Schedulers.computation());
}
}
private static class TestCollapserWithMultipleResponses extends HystrixObservableCollapser<String, String, String, String> {
private final String arg;
private final static ConcurrentMap<String, Integer> emitsPerArg;
private final boolean commandConstructionFails;
private final boolean commandExecutionFails;
private final Func1<String, String> keyMapper;
private final Action1<CollapsedRequest<String, String>> onMissingResponseHandler;
private final static HystrixCollapserKey key = HystrixCollapserKey.Factory.asKey("COLLAPSER_MULTI");
private final static HystrixCollapserProperties.Setter propsSetter = HystrixCollapserProperties.Setter().withMaxRequestsInBatch(10).withTimerDelayInMilliseconds(10);
private final static HystrixCollapserMetrics metrics = HystrixCollapserMetrics.getInstance(key, new HystrixPropertiesCollapserDefault(key, HystrixCollapserProperties.Setter()));
static {
emitsPerArg = new ConcurrentHashMap<String, Integer>();
}
public TestCollapserWithMultipleResponses(CollapserTimer timer, int arg, int numEmits, boolean commandConstructionFails) {
this(timer, arg, numEmits, commandConstructionFails, false, prefixMapper, onMissingComplete);
}
public TestCollapserWithMultipleResponses(CollapserTimer timer, int arg, int numEmits, Action1<CollapsedRequest<String, String>> onMissingHandler) {
this(timer, arg, numEmits, false, false, prefixMapper, onMissingHandler);
}
public TestCollapserWithMultipleResponses(CollapserTimer timer, int arg, int numEmits, Func1<String, String> keyMapper) {
this(timer, arg, numEmits, false, false, keyMapper, onMissingComplete);
}
public TestCollapserWithMultipleResponses(CollapserTimer timer, int arg, int numEmits, boolean commandConstructionFails, boolean commandExecutionFails, Func1<String, String> keyMapper, Action1<CollapsedRequest<String, String>> onMissingResponseHandler) {
super(collapserKeyFromString(timer), Scope.REQUEST, timer, propsSetter, metrics);
this.arg = arg + "";
emitsPerArg.put(this.arg, numEmits);
this.commandConstructionFails = commandConstructionFails;
this.commandExecutionFails = commandExecutionFails;
this.keyMapper = keyMapper;
this.onMissingResponseHandler = onMissingResponseHandler;
}
@Override
public String getRequestArgument() {
return arg;
}
@Override
protected HystrixObservableCommand<String> createCommand(Collection<CollapsedRequest<String, String>> collapsedRequests) {
assertNotNull("command creation should have HystrixRequestContext", HystrixRequestContext.getContextForCurrentThread());
if (commandConstructionFails) {
throw new RuntimeException("Exception thrown in command construction");
} else {
List<Integer> args = new ArrayList<Integer>();
for (CollapsedRequest<String, String> collapsedRequest : collapsedRequests) {
String stringArg = collapsedRequest.getArgument();
int intArg = Integer.parseInt(stringArg);
args.add(intArg);
}
return new TestCollapserCommandWithMultipleResponsePerArgument(args, emitsPerArg, commandExecutionFails);
}
}
//Data comes back in the form: 1:1, 1:2, 1:3, 2:2, 2:4, 2:6.
//This method should use the first half of that string as the request arg
@Override
protected Func1<String, String> getBatchReturnTypeKeySelector() {
return keyMapper;
}
@Override
protected Func1<String, String> getRequestArgumentKeySelector() {
return new Func1<String, String>() {
@Override
public String call(String s) {
return s;
}
};
}
@Override
protected void onMissingResponse(CollapsedRequest<String, String> r) {
onMissingResponseHandler.call(r);
}
@Override
protected Func1<String, String> getBatchReturnTypeToResponseTypeMapper() {
return new Func1<String, String>() {
@Override
public String call(String s) {
return s;
}
};
}
}
private static class TestCollapserCommandWithMultipleResponsePerArgument extends TestHystrixObservableCommand<String> {
private final List<Integer> args;
private final Map<String, Integer> emitsPerArg;
private final boolean commandExecutionFails;
private static InspectableBuilder.TestCommandBuilder setter = testPropsBuilder();
TestCollapserCommandWithMultipleResponsePerArgument(List<Integer> args, Map<String, Integer> emitsPerArg, boolean commandExecutionFails) {
super(setter);
this.args = args;
this.emitsPerArg = emitsPerArg;
this.commandExecutionFails = commandExecutionFails;
}
@Override
protected Observable<String> construct() {
assertNotNull("Wiring the Batch command into the Observable chain should have a HystrixRequestContext", HystrixRequestContext.getContextForCurrentThread());
if (commandExecutionFails) {
return Observable.error(new RuntimeException("Synthetic error while running batch command"));
} else {
return Observable.create(new OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
try {
assertNotNull("Executing the Batch command should have a HystrixRequestContext", HystrixRequestContext.getContextForCurrentThread());
Thread.sleep(1);
for (Integer arg : args) {
int numEmits = emitsPerArg.get(arg.toString());
for (int j = 1; j < numEmits + 1; j++) {
subscriber.onNext(arg + ":" + (arg * j));
Thread.sleep(1);
}
Thread.sleep(1);
}
subscriber.onCompleted();
} catch (Throwable ex) {
ex.printStackTrace();
subscriber.onError(ex);
}
}
});
}
}
}
/**
* A Command implementation that supports caching.
*/
private static class SuccessfulCacheableCollapsedCommand extends TestRequestCollapser {
private final boolean cacheEnabled;
public SuccessfulCacheableCollapsedCommand(TestCollapserTimer timer, String value, boolean cacheEnabled) {
super(timer, value);
this.cacheEnabled = cacheEnabled;
}
@Override
public String getCacheKey() {
if (cacheEnabled)
return "aCacheKey_" + super.value;
else
return null;
}
}
}
| 4,565 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/HystrixCircuitBreakerTest.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Random;
import com.hystrix.junit.HystrixRequestContextRule;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import com.netflix.hystrix.HystrixCircuitBreaker.HystrixCircuitBreakerImpl;
import com.netflix.hystrix.strategy.HystrixPlugins;
import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook;
import rx.Observable;
import rx.Subscription;
/**
* These tests each use a different command key to ensure that running them in parallel doesn't allow the state
* built up during a test to cause others to fail
*/
public class HystrixCircuitBreakerTest {
@Rule
public HystrixRequestContextRule ctx = new HystrixRequestContextRule();
@Before
public void init() {
for (HystrixCommandMetrics metricsInstance: HystrixCommandMetrics.getInstances()) {
metricsInstance.resetStream();
}
HystrixCommandMetrics.reset();
HystrixCircuitBreaker.Factory.reset();
Hystrix.reset();
}
/**
* A simple circuit breaker intended for unit testing of the {@link HystrixCommand} object, NOT production use.
* <p>
* This uses simple logic to 'trip' the circuit after 3 subsequent failures and doesn't recover.
*/
public static class TestCircuitBreaker implements HystrixCircuitBreaker {
final HystrixCommandMetrics metrics;
private boolean forceShortCircuit = false;
public TestCircuitBreaker() {
this.metrics = getMetrics(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter());
forceShortCircuit = false;
}
public TestCircuitBreaker(HystrixCommandKey commandKey) {
this.metrics = getMetrics(commandKey, HystrixCommandPropertiesTest.getUnitTestPropertiesSetter());
forceShortCircuit = false;
}
public TestCircuitBreaker setForceShortCircuit(boolean value) {
this.forceShortCircuit = value;
return this;
}
@Override
public boolean isOpen() {
System.out.println("metrics : " + metrics.getCommandKey().name() + " : " + metrics.getHealthCounts());
if (forceShortCircuit) {
return true;
} else {
return metrics.getHealthCounts().getErrorCount() >= 3;
}
}
@Override
public void markSuccess() {
// we don't need to do anything since we're going to permanently trip the circuit
}
@Override
public void markNonSuccess() {
}
@Override
public boolean attemptExecution() {
return !isOpen();
}
@Override
public boolean allowRequest() {
return !isOpen();
}
}
/**
* Test that if all 'marks' are successes during the test window that it does NOT trip the circuit.
* Test that if all 'marks' are failures during the test window that it trips the circuit.
*/
@Test
public void testTripCircuit() {
String key = "cmd-A";
try {
HystrixCommand<Boolean> cmd1 = new SuccessCommand(key, 1);
HystrixCommand<Boolean> cmd2 = new SuccessCommand(key, 1);
HystrixCommand<Boolean> cmd3 = new SuccessCommand(key, 1);
HystrixCommand<Boolean> cmd4 = new SuccessCommand(key, 1);
HystrixCircuitBreaker cb = cmd1.circuitBreaker;
cmd1.execute();
cmd2.execute();
cmd3.execute();
cmd4.execute();
// this should still allow requests as everything has been successful
Thread.sleep(100);
//assertTrue(cb.allowRequest());
assertFalse(cb.isOpen());
// fail
HystrixCommand<Boolean> cmd5 = new FailureCommand(key, 1);
HystrixCommand<Boolean> cmd6 = new FailureCommand(key, 1);
HystrixCommand<Boolean> cmd7 = new FailureCommand(key, 1);
HystrixCommand<Boolean> cmd8 = new FailureCommand(key, 1);
cmd5.execute();
cmd6.execute();
cmd7.execute();
cmd8.execute();
// everything has failed in the test window so we should return false now
Thread.sleep(100);
assertFalse(cb.allowRequest());
assertTrue(cb.isOpen());
} catch (Exception e) {
e.printStackTrace();
fail("Error occurred: " + e.getMessage());
}
}
/**
* Test that if the % of failures is higher than the threshold that the circuit trips.
*/
@Test
public void testTripCircuitOnFailuresAboveThreshold() {
String key = "cmd-B";
try {
HystrixCommand<Boolean> cmd1 = new SuccessCommand(key, 60);
HystrixCircuitBreaker cb = cmd1.circuitBreaker;
// this should start as allowing requests
assertTrue(cb.allowRequest());
assertFalse(cb.isOpen());
// success with high latency
cmd1.execute();
HystrixCommand<Boolean> cmd2 = new SuccessCommand(key, 1);
cmd2.execute();
HystrixCommand<Boolean> cmd3 = new FailureCommand(key, 1);
cmd3.execute();
HystrixCommand<Boolean> cmd4 = new SuccessCommand(key, 1);
cmd4.execute();
HystrixCommand<Boolean> cmd5 = new FailureCommand(key, 1);
cmd5.execute();
HystrixCommand<Boolean> cmd6 = new SuccessCommand(key, 1);
cmd6.execute();
HystrixCommand<Boolean> cmd7 = new FailureCommand(key, 1);
cmd7.execute();
HystrixCommand<Boolean> cmd8 = new FailureCommand(key, 1);
cmd8.execute();
// this should trip the circuit as the error percentage is above the threshold
Thread.sleep(100);
assertFalse(cb.allowRequest());
assertTrue(cb.isOpen());
} catch (Exception e) {
e.printStackTrace();
fail("Error occurred: " + e.getMessage());
}
}
/**
* Test that if the % of failures is higher than the threshold that the circuit trips.
*/
@Test
public void testCircuitDoesNotTripOnFailuresBelowThreshold() {
String key = "cmd-C";
try {
HystrixCommand<Boolean> cmd1 = new SuccessCommand(key, 60);
HystrixCircuitBreaker cb = cmd1.circuitBreaker;
// this should start as allowing requests
assertTrue(cb.allowRequest());
assertFalse(cb.isOpen());
// success with high latency
cmd1.execute();
HystrixCommand<Boolean> cmd2 = new SuccessCommand(key, 1);
cmd2.execute();
HystrixCommand<Boolean> cmd3 = new FailureCommand(key, 1);
cmd3.execute();
HystrixCommand<Boolean> cmd4 = new SuccessCommand(key, 1);
cmd4.execute();
HystrixCommand<Boolean> cmd5 = new SuccessCommand(key, 1);
cmd5.execute();
HystrixCommand<Boolean> cmd6 = new FailureCommand(key, 1);
cmd6.execute();
HystrixCommand<Boolean> cmd7 = new SuccessCommand(key, 1);
cmd7.execute();
HystrixCommand<Boolean> cmd8 = new FailureCommand(key, 1);
cmd8.execute();
// this should remain closed as the failure threshold is below the percentage limit
Thread.sleep(100);
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
System.out.println("Current CircuitBreaker Status : " + cmd1.getMetrics().getHealthCounts());
assertTrue(cb.allowRequest());
assertFalse(cb.isOpen());
} catch (Exception e) {
e.printStackTrace();
fail("Error occurred: " + e.getMessage());
}
}
/**
* Test that if all 'marks' are timeouts that it will trip the circuit.
*/
@Test
public void testTripCircuitOnTimeouts() {
String key = "cmd-D";
try {
HystrixCommand<Boolean> cmd1 = new TimeoutCommand(key);
HystrixCircuitBreaker cb = cmd1.circuitBreaker;
// this should start as allowing requests
assertTrue(cb.allowRequest());
assertFalse(cb.isOpen());
// success with high latency
cmd1.execute();
HystrixCommand<Boolean> cmd2 = new TimeoutCommand(key);
cmd2.execute();
HystrixCommand<Boolean> cmd3 = new TimeoutCommand(key);
cmd3.execute();
HystrixCommand<Boolean> cmd4 = new TimeoutCommand(key);
cmd4.execute();
// everything has been a timeout so we should not allow any requests
Thread.sleep(100);
assertFalse(cb.allowRequest());
assertTrue(cb.isOpen());
} catch (Exception e) {
e.printStackTrace();
fail("Error occurred: " + e.getMessage());
}
}
/**
* Test that if the % of timeouts is higher than the threshold that the circuit trips.
*/
@Test
public void testTripCircuitOnTimeoutsAboveThreshold() {
String key = "cmd-E";
try {
HystrixCommand<Boolean> cmd1 = new SuccessCommand(key, 60);
HystrixCircuitBreaker cb = cmd1.circuitBreaker;
// this should start as allowing requests
assertTrue(cb.allowRequest());
assertFalse(cb.isOpen());
// success with high latency
cmd1.execute();
HystrixCommand<Boolean> cmd2 = new SuccessCommand(key, 1);
cmd2.execute();
HystrixCommand<Boolean> cmd3 = new TimeoutCommand(key);
cmd3.execute();
HystrixCommand<Boolean> cmd4 = new SuccessCommand(key, 1);
cmd4.execute();
HystrixCommand<Boolean> cmd5 = new TimeoutCommand(key);
cmd5.execute();
HystrixCommand<Boolean> cmd6 = new TimeoutCommand(key);
cmd6.execute();
HystrixCommand<Boolean> cmd7 = new SuccessCommand(key, 1);
cmd7.execute();
HystrixCommand<Boolean> cmd8 = new TimeoutCommand(key);
cmd8.execute();
HystrixCommand<Boolean> cmd9 = new TimeoutCommand(key);
cmd9.execute();
// this should trip the circuit as the error percentage is above the threshold
Thread.sleep(100);
assertTrue(cb.isOpen());
} catch (Exception e) {
e.printStackTrace();
fail("Error occurred: " + e.getMessage());
}
}
/**
* Test that on an open circuit that a single attempt will be allowed after a window of time to see if issues are resolved.
*/
@Test
public void testSingleTestOnOpenCircuitAfterTimeWindow() {
String key = "cmd-F";
try {
int sleepWindow = 200;
HystrixCommand<Boolean> cmd1 = new FailureCommand(key, 60);
HystrixCircuitBreaker cb = cmd1.circuitBreaker;
// this should start as allowing requests
assertTrue(cb.allowRequest());
assertFalse(cb.isOpen());
cmd1.execute();
HystrixCommand<Boolean> cmd2 = new FailureCommand(key, 1);
cmd2.execute();
HystrixCommand<Boolean> cmd3 = new FailureCommand(key, 1);
cmd3.execute();
HystrixCommand<Boolean> cmd4 = new FailureCommand(key, 1);
cmd4.execute();
// everything has failed in the test window so we should return false now
Thread.sleep(100);
assertFalse(cb.allowRequest());
assertTrue(cb.isOpen());
// wait for sleepWindow to pass
Thread.sleep(sleepWindow + 50);
// we should now allow 1 request
assertTrue(cb.attemptExecution());
// but the circuit should still be open
assertTrue(cb.isOpen());
// and further requests are still blocked
assertFalse(cb.attemptExecution());
} catch (Exception e) {
e.printStackTrace();
fail("Error occurred: " + e.getMessage());
}
}
/**
* Test that an open circuit is closed after 1 success. This also ensures that the rolling window (containing failures) is cleared after the sleep window
* Otherwise, the next bucket roll would produce another signal to fail unless it is explicitly cleared (via {@link HystrixCommandMetrics#resetStream()}.
*/
@Test
public void testCircuitClosedAfterSuccess() {
String key = "cmd-G";
try {
int sleepWindow = 100;
HystrixCommand<Boolean> cmd1 = new FailureCommand(key, 1, sleepWindow);
HystrixCircuitBreaker cb = cmd1.circuitBreaker;
// this should start as allowing requests
assertTrue(cb.allowRequest());
assertFalse(cb.isOpen());
cmd1.execute();
HystrixCommand<Boolean> cmd2 = new FailureCommand(key, 1, sleepWindow);
cmd2.execute();
HystrixCommand<Boolean> cmd3 = new FailureCommand(key, 1, sleepWindow);
cmd3.execute();
HystrixCommand<Boolean> cmd4 = new TimeoutCommand(key, sleepWindow);
cmd4.execute();
// everything has failed in the test window so we should return false now
Thread.sleep(100);
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
System.out.println("CircuitBreaker state 1 : " + cmd1.getMetrics().getHealthCounts());
assertTrue(cb.isOpen());
// wait for sleepWindow to pass
Thread.sleep(sleepWindow + 50);
// but the circuit should still be open
assertTrue(cb.isOpen());
// we should now allow 1 request, and upon success, should cause the circuit to be closed
HystrixCommand<Boolean> cmd5 = new SuccessCommand(key, 60, sleepWindow);
Observable<Boolean> asyncResult = cmd5.observe();
// and further requests are still blocked while the singleTest command is in flight
assertFalse(cb.allowRequest());
asyncResult.toBlocking().single();
// all requests should be open again
Thread.sleep(100);
System.out.println("CircuitBreaker state 2 : " + cmd1.getMetrics().getHealthCounts());
assertTrue(cb.allowRequest());
assertTrue(cb.allowRequest());
assertTrue(cb.allowRequest());
// and the circuit should be closed again
assertFalse(cb.isOpen());
} catch (Exception e) {
e.printStackTrace();
fail("Error occurred: " + e.getMessage());
}
}
/**
* Over a period of several 'windows' a single attempt will be made and fail and then finally succeed and close the circuit.
* <p>
* Ensure the circuit is kept open through the entire testing period and that only the single attempt in each window is made.
*/
@Test
public void testMultipleTimeWindowRetriesBeforeClosingCircuit() {
String key = "cmd-H";
try {
int sleepWindow = 200;
HystrixCommand<Boolean> cmd1 = new FailureCommand(key, 60);
HystrixCircuitBreaker cb = cmd1.circuitBreaker;
// this should start as allowing requests
assertTrue(cb.allowRequest());
assertFalse(cb.isOpen());
cmd1.execute();
HystrixCommand<Boolean> cmd2 = new FailureCommand(key, 1);
cmd2.execute();
HystrixCommand<Boolean> cmd3 = new FailureCommand(key, 1);
cmd3.execute();
HystrixCommand<Boolean> cmd4 = new TimeoutCommand(key);
cmd4.execute();
// everything has failed in the test window so we should return false now
System.out.println("!!!! 1: 4 failures, circuit will open on recalc");
Thread.sleep(100);
assertTrue(cb.isOpen());
// wait for sleepWindow to pass
System.out.println("!!!! 2: Sleep window starting where all commands fail-fast");
Thread.sleep(sleepWindow + 50);
System.out.println("!!!! 3: Sleep window over, should allow singleTest()");
// but the circuit should still be open
assertTrue(cb.isOpen());
// we should now allow 1 request, and upon failure, should not affect the circuit breaker, which should remain open
HystrixCommand<Boolean> cmd5 = new FailureCommand(key, 60);
Observable<Boolean> asyncResult5 = cmd5.observe();
System.out.println("!!!! 4: Kicked off the single-test");
// and further requests are still blocked while the singleTest command is in flight
assertFalse(cb.allowRequest());
System.out.println("!!!! 5: Confirmed that no other requests go out during single-test");
asyncResult5.toBlocking().single();
System.out.println("!!!! 6: SingleTest just completed");
// all requests should still be blocked, because the singleTest failed
assertFalse(cb.allowRequest());
assertFalse(cb.allowRequest());
assertFalse(cb.allowRequest());
// wait for sleepWindow to pass
System.out.println("!!!! 2nd sleep window START");
Thread.sleep(sleepWindow + 50);
System.out.println("!!!! 2nd sleep window over");
// we should now allow 1 request, and upon failure, should not affect the circuit breaker, which should remain open
HystrixCommand<Boolean> cmd6 = new FailureCommand(key, 60);
Observable<Boolean> asyncResult6 = cmd6.observe();
System.out.println("2nd singleTest just kicked off");
//and further requests are still blocked while the singleTest command is in flight
assertFalse(cb.allowRequest());
System.out.println("confirmed that 2nd singletest only happened once");
asyncResult6.toBlocking().single();
System.out.println("2nd singleTest now over");
// all requests should still be blocked, because the singleTest failed
assertFalse(cb.allowRequest());
assertFalse(cb.allowRequest());
assertFalse(cb.allowRequest());
// wait for sleepWindow to pass
Thread.sleep(sleepWindow + 50);
// but the circuit should still be open
assertTrue(cb.isOpen());
// we should now allow 1 request, and upon success, should cause the circuit to be closed
HystrixCommand<Boolean> cmd7 = new SuccessCommand(key, 60);
Observable<Boolean> asyncResult7 = cmd7.observe();
// and further requests are still blocked while the singleTest command is in flight
assertFalse(cb.allowRequest());
asyncResult7.toBlocking().single();
// all requests should be open again
assertTrue(cb.allowRequest());
assertTrue(cb.allowRequest());
assertTrue(cb.allowRequest());
// and the circuit should be closed again
assertFalse(cb.isOpen());
// and the circuit should be closed again
assertFalse(cb.isOpen());
} catch (Exception e) {
e.printStackTrace();
fail("Error occurred: " + e.getMessage());
}
}
/**
* When volume of reporting during a statistical window is lower than a defined threshold the circuit
* will not trip regardless of whatever statistics are calculated.
*/
@Test
public void testLowVolumeDoesNotTripCircuit() {
String key = "cmd-I";
try {
int sleepWindow = 200;
int lowVolume = 5;
HystrixCommand<Boolean> cmd1 = new FailureCommand(key, 60, sleepWindow, lowVolume);
HystrixCircuitBreaker cb = cmd1.circuitBreaker;
// this should start as allowing requests
assertTrue(cb.allowRequest());
assertFalse(cb.isOpen());
cmd1.execute();
HystrixCommand<Boolean> cmd2 = new FailureCommand(key, 1, sleepWindow, lowVolume);
cmd2.execute();
HystrixCommand<Boolean> cmd3 = new FailureCommand(key, 1, sleepWindow, lowVolume);
cmd3.execute();
HystrixCommand<Boolean> cmd4 = new FailureCommand(key, 1, sleepWindow, lowVolume);
cmd4.execute();
// even though it has all failed we won't trip the circuit because the volume is low
Thread.sleep(100);
assertTrue(cb.allowRequest());
assertFalse(cb.isOpen());
} catch (Exception e) {
e.printStackTrace();
fail("Error occurred: " + e.getMessage());
}
}
@Test
public void testUnsubscriptionDoesNotLeaveCircuitStuckHalfOpen() {
String key = "cmd-J";
try {
int sleepWindow = 200;
// fail
HystrixCommand<Boolean> cmd1 = new FailureCommand(key, 1, sleepWindow);
HystrixCommand<Boolean> cmd2 = new FailureCommand(key, 1, sleepWindow);
HystrixCommand<Boolean> cmd3 = new FailureCommand(key, 1, sleepWindow);
HystrixCommand<Boolean> cmd4 = new FailureCommand(key, 1, sleepWindow);
cmd1.execute();
cmd2.execute();
cmd3.execute();
cmd4.execute();
HystrixCircuitBreaker cb = cmd1.circuitBreaker;
// everything has failed in the test window so we should return false now
Thread.sleep(100);
assertFalse(cb.allowRequest());
assertTrue(cb.isOpen());
//this should occur after the sleep window, so get executed
//however, it is unsubscribed, so never updates state on the circuit-breaker
HystrixCommand<Boolean> cmd5 = new SuccessCommand(key, 5000, sleepWindow);
//wait for sleep window to pass
Thread.sleep(sleepWindow + 50);
Observable<Boolean> o = cmd5.observe();
Subscription s = o.subscribe();
s.unsubscribe();
//wait for 10 sleep windows, then try a successful command. this should return the circuit to CLOSED
Thread.sleep(10 * sleepWindow);
HystrixCommand<Boolean> cmd6 = new SuccessCommand(key, 1, sleepWindow);
cmd6.execute();
Thread.sleep(100);
assertTrue(cb.allowRequest());
assertFalse(cb.isOpen());
} catch (Exception e) {
e.printStackTrace();
fail("Error occurred: " + e.getMessage());
}
}
/**
* Utility method for creating {@link HystrixCommandMetrics} for unit tests.
*/
private static HystrixCommandMetrics getMetrics(HystrixCommandProperties.Setter properties) {
return HystrixCommandMetrics.getInstance(CommandKeyForUnitTest.KEY_ONE, CommandOwnerForUnitTest.OWNER_ONE, ThreadPoolKeyForUnitTest.THREAD_POOL_ONE, HystrixCommandPropertiesTest.asMock(properties));
}
/**
* Utility method for creating {@link HystrixCommandMetrics} for unit tests.
*/
private static HystrixCommandMetrics getMetrics(HystrixCommandKey commandKey, HystrixCommandProperties.Setter properties) {
return HystrixCommandMetrics.getInstance(commandKey, CommandOwnerForUnitTest.OWNER_ONE, ThreadPoolKeyForUnitTest.THREAD_POOL_ONE, HystrixCommandPropertiesTest.asMock(properties));
}
/**
* Utility method for creating {@link HystrixCircuitBreaker} for unit tests.
*/
private static HystrixCircuitBreaker getCircuitBreaker(HystrixCommandKey key, HystrixCommandGroupKey commandGroup, HystrixCommandMetrics metrics, HystrixCommandProperties.Setter properties) {
return new HystrixCircuitBreakerImpl(key, commandGroup, HystrixCommandPropertiesTest.asMock(properties), metrics);
}
private static enum CommandOwnerForUnitTest implements HystrixCommandGroupKey {
OWNER_ONE, OWNER_TWO
}
private static enum ThreadPoolKeyForUnitTest implements HystrixThreadPoolKey {
THREAD_POOL_ONE, THREAD_POOL_TWO
}
private static enum CommandKeyForUnitTest implements HystrixCommandKey {
KEY_ONE, KEY_TWO
}
// ignoring since this never ends ... useful for testing https://github.com/Netflix/Hystrix/issues/236
@Ignore
@Test
public void testSuccessClosesCircuitWhenBusy() throws InterruptedException {
HystrixPlugins.getInstance().registerCommandExecutionHook(new MyHystrixCommandExecutionHook());
try {
performLoad(200, 0, 40);
performLoad(250, 100, 40);
performLoad(600, 0, 40);
} finally {
Hystrix.reset();
}
}
void performLoad(int totalNumCalls, int errPerc, int waitMillis) {
Random rnd = new Random();
for (int i = 0; i < totalNumCalls; i++) {
//System.out.println(i);
try {
boolean err = rnd.nextFloat() * 100 < errPerc;
TestCommand cmd = new TestCommand(err);
cmd.execute();
} catch (Exception e) {
//System.err.println(e.getMessage());
}
try {
Thread.sleep(waitMillis);
} catch (InterruptedException e) {
}
}
}
public class TestCommand extends HystrixCommand<String> {
boolean error;
public TestCommand(final boolean error) {
super(HystrixCommandGroupKey.Factory.asKey("group"));
this.error = error;
}
@Override
protected String run() throws Exception {
if (error) {
throw new Exception("forced failure");
} else {
return "success";
}
}
@Override
protected String getFallback() {
if (isFailedExecution()) {
return getFailedExecutionException().getMessage();
} else {
return "other fail reason";
}
}
}
private class Command extends HystrixCommand<Boolean> {
private final boolean shouldFail;
private final boolean shouldFailWithBadRequest;
private final long latencyToAdd;
public Command(String commandKey, boolean shouldFail, boolean shouldFailWithBadRequest, long latencyToAdd, int sleepWindow, int requestVolumeThreshold) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("Command")).andCommandKey(HystrixCommandKey.Factory.asKey(commandKey)).
andCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().
withExecutionTimeoutInMilliseconds(500).
withCircuitBreakerRequestVolumeThreshold(requestVolumeThreshold).
withCircuitBreakerSleepWindowInMilliseconds(sleepWindow)));
this.shouldFail = shouldFail;
this.shouldFailWithBadRequest = shouldFailWithBadRequest;
this.latencyToAdd = latencyToAdd;
}
public Command(String commandKey, boolean shouldFail, long latencyToAdd) {
this(commandKey, shouldFail, false, latencyToAdd, 200, 1);
}
@Override
protected Boolean run() throws Exception {
Thread.sleep(latencyToAdd);
if (shouldFail) {
throw new RuntimeException("induced failure");
}
if (shouldFailWithBadRequest) {
throw new HystrixBadRequestException("bad request");
}
return true;
}
@Override
protected Boolean getFallback() {
return false;
}
}
private class SuccessCommand extends Command {
SuccessCommand(String commandKey, long latencyToAdd) {
super(commandKey, false, latencyToAdd);
}
SuccessCommand(String commandKey, long latencyToAdd, int sleepWindow) {
super(commandKey, false, false, latencyToAdd, sleepWindow, 1);
}
}
private class FailureCommand extends Command {
FailureCommand(String commandKey, long latencyToAdd) {
super(commandKey, true, latencyToAdd);
}
FailureCommand(String commandKey, long latencyToAdd, int sleepWindow) {
super(commandKey, true, false, latencyToAdd, sleepWindow, 1);
}
FailureCommand(String commandKey, long latencyToAdd, int sleepWindow, int requestVolumeThreshold) {
super(commandKey, true, false, latencyToAdd, sleepWindow, requestVolumeThreshold);
}
}
private class TimeoutCommand extends Command {
TimeoutCommand(String commandKey) {
super(commandKey, false, 2000);
}
TimeoutCommand(String commandKey, int sleepWindow) {
super(commandKey, false, false, 2000, sleepWindow, 1);
}
}
private class BadRequestCommand extends Command {
BadRequestCommand(String commandKey, long latencyToAdd) {
super(commandKey, false, true, latencyToAdd, 200, 1);
}
BadRequestCommand(String commandKey, long latencyToAdd, int sleepWindow) {
super(commandKey, false, true, latencyToAdd, sleepWindow, 1);
}
}
public class MyHystrixCommandExecutionHook extends HystrixCommandExecutionHook {
@Override
public <T> T onComplete(final HystrixInvokable<T> command, final T response) {
logHC(command, response);
return super.onComplete(command, response);
}
private int counter = 0;
private <T> void logHC(HystrixInvokable<T> command, T response) {
if(command instanceof HystrixInvokableInfo) {
HystrixInvokableInfo<T> commandInfo = (HystrixInvokableInfo<T>)command;
HystrixCommandMetrics metrics = commandInfo.getMetrics();
System.out.println("cb/error-count/%/total: "
+ commandInfo.isCircuitBreakerOpen() + " "
+ metrics.getHealthCounts().getErrorCount() + " "
+ metrics.getHealthCounts().getErrorPercentage() + " "
+ metrics.getHealthCounts().getTotalRequests() + " => " + response + " " + commandInfo.getExecutionEvents());
}
}
}
}
| 4,566 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/AbstractTestHystrixCommand.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix;
import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy;
public interface AbstractTestHystrixCommand<R> extends HystrixObservable<R>, InspectableBuilder {
enum ExecutionResult {
SUCCESS, FAILURE, ASYNC_FAILURE, HYSTRIX_FAILURE, NOT_WRAPPED_FAILURE, ASYNC_HYSTRIX_FAILURE, RECOVERABLE_ERROR, ASYNC_RECOVERABLE_ERROR, UNRECOVERABLE_ERROR, ASYNC_UNRECOVERABLE_ERROR, BAD_REQUEST, ASYNC_BAD_REQUEST, BAD_REQUEST_NOT_WRAPPED, MULTIPLE_EMITS_THEN_SUCCESS, MULTIPLE_EMITS_THEN_FAILURE, NO_EMITS_THEN_SUCCESS
}
enum FallbackResult {
UNIMPLEMENTED, SUCCESS, FAILURE, ASYNC_FAILURE, MULTIPLE_EMITS_THEN_SUCCESS, MULTIPLE_EMITS_THEN_FAILURE, NO_EMITS_THEN_SUCCESS
}
enum CacheEnabled {
YES, NO
}
HystrixPropertiesStrategy TEST_PROPERTIES_FACTORY = new TestPropertiesFactory();
class TestPropertiesFactory extends HystrixPropertiesStrategy {
@Override
public HystrixCommandProperties getCommandProperties(HystrixCommandKey commandKey, HystrixCommandProperties.Setter builder) {
if (builder == null) {
builder = HystrixCommandPropertiesTest.getUnitTestPropertiesSetter();
}
return HystrixCommandPropertiesTest.asMock(builder);
}
@Override
public HystrixThreadPoolProperties getThreadPoolProperties(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties.Setter builder) {
if (builder == null) {
builder = HystrixThreadPoolPropertiesTest.getUnitTestPropertiesBuilder();
}
return HystrixThreadPoolPropertiesTest.asMock(builder);
}
@Override
public HystrixCollapserProperties getCollapserProperties(HystrixCollapserKey collapserKey, HystrixCollapserProperties.Setter builder) {
throw new IllegalStateException("not expecting collapser properties");
}
@Override
public String getCommandPropertiesCacheKey(HystrixCommandKey commandKey, HystrixCommandProperties.Setter builder) {
return null;
}
@Override
public String getThreadPoolPropertiesCacheKey(HystrixThreadPoolKey threadPoolKey, com.netflix.hystrix.HystrixThreadPoolProperties.Setter builder) {
return null;
}
@Override
public String getCollapserPropertiesCacheKey(HystrixCollapserKey collapserKey, com.netflix.hystrix.HystrixCollapserProperties.Setter builder) {
return null;
}
}
}
| 4,567 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/HystrixObservableCommandTest.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix;
import com.hystrix.junit.HystrixRequestContextRule;
import com.netflix.config.ConfigurationManager;
import com.netflix.hystrix.AbstractCommand.TryableSemaphoreActual;
import com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker;
import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import com.netflix.hystrix.strategy.HystrixPlugins;
import com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable;
import com.netflix.hystrix.strategy.concurrency.HystrixContextScheduler;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import com.netflix.hystrix.strategy.properties.HystrixProperty;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import rx.*;
import rx.Observable.OnSubscribe;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.observers.TestSubscriber;
import rx.schedulers.Schedulers;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.*;
public class HystrixObservableCommandTest extends CommonHystrixCommandTests<TestHystrixObservableCommand<Integer>> {
@Rule
public HystrixRequestContextRule ctx = new HystrixRequestContextRule();
@After
public void cleanup() {
// force properties to be clean as well
ConfigurationManager.getConfigInstance().clear();
/*
* RxJava will create one worker for each processor when we schedule Observables in the
* Schedulers.computation(). Any leftovers here might lead to a congestion in a following
* thread. To ensure all existing threads have completed we now schedule some observables
* that will execute in distinct threads due to the latch..
*/
int count = Runtime.getRuntime().availableProcessors();
final CountDownLatch latch = new CountDownLatch(count);
ArrayList<Future<Boolean>> futures = new ArrayList<Future<Boolean>>();
for (int i = 0; i < count; ++i) {
futures.add(Observable.create(new OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> sub) {
latch.countDown();
try {
latch.await();
sub.onNext(true);
sub.onCompleted();
} catch (InterruptedException e) {
sub.onError(e);
}
}
}).subscribeOn(Schedulers.computation()).toBlocking().toFuture());
}
for (Future<Boolean> future : futures) {
try {
future.get();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
//TODO commented out as it has issues when built from command-line even though it works from IDE
// HystrixCommandKey key = Hystrix.getCurrentThreadExecutingCommand();
// if (key != null) {
// throw new IllegalStateException("should be null but got: " + key);
// }
}
class CompletableCommand extends HystrixObservableCommand<Integer> {
CompletableCommand() {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("COMPLETABLE")));
}
@Override
protected Observable<Integer> construct() {
return Completable.complete().toObservable();
}
}
@Test
public void testCompletable() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final HystrixObservableCommand<Integer> command = new CompletableCommand();
command.observe().subscribe(new Subscriber<Integer>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " OnCompleted");
latch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " OnError : " + e);
latch.countDown();
}
@Override
public void onNext(Integer integer) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " OnNext : " + integer);
}
});
latch.await();
assertEquals(null, command.getFailedExecutionException());
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isSuccessfulExecution());
assertFalse(command.isResponseFromFallback());
assertCommandExecutionEvents(command, HystrixEventType.SUCCESS);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
assertNull(command.getExecutionException());
}
/**
* Test a successful semaphore-isolated command execution.
*/
@Test
public void testSemaphoreObserveSuccess() {
testObserveSuccess(ExecutionIsolationStrategy.SEMAPHORE);
}
/**
* Test a successful thread-isolated command execution.
*/
@Test
public void testThreadObserveSuccess() {
testObserveSuccess(ExecutionIsolationStrategy.THREAD);
}
private void testObserveSuccess(ExecutionIsolationStrategy isolationStrategy) {
try {
TestHystrixObservableCommand<Boolean> command = new SuccessfulTestCommand(isolationStrategy);
assertEquals(true, command.observe().toBlocking().single());
assertEquals(null, command.getFailedExecutionException());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isSuccessfulExecution());
assertFalse(command.isResponseFromFallback());
assertCommandExecutionEvents(command, HystrixEventType.EMIT, HystrixEventType.SUCCESS);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
assertNull(command.getExecutionException());
assertEquals(isolationStrategy.equals(ExecutionIsolationStrategy.THREAD), command.isExecutedInThread());
} catch (Exception e) {
e.printStackTrace();
fail("We received an exception.");
}
}
/**
* Test that a semaphore command can not be executed multiple times.
*/
@Test
public void testSemaphoreIsolatedObserveMultipleTimes() {
testObserveMultipleTimes(ExecutionIsolationStrategy.SEMAPHORE);
}
/**
* Test that a thread command can not be executed multiple times.
*/
@Test
public void testThreadIsolatedObserveMultipleTimes() {
testObserveMultipleTimes(ExecutionIsolationStrategy.THREAD);
}
private void testObserveMultipleTimes(ExecutionIsolationStrategy isolationStrategy) {
SuccessfulTestCommand command = new SuccessfulTestCommand(isolationStrategy);
assertFalse(command.isExecutionComplete());
// first should succeed
assertEquals(true, command.observe().toBlocking().single());
assertTrue(command.isExecutionComplete());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isSuccessfulExecution());
assertFalse(command.isResponseFromFallback());
assertNull(command.getExecutionException());
try {
// second should fail
command.observe().toBlocking().single();
fail("we should not allow this ... it breaks the state of request logs");
} catch (HystrixRuntimeException e) {
e.printStackTrace();
// we want to get here
}
assertEquals(isolationStrategy.equals(ExecutionIsolationStrategy.THREAD), command.isExecutedInThread());
assertSaneHystrixRequestLog(1);
assertCommandExecutionEvents(command, HystrixEventType.EMIT, HystrixEventType.SUCCESS);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
}
/**
* Test a semaphore command execution that throws an HystrixException synchronously and didn't implement getFallback.
*/
@Test
public void testSemaphoreIsolatedObserveKnownSyncFailureWithNoFallback() {
testObserveKnownFailureWithNoFallback(ExecutionIsolationStrategy.SEMAPHORE, false);
}
/**
* Test a semaphore command execution that throws an HystrixException asynchronously and didn't implement getFallback.
*/
@Test
public void testSemaphoreIsolatedObserveKnownAsyncFailureWithNoFallback() {
testObserveKnownFailureWithNoFallback(ExecutionIsolationStrategy.SEMAPHORE, true);
}
/**
* Test a thread command execution that throws an HystrixException synchronously and didn't implement getFallback.
*/
@Test
public void testThreadIsolatedObserveKnownSyncFailureWithNoFallback() {
testObserveKnownFailureWithNoFallback(ExecutionIsolationStrategy.THREAD, false);
}
/**
* Test a thread command execution that throws an HystrixException asynchronously and didn't implement getFallback.
*/
@Test
public void testThreadIsolatedObserveKnownAsyncFailureWithNoFallback() {
testObserveKnownFailureWithNoFallback(ExecutionIsolationStrategy.THREAD, true);
}
private void testObserveKnownFailureWithNoFallback(ExecutionIsolationStrategy isolationStrategy, boolean asyncException) {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
TestHystrixObservableCommand<Boolean> command = new KnownFailureTestCommandWithoutFallback(circuitBreaker, isolationStrategy, asyncException);
try {
command.observe().toBlocking().single();
fail("we shouldn't get here");
} catch (HystrixRuntimeException e) {
e.printStackTrace();
assertNotNull(e.getFallbackException());
assertNotNull(e.getImplementingClass());
} catch (Exception e) {
e.printStackTrace();
fail("We should always get an HystrixRuntimeException when an error occurs.");
}
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isFailedExecution());
assertFalse(command.isResponseFromFallback());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_MISSING);
assertNotNull(command.getExecutionException());
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
assertEquals(isolationStrategy.equals(ExecutionIsolationStrategy.THREAD), command.isExecutedInThread());
}
/**
* Test a semaphore command execution that throws an unknown exception (not HystrixException) synchronously and didn't implement getFallback.
*/
@Test
public void testSemaphoreIsolatedObserveUnknownSyncFailureWithNoFallback() {
testObserveUnknownFailureWithNoFallback(ExecutionIsolationStrategy.SEMAPHORE, false);
}
/**
* Test a semaphore command execution that throws an unknown exception (not HystrixException) asynchronously and didn't implement getFallback.
*/
@Test
public void testSemaphoreIsolatedObserveUnknownAsyncFailureWithNoFallback() {
testObserveUnknownFailureWithNoFallback(ExecutionIsolationStrategy.SEMAPHORE, true);
}
/**
* Test a thread command execution that throws an unknown exception (not HystrixException) synchronously and didn't implement getFallback.
*/
@Test
public void testThreadIsolatedObserveUnknownSyncFailureWithNoFallback() {
testObserveUnknownFailureWithNoFallback(ExecutionIsolationStrategy.THREAD, false);
}
/**
* Test a thread command execution that throws an unknown exception (not HystrixException) asynchronously and didn't implement getFallback.
*/
@Test
public void testThreadIsolatedObserveUnknownAsyncFailureWithNoFallback() {
testObserveUnknownFailureWithNoFallback(ExecutionIsolationStrategy.THREAD, true);
}
private void testObserveUnknownFailureWithNoFallback(ExecutionIsolationStrategy isolationStrategy, boolean asyncException) {
TestHystrixObservableCommand<Boolean> command = new UnknownFailureTestCommandWithoutFallback(isolationStrategy, asyncException);
try {
command.observe().toBlocking().single();
fail("we shouldn't get here");
} catch (HystrixRuntimeException e) {
e.printStackTrace();
assertNotNull(e.getFallbackException());
assertNotNull(e.getImplementingClass());
} catch (Exception e) {
e.printStackTrace();
fail("We should always get an HystrixRuntimeException when an error occurs.");
}
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isFailedExecution());
assertFalse(command.isResponseFromFallback());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_MISSING);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
assertNotNull(command.getExecutionException());
assertEquals(isolationStrategy.equals(ExecutionIsolationStrategy.THREAD), command.isExecutedInThread());
}
/**
* Test a semaphore command execution that fails synchronously but has a fallback.
*/
@Test
public void testSemaphoreIsolatedObserveSyncFailureWithFallback() {
testObserveFailureWithFallback(ExecutionIsolationStrategy.SEMAPHORE, false);
}
/**
* Test a semaphore command execution that fails asynchronously but has a fallback.
*/
@Test
public void testSemaphoreIsolatedObserveAsyncFailureWithFallback() {
testObserveFailureWithFallback(ExecutionIsolationStrategy.SEMAPHORE, true);
}
/**
* Test a thread command execution that fails synchronously but has a fallback.
*/
@Test
public void testThreadIsolatedObserveSyncFailureWithFallback() {
testObserveFailureWithFallback(ExecutionIsolationStrategy.THREAD, false);
}
/**
* Test a thread command execution that fails asynchronously but has a fallback.
*/
@Test
public void testThreadIsolatedObserveAsyncFailureWithFallback() {
testObserveFailureWithFallback(ExecutionIsolationStrategy.THREAD, true);
}
private void testObserveFailureWithFallback(ExecutionIsolationStrategy isolationStrategy, boolean asyncException) {
TestHystrixObservableCommand<Boolean> command = new KnownFailureTestCommandWithFallback(new TestCircuitBreaker(), isolationStrategy, asyncException);
try {
assertEquals(false, command.observe().toBlocking().single());
} catch (Exception e) {
e.printStackTrace();
fail("We should have received a response from the fallback.");
}
assertEquals("we failed with a simulated issue", command.getFailedExecutionException().getMessage());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isFailedExecution());
assertTrue(command.isResponseFromFallback());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
assertNotNull(command.getExecutionException());
assertEquals(isolationStrategy.equals(ExecutionIsolationStrategy.THREAD), command.isExecutedInThread());
}
/**
* Test a command execution that fails synchronously, has getFallback implemented but that fails as well (synchronously).
*/
@Test
public void testSemaphoreIsolatedObserveSyncFailureWithSyncFallbackFailure() {
testObserveFailureWithFallbackFailure(ExecutionIsolationStrategy.SEMAPHORE, false, false);
}
/**
* Test a command execution that fails synchronously, has getFallback implemented but that fails as well (asynchronously).
*/
@Test
public void testSemaphoreIsolatedObserveSyncFailureWithAsyncFallbackFailure() {
testObserveFailureWithFallbackFailure(ExecutionIsolationStrategy.SEMAPHORE, false, true);
}
/**
* Test a command execution that fails asynchronously, has getFallback implemented but that fails as well (synchronously).
*/
@Test
public void testSemaphoreIsolatedObserveAyncFailureWithSyncFallbackFailure() {
testObserveFailureWithFallbackFailure(ExecutionIsolationStrategy.SEMAPHORE, true, false);
}
/**
* Test a command execution that fails asynchronously, has getFallback implemented but that fails as well (asynchronously).
*/
@Test
public void testSemaphoreIsolatedObserveAsyncFailureWithAsyncFallbackFailure() {
testObserveFailureWithFallbackFailure(ExecutionIsolationStrategy.SEMAPHORE, true, true);
}
/**
* Test a command execution that fails synchronously, has getFallback implemented but that fails as well (synchronously).
*/
@Test
public void testThreadIsolatedObserveSyncFailureWithSyncFallbackFailure() {
testObserveFailureWithFallbackFailure(ExecutionIsolationStrategy.THREAD, false, false);
}
/**
* Test a command execution that fails synchronously, has getFallback implemented but that fails as well (asynchronously).
*/
@Test
public void testThreadIsolatedObserveSyncFailureWithAsyncFallbackFailure() {
testObserveFailureWithFallbackFailure(ExecutionIsolationStrategy.THREAD, true, false);
}
/**
* Test a command execution that fails asynchronously, has getFallback implemented but that fails as well (synchronously).
*/
@Test
public void testThreadIsolatedObserveAyncFailureWithSyncFallbackFailure() {
testObserveFailureWithFallbackFailure(ExecutionIsolationStrategy.THREAD, false, true);
}
/**
* Test a command execution that fails asynchronously, has getFallback implemented but that fails as well (asynchronously).
*/
@Test
public void testThreadIsolatedObserveAsyncFailureWithAsyncFallbackFailure() {
testObserveFailureWithFallbackFailure(ExecutionIsolationStrategy.THREAD, true, true);
}
private void testObserveFailureWithFallbackFailure(ExecutionIsolationStrategy isolationStrategy, boolean asyncFallbackException, boolean asyncConstructException) {
TestHystrixObservableCommand<Boolean> command = new KnownFailureTestCommandWithFallbackFailure(new TestCircuitBreaker(), isolationStrategy, asyncConstructException, asyncFallbackException);
try {
command.observe().toBlocking().single();
fail("we shouldn't get here");
} catch (HystrixRuntimeException e) {
System.out.println("------------------------------------------------");
e.printStackTrace();
System.out.println("------------------------------------------------");
assertNotNull(e.getFallbackException());
}
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isFailedExecution());
assertFalse(command.isResponseFromFallback());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_FAILURE);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
assertNotNull(command.getExecutionException());
assertEquals(isolationStrategy.equals(ExecutionIsolationStrategy.THREAD), command.isExecutedInThread());
}
/**
* Test a semaphore command execution that times out with a fallback and eventually succeeds.
*/
@Test
public void testSemaphoreIsolatedObserveTimeoutWithSuccessAndFallback() {
testObserveFailureWithTimeoutAndFallback(ExecutionIsolationStrategy.SEMAPHORE, TestHystrixObservableCommand.ExecutionResult.MULTIPLE_EMITS_THEN_SUCCESS);
}
/**
* Test a semaphore command execution that times out with a fallback and eventually fails.
*/
@Test
public void testSemaphoreIsolatedObserveTimeoutWithFailureAndFallback() {
testObserveFailureWithTimeoutAndFallback(ExecutionIsolationStrategy.SEMAPHORE, TestHystrixObservableCommand.ExecutionResult.MULTIPLE_EMITS_THEN_FAILURE);
}
/**
* Test a thread command execution that times out with a fallback and eventually succeeds.
*/
@Test
public void testThreadIsolatedObserveTimeoutWithSuccessAndFallback() {
testObserveFailureWithTimeoutAndFallback(ExecutionIsolationStrategy.THREAD, TestHystrixObservableCommand.ExecutionResult.MULTIPLE_EMITS_THEN_SUCCESS);
}
/**
* Test a thread command execution that times out with a fallback and eventually fails.
*/
@Test
public void testThreadIsolatedObserveTimeoutWithFailureAndFallback() {
testObserveFailureWithTimeoutAndFallback(ExecutionIsolationStrategy.THREAD, TestHystrixObservableCommand.ExecutionResult.MULTIPLE_EMITS_THEN_FAILURE);
}
private void testObserveFailureWithTimeoutAndFallback(ExecutionIsolationStrategy isolationStrategy, TestHystrixObservableCommand.ExecutionResult executionResult) {
TestHystrixObservableCommand<Integer> command = getCommand(isolationStrategy, executionResult, 200, AbstractTestHystrixCommand.FallbackResult.SUCCESS, 100);
long observedCommandDuration = 0;
try {
long startTime = System.currentTimeMillis();
assertEquals(FlexibleTestHystrixObservableCommand.FALLBACK_VALUE, command.observe().toBlocking().single());
observedCommandDuration = System.currentTimeMillis() - startTime;
} catch (Exception e) {
e.printStackTrace();
fail("We should have received a response from the fallback.");
}
assertNull(command.getFailedExecutionException());
assertNotNull(command.getExecutionException());
System.out.println("Command time : " + command.getExecutionTimeInMilliseconds());
System.out.println("Observed command time : " + observedCommandDuration);
assertTrue(command.getExecutionTimeInMilliseconds() >= 100);
assertTrue(observedCommandDuration >= 100);
assertTrue(command.getExecutionTimeInMilliseconds() < 1000);
assertTrue(observedCommandDuration < 1000);
assertFalse(command.isFailedExecution());
assertTrue(command.isResponseFromFallback());
assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
assertEquals(isolationStrategy.equals(ExecutionIsolationStrategy.THREAD), command.isExecutedInThread());
}
/**
* Test a successful command execution.
*/
@Test
public void testObserveOnImmediateSchedulerByDefaultForSemaphoreIsolation() throws Exception {
final AtomicReference<Thread> commandThread = new AtomicReference<Thread>();
final AtomicReference<Thread> subscribeThread = new AtomicReference<Thread>();
TestHystrixObservableCommand<Boolean> command = new TestHystrixObservableCommand<Boolean>(TestHystrixObservableCommand.testPropsBuilder()
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE))) {
@Override
protected Observable<Boolean> construct() {
commandThread.set(Thread.currentThread());
return Observable.just(true);
}
};
final CountDownLatch latch = new CountDownLatch(1);
command.toObservable().subscribe(new Observer<Boolean>() {
@Override
public void onCompleted() {
latch.countDown();
}
@Override
public void onError(Throwable e) {
latch.countDown();
e.printStackTrace();
}
@Override
public void onNext(Boolean args) {
subscribeThread.set(Thread.currentThread());
}
});
if (!latch.await(2000, TimeUnit.MILLISECONDS)) {
fail("timed out");
}
assertNotNull(commandThread.get());
assertNotNull(subscribeThread.get());
System.out.println("Command Thread: " + commandThread.get());
System.out.println("Subscribe Thread: " + subscribeThread.get());
String mainThreadName = Thread.currentThread().getName();
// semaphore should be on the calling thread
assertTrue(commandThread.get().getName().equals(mainThreadName));
System.out.println("testObserveOnImmediateSchedulerByDefaultForSemaphoreIsolation: " + subscribeThread.get() + " => " + mainThreadName);
assertTrue(subscribeThread.get().getName().equals(mainThreadName));
// semaphore isolated
assertFalse(command.isExecutedInThread());
assertCommandExecutionEvents(command, HystrixEventType.EMIT, HystrixEventType.SUCCESS);
assertSaneHystrixRequestLog(1);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertNull(command.getExecutionException());
assertFalse(command.isResponseFromFallback());
}
/**
* Test that the circuit-breaker will 'trip' and prevent command execution on subsequent calls.
*/
@Test
public void testCircuitBreakerTripsAfterFailures() throws InterruptedException {
HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey("KnownFailureTestCommandWithFallback");
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(commandKey);
/* fail 3 times and then it should trip the circuit and stop executing */
// failure 1
KnownFailureTestCommandWithFallback attempt1 = new KnownFailureTestCommandWithFallback(circuitBreaker, ExecutionIsolationStrategy.SEMAPHORE, true);
attempt1.observe().toBlocking().single();
Thread.sleep(100);
assertTrue(attempt1.isResponseFromFallback());
assertFalse(attempt1.isCircuitBreakerOpen());
assertFalse(attempt1.isResponseShortCircuited());
// failure 2
KnownFailureTestCommandWithFallback attempt2 = new KnownFailureTestCommandWithFallback(circuitBreaker, ExecutionIsolationStrategy.SEMAPHORE, true);
attempt2.observe().toBlocking().single();
Thread.sleep(100);
assertTrue(attempt2.isResponseFromFallback());
assertFalse(attempt2.isCircuitBreakerOpen());
assertFalse(attempt2.isResponseShortCircuited());
// failure 3
KnownFailureTestCommandWithFallback attempt3 = new KnownFailureTestCommandWithFallback(circuitBreaker, ExecutionIsolationStrategy.SEMAPHORE, true);
attempt3.observe().toBlocking().single();
Thread.sleep(100);
assertTrue(attempt3.isResponseFromFallback());
assertFalse(attempt3.isResponseShortCircuited());
// it should now be 'open' and prevent further executions
assertTrue(attempt3.isCircuitBreakerOpen());
// attempt 4
KnownFailureTestCommandWithFallback attempt4 = new KnownFailureTestCommandWithFallback(circuitBreaker, ExecutionIsolationStrategy.SEMAPHORE, true);
attempt4.observe().toBlocking().single();
Thread.sleep(100);
assertTrue(attempt4.isResponseFromFallback());
// this should now be true as the response will be short-circuited
assertTrue(attempt4.isResponseShortCircuited());
// this should remain open
assertTrue(attempt4.isCircuitBreakerOpen());
assertCommandExecutionEvents(attempt1, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
assertCommandExecutionEvents(attempt2, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
assertCommandExecutionEvents(attempt3, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
assertCommandExecutionEvents(attempt4, HystrixEventType.SHORT_CIRCUITED, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertEquals(4, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
}
/**
* Test that the circuit-breaker being disabled doesn't wreak havoc.
*/
@Test
public void testExecutionSuccessWithCircuitBreakerDisabled() {
TestHystrixObservableCommand<Boolean> command = new TestCommandWithoutCircuitBreaker();
try {
assertEquals(true, command.observe().toBlocking().single());
} catch (Exception e) {
e.printStackTrace();
fail("We received an exception.");
}
assertCommandExecutionEvents(command, HystrixEventType.EMIT, HystrixEventType.SUCCESS);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
assertNull(command.getExecutionException());
}
/**
* Test a command execution timeout where the command didn't implement getFallback.
*/
@Test
public void testExecutionTimeoutWithNoFallbackUsingSemaphoreIsolation() {
TestHystrixObservableCommand<Integer> command = getCommand(ExecutionIsolationStrategy.SEMAPHORE, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 200, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED, 100);
try {
command.observe().toBlocking().single();
fail("we shouldn't get here");
} catch (Exception e) {
e.printStackTrace();
if (e instanceof HystrixRuntimeException) {
HystrixRuntimeException de = (HystrixRuntimeException) e;
assertNotNull(de.getFallbackException());
assertTrue(de.getFallbackException() instanceof UnsupportedOperationException);
assertNotNull(de.getImplementingClass());
assertNotNull(de.getCause());
assertTrue(de.getCause() instanceof TimeoutException);
} else {
fail("the exception should be HystrixRuntimeException");
}
}
// the time should be 50+ since we timeout at 50ms
assertTrue("Execution Time is: " + command.getExecutionTimeInMilliseconds(), command.getExecutionTimeInMilliseconds() >= 50);
assertTrue(command.isResponseTimedOut());
assertFalse(command.isResponseFromFallback());
assertFalse(command.isResponseRejected());
assertNotNull(command.getExecutionException());
assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
// semaphore isolated
assertFalse(command.isExecutedInThread());
}
/**
* Test a command execution timeout where the command implemented getFallback.
*/
@Test
public void testExecutionTimeoutWithFallbackUsingSemaphoreIsolation() {
TestHystrixObservableCommand<Integer> command = getCommand(ExecutionIsolationStrategy.SEMAPHORE, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 200, AbstractTestHystrixCommand.FallbackResult.SUCCESS, 50);
try {
assertEquals(FlexibleTestHystrixObservableCommand.FALLBACK_VALUE, command.observe().toBlocking().single());
// the time should be 50+ since we timeout at 50ms
assertTrue("Execution Time is: " + command.getExecutionTimeInMilliseconds(), command.getExecutionTimeInMilliseconds() >= 50);
assertTrue(command.isResponseTimedOut());
assertTrue(command.isResponseFromFallback());
assertNotNull(command.getExecutionException());
} catch (Exception e) {
e.printStackTrace();
fail("We should have received a response from the fallback.");
}
assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
// semaphore isolated
assertFalse(command.isExecutedInThread());
}
/**
* Test a command execution timeout where the command implemented getFallback but it fails.
*/
@Test
public void testExecutionTimeoutFallbackFailureUsingSemaphoreIsolation() {
TestHystrixObservableCommand<Integer> command = getCommand(ExecutionIsolationStrategy.SEMAPHORE, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 500, AbstractTestHystrixCommand.FallbackResult.FAILURE, 200);
try {
command.observe().toBlocking().single();
fail("we shouldn't get here");
} catch (Exception e) {
if (e instanceof HystrixRuntimeException) {
e.printStackTrace();
HystrixRuntimeException de = (HystrixRuntimeException) e;
assertNotNull(de.getFallbackException());
assertFalse(de.getFallbackException() instanceof UnsupportedOperationException);
assertNotNull(de.getImplementingClass());
assertNotNull(de.getCause());
assertTrue(de.getCause() instanceof TimeoutException);
assertNotNull(command.getExecutionException());
} else {
fail("the exception should be HystrixRuntimeException");
}
}
// the time should be 200+ since we timeout at 200ms
assertTrue("Execution Time is: " + command.getExecutionTimeInMilliseconds(), command.getExecutionTimeInMilliseconds() >= 200);
assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_FAILURE);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
// semaphore isolated
assertFalse(command.isExecutedInThread());
}
/**
* Test a semaphore command execution timeout where the command didn't implement getFallback.
*/
@Test
public void testSemaphoreExecutionTimeoutWithNoFallback() {
testExecutionTimeoutWithNoFallback(ExecutionIsolationStrategy.SEMAPHORE);
}
/**
* Test a thread command execution timeout where the command didn't implement getFallback.
*/
@Test
public void testThreadExecutionTimeoutWithNoFallback() {
testExecutionTimeoutWithNoFallback(ExecutionIsolationStrategy.THREAD);
}
private void testExecutionTimeoutWithNoFallback(ExecutionIsolationStrategy isolationStrategy) {
TestHystrixObservableCommand<Integer> command = getCommand(isolationStrategy, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 200, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED, 50);
try {
command.observe().toBlocking().single();
fail("we shouldn't get here");
} catch (Exception e) {
e.printStackTrace();
if (e instanceof HystrixRuntimeException) {
HystrixRuntimeException de = (HystrixRuntimeException) e;
assertNotNull(de.getFallbackException());
assertTrue(de.getFallbackException() instanceof UnsupportedOperationException);
assertNotNull(de.getImplementingClass());
assertNotNull(de.getCause());
assertTrue(de.getCause() instanceof TimeoutException);
} else {
fail("the exception should be HystrixRuntimeException");
}
}
// the time should be 50+ since we timeout at 50ms
assertTrue("Execution Time is: " + command.getExecutionTimeInMilliseconds(), command.getExecutionTimeInMilliseconds() >= 50);
assertTrue(command.isResponseTimedOut());
assertFalse(command.isResponseFromFallback());
assertFalse(command.isResponseRejected());
assertNotNull(command.getExecutionException());
assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
assertEquals(isolationStrategy.equals(ExecutionIsolationStrategy.THREAD), command.isExecutedInThread());
}
/**
* Test a semaphore command execution timeout where the command implemented getFallback.
*/
@Test
public void testSemaphoreIsolatedExecutionTimeoutWithSuccessfulFallback() {
testExecutionTimeoutWithSuccessfulFallback(ExecutionIsolationStrategy.SEMAPHORE);
}
/**
* Test a thread command execution timeout where the command implemented getFallback.
*/
@Test
public void testThreadIsolatedExecutionTimeoutWithSuccessfulFallback() {
testExecutionTimeoutWithSuccessfulFallback(ExecutionIsolationStrategy.THREAD);
}
private void testExecutionTimeoutWithSuccessfulFallback(ExecutionIsolationStrategy isolationStrategy) {
TestHystrixObservableCommand<Integer> command = getCommand(isolationStrategy, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 200, AbstractTestHystrixCommand.FallbackResult.SUCCESS, 100);
try {
assertEquals(FlexibleTestHystrixObservableCommand.FALLBACK_VALUE, command.observe().toBlocking().single());
// the time should be 50+ since we timeout at 50ms
assertTrue("Execution Time is: " + command.getExecutionTimeInMilliseconds(), command.getExecutionTimeInMilliseconds() >= 50);
assertTrue(command.isResponseTimedOut());
assertTrue(command.isResponseFromFallback());
assertNotNull(command.getExecutionException());
} catch (Exception e) {
e.printStackTrace();
fail("We should have received a response from the fallback.");
}
assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
assertEquals(isolationStrategy.equals(ExecutionIsolationStrategy.THREAD), command.isExecutedInThread());
}
/**
* Test a semaphore command execution timeout where the command implemented getFallback but it fails synchronously.
*/
@Test
public void testSemaphoreExecutionTimeoutSyncFallbackFailure() {
testExecutionTimeoutFallbackFailure(ExecutionIsolationStrategy.SEMAPHORE, false);
}
/**
* Test a semaphore command execution timeout where the command implemented getFallback but it fails asynchronously.
*/
@Test
public void testSemaphoreExecutionTimeoutAsyncFallbackFailure() {
testExecutionTimeoutFallbackFailure(ExecutionIsolationStrategy.SEMAPHORE, true);
}
/**
* Test a thread command execution timeout where the command implemented getFallback but it fails synchronously.
*/
@Test
public void testThreadExecutionTimeoutSyncFallbackFailure() {
testExecutionTimeoutFallbackFailure(ExecutionIsolationStrategy.THREAD, false);
}
/**
* Test a thread command execution timeout where the command implemented getFallback but it fails asynchronously.
*/
@Test
public void testThreadExecutionTimeoutAsyncFallbackFailure() {
testExecutionTimeoutFallbackFailure(ExecutionIsolationStrategy.THREAD, true);
}
private void testExecutionTimeoutFallbackFailure(ExecutionIsolationStrategy isolationStrategy, boolean asyncFallbackException) {
TestHystrixObservableCommand<Integer> command = getCommand(isolationStrategy, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 200, AbstractTestHystrixCommand.FallbackResult.FAILURE, 100);
try {
command.observe().toBlocking().single();
fail("we shouldn't get here");
} catch (Exception e) {
if (e instanceof HystrixRuntimeException) {
HystrixRuntimeException de = (HystrixRuntimeException) e;
assertNotNull(de.getFallbackException());
assertFalse(de.getFallbackException() instanceof UnsupportedOperationException);
assertNotNull(de.getImplementingClass());
assertNotNull(de.getCause());
assertTrue(de.getCause() instanceof TimeoutException);
assertNotNull(command.getExecutionException());
} else {
fail("the exception should be HystrixRuntimeException");
}
}
// the time should be 50+ since we timeout at 50ms
assertTrue("Execution Time is: " + command.getExecutionTimeInMilliseconds(), command.getExecutionTimeInMilliseconds() >= 50);
assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_FAILURE);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
assertEquals(isolationStrategy.equals(ExecutionIsolationStrategy.THREAD), command.isExecutedInThread());
}
/**
* Test that the circuit-breaker counts a command execution timeout as a 'timeout' and not just failure.
*/
@Test
public void testShortCircuitFallbackCounter() {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker().setForceShortCircuit(true);
KnownFailureTestCommandWithFallback command1 = new KnownFailureTestCommandWithFallback(circuitBreaker, ExecutionIsolationStrategy.SEMAPHORE, true);
KnownFailureTestCommandWithFallback command2 = new KnownFailureTestCommandWithFallback(circuitBreaker, ExecutionIsolationStrategy.SEMAPHORE, true);
try {
command1.observe().toBlocking().single();
command2.observe().toBlocking().single();
// will be -1 because it never attempted execution
assertEquals(-1, command2.getExecutionTimeInMilliseconds());
assertTrue(command2.isResponseShortCircuited());
assertFalse(command2.isResponseTimedOut());
assertNotNull(command2.getExecutionException());
// semaphore isolated
assertFalse(command2.isExecutedInThread());
} catch (Exception e) {
e.printStackTrace();
fail("We should have received a response from the fallback.");
}
assertCommandExecutionEvents(command1, HystrixEventType.SHORT_CIRCUITED, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.SHORT_CIRCUITED, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
assertSaneHystrixRequestLog(2);
}
@Test
public void testExecutionSemaphoreWithObserve() {
final TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
TestSemaphoreCommand command1 = new TestSemaphoreCommand(circuitBreaker, 1, 200, TestSemaphoreCommand.RESULT_SUCCESS, TestSemaphoreCommand.FALLBACK_NOT_IMPLEMENTED);
// single thread should work
try {
boolean result = command1.observe().toBlocking().toFuture().get();
assertTrue(result);
} catch (Exception e) {
// we shouldn't fail on this one
throw new RuntimeException(e);
}
final AtomicBoolean exceptionReceived = new AtomicBoolean();
final TryableSemaphoreActual semaphore =
new TryableSemaphoreActual(HystrixProperty.Factory.asProperty(1));
final TestSemaphoreCommand command2 = new TestSemaphoreCommand(circuitBreaker, semaphore, 200, TestSemaphoreCommand.RESULT_SUCCESS, TestSemaphoreCommand.FALLBACK_NOT_IMPLEMENTED);
Runnable r2 = new HystrixContextRunnable(HystrixPlugins.getInstance().getConcurrencyStrategy(), new Runnable() {
@Override
public void run() {
try {
command2.observe().toBlocking().toFuture().get();
} catch (Exception e) {
e.printStackTrace();
exceptionReceived.set(true);
}
}
});
final TestSemaphoreCommand command3 = new TestSemaphoreCommand(circuitBreaker, semaphore, 200, TestSemaphoreCommand.RESULT_SUCCESS, TestSemaphoreCommand.FALLBACK_NOT_IMPLEMENTED);
Runnable r3 = new HystrixContextRunnable(HystrixPlugins.getInstance().getConcurrencyStrategy(), new Runnable() {
@Override
public void run() {
try {
command3.observe().toBlocking().toFuture().get();
} catch (Exception e) {
e.printStackTrace();
exceptionReceived.set(true);
}
}
});
// 2 threads, the second should be rejected by the semaphore
Thread t2 = new Thread(r2);
Thread t3 = new Thread(r3);
t2.start();
try {
Thread.sleep(100);
} catch (Throwable ex) {
fail(ex.getMessage());
}
t3.start();
try {
t2.join();
t3.join();
} catch (Exception e) {
e.printStackTrace();
fail("failed waiting on threads");
}
if (!exceptionReceived.get()) {
fail("We expected an exception on the 2nd get");
}
System.out.println("CMD1 : " + command1.getExecutionEvents());
System.out.println("CMD2 : " + command2.getExecutionEvents());
System.out.println("CMD3 : " + command3.getExecutionEvents());
assertCommandExecutionEvents(command1, HystrixEventType.EMIT, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.EMIT, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command3, HystrixEventType.SEMAPHORE_REJECTED, HystrixEventType.FALLBACK_MISSING);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(3);
}
@Test
public void testRejectedExecutionSemaphoreWithFallback() {
final TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
final ArrayBlockingQueue<Boolean> results = new ArrayBlockingQueue<Boolean>(2);
final AtomicBoolean exceptionReceived = new AtomicBoolean();
final TestSemaphoreCommandWithFallback command1 = new TestSemaphoreCommandWithFallback(circuitBreaker, 1, 200, false);
Runnable r1 = new HystrixContextRunnable(HystrixPlugins.getInstance().getConcurrencyStrategy(), new Runnable() {
@Override
public void run() {
try {
results.add(command1.observe().toBlocking().single());
} catch (Exception e) {
e.printStackTrace();
exceptionReceived.set(true);
}
}
});
final TestSemaphoreCommandWithFallback command2 = new TestSemaphoreCommandWithFallback(circuitBreaker, 1, 200, false);
Runnable r2 = new HystrixContextRunnable(HystrixPlugins.getInstance().getConcurrencyStrategy(), new Runnable() {
@Override
public void run() {
try {
results.add(command2.observe().toBlocking().single());
} catch (Exception e) {
e.printStackTrace();
exceptionReceived.set(true);
}
}
});
// 2 threads, the second should be rejected by the semaphore and return fallback
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
try {
//give t1 a headstart
Thread.sleep(50);
} catch (InterruptedException ex) {
fail(ex.getMessage());
}
t2.start();
try {
t1.join();
t2.join();
} catch (Exception e) {
e.printStackTrace();
fail("failed waiting on threads");
}
if (exceptionReceived.get()) {
fail("We should have received a fallback response");
}
// both threads should have returned values
assertEquals(2, results.size());
// should contain both a true and false result
assertTrue(results.contains(Boolean.TRUE));
assertTrue(results.contains(Boolean.FALSE));
assertCommandExecutionEvents(command1, HystrixEventType.EMIT, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.SEMAPHORE_REJECTED, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
assertEquals(0, command1.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(2);
}
@Test
public void testSemaphorePermitsInUse() {
// this semaphore will be shared across multiple command instances
final TryableSemaphoreActual sharedSemaphore =
new TryableSemaphoreActual(HystrixProperty.Factory.asProperty(3));
// creates thread using isolated semaphore
final TryableSemaphoreActual isolatedSemaphore =
new TryableSemaphoreActual(HystrixProperty.Factory.asProperty(1));
final TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
//used to wait until all commands are started
final CountDownLatch startLatch = new CountDownLatch((sharedSemaphore.numberOfPermits.get()) * 2 + 1);
// used to signal that all command can finish
final CountDownLatch sharedLatch = new CountDownLatch(1);
final CountDownLatch isolatedLatch = new CountDownLatch(1);
final List<HystrixObservableCommand<Boolean>> commands = new ArrayList<HystrixObservableCommand<Boolean>>();
final List<Observable<Boolean>> results = new ArrayList<Observable<Boolean>>();
HystrixObservableCommand<Boolean> isolated = new LatchedSemaphoreCommand("ObservableCommand-Isolated", circuitBreaker, isolatedSemaphore, startLatch, isolatedLatch);
commands.add(isolated);
for (int s = 0; s < sharedSemaphore.numberOfPermits.get() * 2; s++) {
HystrixObservableCommand<Boolean> shared = new LatchedSemaphoreCommand("ObservableCommand-Shared", circuitBreaker, sharedSemaphore, startLatch, sharedLatch);
commands.add(shared);
Observable<Boolean> result = shared.toObservable();
results.add(result);
}
Observable<Boolean> isolatedResult = isolated.toObservable();
results.add(isolatedResult);
// verifies no permits in use before starting commands
assertEquals("before commands start, shared semaphore should be unused", 0, sharedSemaphore.getNumberOfPermitsUsed());
assertEquals("before commands start, isolated semaphore should be unused", 0, isolatedSemaphore.getNumberOfPermitsUsed());
final CountDownLatch allTerminal = new CountDownLatch(1);
Observable.merge(results)
.subscribeOn(Schedulers.newThread())
.subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
System.out.println(Thread.currentThread().getName() + " OnCompleted");
allTerminal.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(Thread.currentThread().getName() + " OnError : " + e);
allTerminal.countDown();
}
@Override
public void onNext(Boolean b) {
System.out.println(Thread.currentThread().getName() + " OnNext : " + b);
}
});
try {
assertTrue(startLatch.await(20, TimeUnit.SECONDS));
} catch (Throwable ex) {
fail(ex.getMessage());
}
// verifies that all semaphores are in use
assertEquals("immediately after command start, all shared semaphores should be in-use",
sharedSemaphore.numberOfPermits.get().longValue(), sharedSemaphore.getNumberOfPermitsUsed());
assertEquals("immediately after command start, isolated semaphore should be in-use",
isolatedSemaphore.numberOfPermits.get().longValue(), isolatedSemaphore.getNumberOfPermitsUsed());
// signals commands to finish
sharedLatch.countDown();
isolatedLatch.countDown();
try {
assertTrue(allTerminal.await(5000, TimeUnit.MILLISECONDS));
} catch (Exception e) {
e.printStackTrace();
fail("failed waiting on commands");
}
// verifies no permits in use after finishing threads
assertEquals("after all threads have finished, no shared semaphores should be in-use", 0, sharedSemaphore.getNumberOfPermitsUsed());
assertEquals("after all threads have finished, isolated semaphore not in-use", 0, isolatedSemaphore.getNumberOfPermitsUsed());
// verifies that some executions failed
int numSemaphoreRejected = 0;
for (HystrixObservableCommand<Boolean> cmd: commands) {
if (cmd.isResponseSemaphoreRejected()) {
numSemaphoreRejected++;
}
}
assertEquals("expected some of shared semaphore commands to get rejected", sharedSemaphore.numberOfPermits.get().longValue(), numSemaphoreRejected);
}
/**
* Test that HystrixOwner can be passed in dynamically.
*/
@Test
public void testDynamicOwner() {
try {
TestHystrixObservableCommand<Boolean> command = new DynamicOwnerTestCommand(InspectableBuilder.CommandGroupForUnitTest.OWNER_ONE);
assertEquals(true, command.observe().toBlocking().single());
assertCommandExecutionEvents(command, HystrixEventType.EMIT, HystrixEventType.SUCCESS);
// semaphore isolated
assertFalse(command.isExecutedInThread());
} catch (Exception e) {
e.printStackTrace();
fail("We received an exception.");
}
}
/**
* Test a successful command execution.
*/
@Test
public void testDynamicOwnerFails() {
try {
TestHystrixObservableCommand<Boolean> command = new DynamicOwnerTestCommand(null);
assertEquals(true, command.observe().toBlocking().single());
fail("we should have thrown an exception as we need an owner");
// semaphore isolated
assertFalse(command.isExecutedInThread());
assertEquals(0, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
} catch (Exception e) {
// success if we get here
}
}
/**
* Test that HystrixCommandKey can be passed in dynamically.
*/
@Test
public void testDynamicKey() {
try {
DynamicOwnerAndKeyTestCommand command1 = new DynamicOwnerAndKeyTestCommand(InspectableBuilder.CommandGroupForUnitTest.OWNER_ONE, InspectableBuilder.CommandKeyForUnitTest.KEY_ONE);
assertEquals(true, command1.observe().toBlocking().single());
DynamicOwnerAndKeyTestCommand command2 = new DynamicOwnerAndKeyTestCommand(InspectableBuilder.CommandGroupForUnitTest.OWNER_ONE, InspectableBuilder.CommandKeyForUnitTest.KEY_TWO);
assertEquals(true, command2.observe().toBlocking().single());
// 2 different circuit breakers should be created
assertNotSame(command1.getCircuitBreaker(), command2.getCircuitBreaker());
// semaphore isolated
assertFalse(command1.isExecutedInThread());
assertEquals(2, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
} catch (Exception e) {
e.printStackTrace();
fail("We received an exception.");
}
}
/**
* Test Request scoped caching of commands so that a 2nd duplicate call doesn't execute but returns the previous Future
*/
@Test
public void testRequestCache1UsingThreadIsolation() {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
SuccessfulCacheableCommand<String> command1 = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "A");
SuccessfulCacheableCommand<String> command2 = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "A");
assertTrue(command1.isCommandRunningInThread());
Future<String> f1 = command1.observe().toBlocking().toFuture();
Future<String> f2 = command2.observe().toBlocking().toFuture();
try {
assertEquals("A", f1.get());
assertEquals("A", f2.get());
} catch (Exception e) {
throw new RuntimeException(e);
}
assertTrue(command1.executed);
// the second one should not have executed as it should have received the cached value instead
assertFalse(command2.executed);
assertCommandExecutionEvents(command1, HystrixEventType.EMIT, HystrixEventType.SUCCESS);
assertTrue(command1.getExecutionTimeInMilliseconds() > -1);
assertFalse(command1.isResponseFromCache());
assertNull(command1.getExecutionException());
// the execution log for command2 should show it came from cache
assertCommandExecutionEvents(command2, HystrixEventType.EMIT, HystrixEventType.SUCCESS, HystrixEventType.RESPONSE_FROM_CACHE);
assertTrue(command2.getExecutionTimeInMilliseconds() == -1);
assertTrue(command2.isResponseFromCache());
assertNull(command2.getExecutionException());
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(2);
}
/**
* Test Request scoped caching doesn't prevent different ones from executing
*/
@Test
public void testRequestCache2UsingThreadIsolation() {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
SuccessfulCacheableCommand<String> command1 = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "A");
SuccessfulCacheableCommand<String> command2 = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "B");
assertTrue(command1.isCommandRunningInThread());
Future<String> f1 = command1.observe().toBlocking().toFuture();
Future<String> f2 = command2.observe().toBlocking().toFuture();
try {
assertEquals("A", f1.get());
assertEquals("B", f2.get());
} catch (Exception e) {
throw new RuntimeException(e);
}
assertTrue(command1.executed);
// both should execute as they are different
assertTrue(command2.executed);
assertCommandExecutionEvents(command1, HystrixEventType.EMIT, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.EMIT, HystrixEventType.SUCCESS);
assertTrue(command2.getExecutionTimeInMilliseconds() > -1);
assertFalse(command2.isResponseFromCache());
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(2);
}
/**
* Test Request scoped caching with a mixture of commands
*/
@Test
public void testRequestCache3UsingThreadIsolation() {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
SuccessfulCacheableCommand<String> command1 = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "A");
SuccessfulCacheableCommand<String> command2 = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "B");
SuccessfulCacheableCommand<String> command3 = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "A");
assertTrue(command1.isCommandRunningInThread());
Future<String> f1 = command1.observe().toBlocking().toFuture();
Future<String> f2 = command2.observe().toBlocking().toFuture();
Future<String> f3 = command3.observe().toBlocking().toFuture();
try {
assertEquals("A", f1.get());
assertEquals("B", f2.get());
assertEquals("A", f3.get());
} catch (Exception e) {
throw new RuntimeException(e);
}
assertTrue(command1.executed);
// both should execute as they are different
assertTrue(command2.executed);
// but the 3rd should come from cache
assertFalse(command3.executed);
assertCommandExecutionEvents(command1, HystrixEventType.EMIT, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.EMIT, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command3, HystrixEventType.EMIT, HystrixEventType.SUCCESS, HystrixEventType.RESPONSE_FROM_CACHE);
assertTrue(command3.getExecutionTimeInMilliseconds() == -1);
assertTrue(command3.isResponseFromCache());
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(3);
}
/**
* Test Request scoped caching of commands so that a 2nd duplicate call doesn't execute but returns the previous Future
*/
@Test
public void testRequestCacheWithSlowExecution() {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
SlowCacheableCommand command1 = new SlowCacheableCommand(circuitBreaker, "A", 200);
SlowCacheableCommand command2 = new SlowCacheableCommand(circuitBreaker, "A", 100);
SlowCacheableCommand command3 = new SlowCacheableCommand(circuitBreaker, "A", 100);
SlowCacheableCommand command4 = new SlowCacheableCommand(circuitBreaker, "A", 100);
Future<String> f1 = command1.observe().toBlocking().toFuture();
Future<String> f2 = command2.observe().toBlocking().toFuture();
Future<String> f3 = command3.observe().toBlocking().toFuture();
Future<String> f4 = command4.observe().toBlocking().toFuture();
try {
assertEquals("A", f2.get());
assertEquals("A", f3.get());
assertEquals("A", f4.get());
assertEquals("A", f1.get());
} catch (Exception e) {
throw new RuntimeException(e);
}
assertTrue(command1.executed);
// the second one should not have executed as it should have received the cached value instead
assertFalse(command2.executed);
assertFalse(command3.executed);
assertFalse(command4.executed);
// the execution log for command1 should show an EMIT and a SUCCESS
assertCommandExecutionEvents(command1, HystrixEventType.EMIT, HystrixEventType.SUCCESS);
assertTrue(command1.getExecutionTimeInMilliseconds() > -1);
assertFalse(command1.isResponseFromCache());
// the execution log for command2 should show it came from cache
assertCommandExecutionEvents(command2, HystrixEventType.EMIT, HystrixEventType.SUCCESS, HystrixEventType.RESPONSE_FROM_CACHE);
assertTrue(command2.getExecutionTimeInMilliseconds() == -1);
assertTrue(command2.isResponseFromCache());
assertCommandExecutionEvents(command3, HystrixEventType.EMIT, HystrixEventType.SUCCESS, HystrixEventType.RESPONSE_FROM_CACHE);
assertTrue(command3.isResponseFromCache());
assertTrue(command3.getExecutionTimeInMilliseconds() == -1);
assertCommandExecutionEvents(command4, HystrixEventType.EMIT, HystrixEventType.SUCCESS, HystrixEventType.RESPONSE_FROM_CACHE);
assertTrue(command4.isResponseFromCache());
assertTrue(command4.getExecutionTimeInMilliseconds() == -1);
assertSaneHystrixRequestLog(4);
// semaphore isolated
assertFalse(command1.isExecutedInThread());
assertFalse(command2.isExecutedInThread());
assertFalse(command3.isExecutedInThread());
assertFalse(command4.isExecutedInThread());
}
/**
* Test Request scoped caching with a mixture of commands
*/
@Test
public void testNoRequestCache3UsingThreadIsolation() {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
SuccessfulCacheableCommand<String> command1 = new SuccessfulCacheableCommand<String>(circuitBreaker, false, "A");
SuccessfulCacheableCommand<String> command2 = new SuccessfulCacheableCommand<String>(circuitBreaker, false, "B");
SuccessfulCacheableCommand<String> command3 = new SuccessfulCacheableCommand<String>(circuitBreaker, false, "A");
assertTrue(command1.isCommandRunningInThread());
Future<String> f1 = command1.observe().toBlocking().toFuture();
Future<String> f2 = command2.observe().toBlocking().toFuture();
Future<String> f3 = command3.observe().toBlocking().toFuture();
try {
assertEquals("A", f1.get());
assertEquals("B", f2.get());
assertEquals("A", f3.get());
} catch (Exception e) {
throw new RuntimeException(e);
}
assertTrue(command1.executed);
// both should execute as they are different
assertTrue(command2.executed);
// this should also execute since we disabled the cache
assertTrue(command3.executed);
assertCommandExecutionEvents(command1, HystrixEventType.EMIT, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.EMIT, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command3, HystrixEventType.EMIT, HystrixEventType.SUCCESS);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(3);
// thread isolated
assertTrue(command1.isExecutedInThread());
assertTrue(command2.isExecutedInThread());
assertTrue(command3.isExecutedInThread());
}
@Test
public void testNoRequestCacheOnTimeoutThrowsException() throws Exception {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
NoRequestCacheTimeoutWithoutFallback r1 = new NoRequestCacheTimeoutWithoutFallback(circuitBreaker);
try {
System.out.println("r1 value: " + r1.observe().toBlocking().single());
// we should have thrown an exception
fail("expected a timeout");
} catch (HystrixRuntimeException e) {
assertTrue(r1.isResponseTimedOut());
// what we want
}
NoRequestCacheTimeoutWithoutFallback r2 = new NoRequestCacheTimeoutWithoutFallback(circuitBreaker);
try {
r2.observe().toBlocking().single();
// we should have thrown an exception
fail("expected a timeout");
} catch (HystrixRuntimeException e) {
assertTrue(r2.isResponseTimedOut());
// what we want
}
NoRequestCacheTimeoutWithoutFallback r3 = new NoRequestCacheTimeoutWithoutFallback(circuitBreaker);
Future<Boolean> f3 = r3.observe().toBlocking().toFuture();
try {
f3.get();
// we should have thrown an exception
fail("expected a timeout");
} catch (ExecutionException e) {
e.printStackTrace();
assertTrue(r3.isResponseTimedOut());
// what we want
}
Thread.sleep(500); // timeout on command is set to 200ms
NoRequestCacheTimeoutWithoutFallback r4 = new NoRequestCacheTimeoutWithoutFallback(circuitBreaker);
try {
r4.observe().toBlocking().single();
// we should have thrown an exception
fail("expected a timeout");
} catch (HystrixRuntimeException e) {
e.printStackTrace();
assertTrue(r4.isResponseTimedOut());
assertFalse(r4.isResponseFromFallback());
// what we want
}
assertCommandExecutionEvents(r1, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING);
assertCommandExecutionEvents(r2, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING);
assertCommandExecutionEvents(r3, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING);
assertCommandExecutionEvents(r4, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(4);
}
@Test
public void testRequestCacheOnTimeoutCausesNullPointerException() throws Exception {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
RequestCacheNullPointerExceptionCase command1 = new RequestCacheNullPointerExceptionCase(circuitBreaker);
RequestCacheNullPointerExceptionCase command2 = new RequestCacheNullPointerExceptionCase(circuitBreaker);
RequestCacheNullPointerExceptionCase command3 = new RequestCacheNullPointerExceptionCase(circuitBreaker);
RequestCacheNullPointerExceptionCase command4 = new RequestCacheNullPointerExceptionCase(circuitBreaker);
RequestCacheNullPointerExceptionCase command5 = new RequestCacheNullPointerExceptionCase(circuitBreaker);
// Expect it to time out - all results should be false
assertFalse(command1.observe().toBlocking().single());
assertFalse(command2.observe().toBlocking().single()); // return from cache #1
assertFalse(command3.observe().toBlocking().single()); // return from cache #2
Thread.sleep(500); // timeout on command is set to 200ms
Boolean value = command4.observe().toBlocking().single(); // return from cache #3
assertFalse(value);
Future<Boolean> f = command5.observe().toBlocking().toFuture(); // return from cache #4
// the bug is that we're getting a null Future back, rather than a Future that returns false
assertNotNull(f);
assertFalse(f.get());
assertTrue(command5.isResponseFromFallback());
assertTrue(command5.isResponseTimedOut());
assertFalse(command5.isFailedExecution());
assertFalse(command5.isResponseShortCircuited());
assertNotNull(command5.getExecutionException());
assertCommandExecutionEvents(command1, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS, HystrixEventType.RESPONSE_FROM_CACHE);
assertCommandExecutionEvents(command3, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS, HystrixEventType.RESPONSE_FROM_CACHE);
assertCommandExecutionEvents(command4, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS, HystrixEventType.RESPONSE_FROM_CACHE);
assertCommandExecutionEvents(command5, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS, HystrixEventType.RESPONSE_FROM_CACHE);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(5);
}
@Test
public void testRequestCacheOnTimeoutThrowsException() throws Exception {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
RequestCacheTimeoutWithoutFallback r1 = new RequestCacheTimeoutWithoutFallback(circuitBreaker);
try {
System.out.println("r1 value: " + r1.observe().toBlocking().single());
// we should have thrown an exception
fail("expected a timeout");
} catch (HystrixRuntimeException e) {
assertTrue(r1.isResponseTimedOut());
assertNotNull(r1.getExecutionException());
// what we want
}
RequestCacheTimeoutWithoutFallback r2 = new RequestCacheTimeoutWithoutFallback(circuitBreaker);
try {
r2.observe().toBlocking().single();
// we should have thrown an exception
fail("expected a timeout");
} catch (HystrixRuntimeException e) {
assertTrue(r2.isResponseTimedOut());
assertNotNull(r2.getExecutionException());
// what we want
}
RequestCacheTimeoutWithoutFallback r3 = new RequestCacheTimeoutWithoutFallback(circuitBreaker);
Future<Boolean> f3 = r3.observe().toBlocking().toFuture();
try {
f3.get();
// we should have thrown an exception
fail("expected a timeout");
} catch (ExecutionException e) {
e.printStackTrace();
assertTrue(r3.isResponseTimedOut());
assertNotNull(r3.getExecutionException());
// what we want
}
Thread.sleep(500); // timeout on command is set to 200ms
RequestCacheTimeoutWithoutFallback r4 = new RequestCacheTimeoutWithoutFallback(circuitBreaker);
try {
r4.observe().toBlocking().single();
// we should have thrown an exception
fail("expected a timeout");
} catch (HystrixRuntimeException e) {
assertTrue(r4.isResponseTimedOut());
assertFalse(r4.isResponseFromFallback());
assertNotNull(r4.getExecutionException());
}
assertCommandExecutionEvents(r1, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING);
assertCommandExecutionEvents(r2, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING, HystrixEventType.RESPONSE_FROM_CACHE);
assertCommandExecutionEvents(r3, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING, HystrixEventType.RESPONSE_FROM_CACHE);
assertCommandExecutionEvents(r4, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING, HystrixEventType.RESPONSE_FROM_CACHE);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(4);
}
@Test
public void testRequestCacheOnThreadRejectionThrowsException() throws Exception {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
CountDownLatch completionLatch = new CountDownLatch(1);
RequestCacheThreadRejectionWithoutFallback r1 = new RequestCacheThreadRejectionWithoutFallback(circuitBreaker, completionLatch);
try {
System.out.println("r1: " + r1.observe().toBlocking().single());
// we should have thrown an exception
fail("expected a rejection");
} catch (HystrixRuntimeException e) {
e.printStackTrace();
assertTrue(r1.isResponseRejected());
assertNotNull(r1.getExecutionException());
// what we want
}
RequestCacheThreadRejectionWithoutFallback r2 = new RequestCacheThreadRejectionWithoutFallback(circuitBreaker, completionLatch);
try {
System.out.println("r2: " + r2.observe().toBlocking().single());
// we should have thrown an exception
fail("expected a rejection");
} catch (HystrixRuntimeException e) {
// e.printStackTrace();
assertTrue(r2.isResponseRejected());
assertNotNull(r2.getExecutionException());
// what we want
}
RequestCacheThreadRejectionWithoutFallback r3 = new RequestCacheThreadRejectionWithoutFallback(circuitBreaker, completionLatch);
try {
System.out.println("f3: " + r3.observe().toBlocking().toFuture().get());
// we should have thrown an exception
fail("expected a rejection");
} catch (ExecutionException e) {
assertTrue(r3.isResponseRejected());
assertTrue(e.getCause() instanceof HystrixRuntimeException);
assertNotNull(r3.getExecutionException());
}
// let the command finish (only 1 should actually be blocked on this due to the response cache)
completionLatch.countDown();
// then another after the command has completed
RequestCacheThreadRejectionWithoutFallback r4 = new RequestCacheThreadRejectionWithoutFallback(circuitBreaker, completionLatch);
try {
System.out.println("r4: " + r4.observe().toBlocking().single());
// we should have thrown an exception
fail("expected a rejection");
} catch (HystrixRuntimeException e) {
// e.printStackTrace();
assertTrue(r4.isResponseRejected());
assertFalse(r4.isResponseFromFallback());
assertNotNull(r4.getExecutionException());
// what we want
}
assertCommandExecutionEvents(r1, HystrixEventType.THREAD_POOL_REJECTED, HystrixEventType.FALLBACK_MISSING);
assertCommandExecutionEvents(r2, HystrixEventType.THREAD_POOL_REJECTED, HystrixEventType.FALLBACK_MISSING, HystrixEventType.RESPONSE_FROM_CACHE);
assertCommandExecutionEvents(r3, HystrixEventType.THREAD_POOL_REJECTED, HystrixEventType.FALLBACK_MISSING, HystrixEventType.RESPONSE_FROM_CACHE);
assertCommandExecutionEvents(r4, HystrixEventType.THREAD_POOL_REJECTED, HystrixEventType.FALLBACK_MISSING, HystrixEventType.RESPONSE_FROM_CACHE);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(4);
}
/**
* Test that we can do basic execution without a RequestVariable being initialized.
*/
@Test
public void testBasicExecutionWorksWithoutRequestVariable() {
try {
/* force the RequestVariable to not be initialized */
HystrixRequestContext.setContextOnCurrentThread(null);
TestHystrixObservableCommand<Boolean> command = new SuccessfulTestCommand(ExecutionIsolationStrategy.SEMAPHORE);
assertEquals(true, command.observe().toBlocking().single());
TestHystrixObservableCommand<Boolean> command2 = new SuccessfulTestCommand(ExecutionIsolationStrategy.SEMAPHORE);
assertEquals(true, command2.observe().toBlocking().toFuture().get());
// we should be able to execute without a RequestVariable if ...
// 1) We don't have a cacheKey
// 2) We don't ask for the RequestLog
// 3) We don't do collapsing
// semaphore isolated
assertFalse(command.isExecutedInThread());
assertNull(command.getExecutionException());
} catch (Exception e) {
e.printStackTrace();
fail("We received an exception => " + e.getMessage());
}
assertNull(HystrixRequestLog.getCurrentRequest());
}
/**
* Test that if we try and execute a command with a cacheKey without initializing RequestVariable that it gives an error.
*/
@Test
public void testCacheKeyExecutionRequiresRequestVariable() {
try {
/* force the RequestVariable to not be initialized */
HystrixRequestContext.setContextOnCurrentThread(null);
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
SuccessfulCacheableCommand<String> command = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "one");
assertEquals("one", command.observe().toBlocking().single());
SuccessfulCacheableCommand<String> command2 = new SuccessfulCacheableCommand<String>(circuitBreaker, true, "two");
assertEquals("two", command2.observe().toBlocking().toFuture().get());
fail("We expect an exception because cacheKey requires RequestVariable.");
// semaphore isolated
assertFalse(command.isExecutedInThread());
assertNull(command.getExecutionException());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Test that a BadRequestException can be synchronously thrown from a semaphore-isolated command and not count towards errors and bypasses fallback.
*/
@Test
public void testSemaphoreIsolatedBadRequestSyncExceptionObserve() {
testBadRequestExceptionObserve(ExecutionIsolationStrategy.SEMAPHORE, KnownHystrixBadRequestFailureTestCommand.SYNC_EXCEPTION);
}
/**
* Test that a BadRequestException can be asynchronously thrown from a semaphore-isolated command and not count towards errors and bypasses fallback.
*/
@Test
public void testSemaphoreIsolatedBadRequestAsyncExceptionObserve() {
testBadRequestExceptionObserve(ExecutionIsolationStrategy.SEMAPHORE, KnownHystrixBadRequestFailureTestCommand.ASYNC_EXCEPTION);
}
/**
* Test that a BadRequestException can be synchronously thrown from a thread-isolated command and not count towards errors and bypasses fallback.
*/
@Test
public void testThreadIsolatedBadRequestSyncExceptionObserve() {
testBadRequestExceptionObserve(ExecutionIsolationStrategy.THREAD, KnownHystrixBadRequestFailureTestCommand.SYNC_EXCEPTION);
}
/**
* Test that a BadRequestException can be asynchronously thrown from a thread-isolated command and not count towards errors and bypasses fallback.
*/
@Test
public void testThreadIsolatedBadRequestAsyncExceptionObserve() {
testBadRequestExceptionObserve(ExecutionIsolationStrategy.THREAD, KnownHystrixBadRequestFailureTestCommand.ASYNC_EXCEPTION);
}
private void testBadRequestExceptionObserve(ExecutionIsolationStrategy isolationStrategy, boolean asyncException) {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
KnownHystrixBadRequestFailureTestCommand command1 = new KnownHystrixBadRequestFailureTestCommand(circuitBreaker, isolationStrategy, asyncException);
try {
command1.observe().toBlocking().single();
fail("we expect to receive a " + HystrixBadRequestException.class.getSimpleName());
} catch (HystrixBadRequestException e) {
// success
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
fail("We expect a " + HystrixBadRequestException.class.getSimpleName() + " but got a " + e.getClass().getSimpleName());
}
assertCommandExecutionEvents(command1, HystrixEventType.BAD_REQUEST);
assertSaneHystrixRequestLog(1);
assertNotNull(command1.getExecutionException());
}
/**
* Test that synchronous BadRequestException behavior works the same on a cached response for a semaphore-isolated command.
*/
@Test
public void testSyncBadRequestExceptionOnResponseFromCacheInSempahore() {
testBadRequestExceptionOnResponseFromCache(ExecutionIsolationStrategy.SEMAPHORE, KnownHystrixBadRequestFailureTestCommand.SYNC_EXCEPTION);
}
/**
* Test that asynchronous BadRequestException behavior works the same on a cached response for a semaphore-isolated command.
*/
@Test
public void testAsyncBadRequestExceptionOnResponseFromCacheInSemaphore() {
testBadRequestExceptionOnResponseFromCache(ExecutionIsolationStrategy.SEMAPHORE, KnownHystrixBadRequestFailureTestCommand.ASYNC_EXCEPTION);
}
/**
* Test that synchronous BadRequestException behavior works the same on a cached response for a thread-isolated command.
*/
@Test
public void testSyncBadRequestExceptionOnResponseFromCacheInThread() {
testBadRequestExceptionOnResponseFromCache(ExecutionIsolationStrategy.THREAD, KnownHystrixBadRequestFailureTestCommand.SYNC_EXCEPTION);
}
/**
* Test that asynchronous BadRequestException behavior works the same on a cached response for a thread-isolated command.
*/
@Test
public void testAsyncBadRequestExceptionOnResponseFromCacheInThread() {
testBadRequestExceptionOnResponseFromCache(ExecutionIsolationStrategy.THREAD, KnownHystrixBadRequestFailureTestCommand.ASYNC_EXCEPTION);
}
private void testBadRequestExceptionOnResponseFromCache(ExecutionIsolationStrategy isolationStrategy, boolean asyncException) {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
KnownHystrixBadRequestFailureTestCommand command1 = new KnownHystrixBadRequestFailureTestCommand(circuitBreaker, isolationStrategy, asyncException);
// execute once to cache the value
try {
command1.observe().toBlocking().single();
} catch (Throwable e) {
// ignore
}
KnownHystrixBadRequestFailureTestCommand command2 = new KnownHystrixBadRequestFailureTestCommand(circuitBreaker, isolationStrategy, asyncException);
try {
command2.observe().toBlocking().toFuture().get();
fail("we expect to receive a " + HystrixBadRequestException.class.getSimpleName());
} catch (ExecutionException e) {
e.printStackTrace();
if (e.getCause() instanceof HystrixBadRequestException) {
// success
} else {
fail("We expect a " + HystrixBadRequestException.class.getSimpleName() + " but got a " + e.getClass().getSimpleName());
}
} catch (Exception e) {
e.printStackTrace();
fail();
}
assertCommandExecutionEvents(command1, HystrixEventType.BAD_REQUEST);
assertCommandExecutionEvents(command2, HystrixEventType.BAD_REQUEST);
assertSaneHystrixRequestLog(2);
assertNotNull(command1.getExecutionException());
assertNotNull(command2.getExecutionException());
}
/**
* Test a checked Exception being thrown
*/
@Test
public void testCheckedExceptionViaExecute() {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
CommandWithCheckedException command = new CommandWithCheckedException(circuitBreaker);
try {
command.observe().toBlocking().single();
fail("we expect to receive a " + Exception.class.getSimpleName());
} catch (Exception e) {
assertEquals("simulated checked exception message", e.getCause().getMessage());
}
assertEquals("simulated checked exception message", command.getFailedExecutionException().getMessage());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isFailedExecution());
assertNotNull(command.getExecutionException());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_MISSING);
assertSaneHystrixRequestLog(1);
}
/**
* Test a java.lang.Error being thrown
*
* @throws InterruptedException
*/
@Test
public void testCheckedExceptionViaObserve() throws InterruptedException {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
CommandWithCheckedException command = new CommandWithCheckedException(circuitBreaker);
final AtomicReference<Throwable> t = new AtomicReference<Throwable>();
final CountDownLatch latch = new CountDownLatch(1);
try {
command.observe().subscribe(new Observer<Boolean>() {
@Override
public void onCompleted() {
latch.countDown();
}
@Override
public void onError(Throwable e) {
t.set(e);
latch.countDown();
}
@Override
public void onNext(Boolean args) {
}
});
} catch (Exception e) {
e.printStackTrace();
fail("we should not get anything thrown, it should be emitted via the Observer#onError method");
}
latch.await(1, TimeUnit.SECONDS);
assertNotNull(t.get());
t.get().printStackTrace();
assertTrue(t.get() instanceof HystrixRuntimeException);
assertEquals("simulated checked exception message", t.get().getCause().getMessage());
assertEquals("simulated checked exception message", command.getFailedExecutionException().getMessage());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isFailedExecution());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_MISSING);
assertNotNull(command.getExecutionException());
// semaphore isolated
assertFalse(command.isExecutedInThread());
assertSaneHystrixRequestLog(1);
}
/**
* Test a java.lang.Error being thrown
*
* @throws InterruptedException
*/
@Test
public void testErrorThrownViaObserve() throws InterruptedException {
TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
CommandWithErrorThrown command = new CommandWithErrorThrown(circuitBreaker, true);
final AtomicReference<Throwable> t = new AtomicReference<Throwable>();
final CountDownLatch latch = new CountDownLatch(1);
try {
command.observe().subscribe(new Observer<Boolean>() {
@Override
public void onCompleted() {
latch.countDown();
}
@Override
public void onError(Throwable e) {
t.set(e);
latch.countDown();
}
@Override
public void onNext(Boolean args) {
}
});
} catch (Exception e) {
e.printStackTrace();
fail("we should not get anything thrown, it should be emitted via the Observer#onError method");
}
latch.await(1, TimeUnit.SECONDS);
assertNotNull(t.get());
t.get().printStackTrace();
assertTrue(t.get() instanceof HystrixRuntimeException);
// the actual error is an extra cause level deep because Hystrix needs to wrap Throwable/Error as it's public
// methods only support Exception and it's not a strong enough reason to break backwards compatibility and jump to version 2.x
assertEquals("simulated java.lang.Error message", t.get().getCause().getCause().getMessage());
assertEquals("simulated java.lang.Error message", command.getFailedExecutionException().getCause().getMessage());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isFailedExecution());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_MISSING);
assertNotNull(command.getExecutionException());
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertFalse(command.isExecutedInThread());
assertSaneHystrixRequestLog(1);
}
@Test
public void testInterruptObserveOnTimeout() throws InterruptedException {
// given
InterruptibleCommand cmd = new InterruptibleCommand(new TestCircuitBreaker(), true);
// when
cmd.observe().subscribe();
// then
Thread.sleep(500);
assertTrue(cmd.hasBeenInterrupted());
}
@Test
public void testInterruptToObservableOnTimeout() throws InterruptedException {
// given
InterruptibleCommand cmd = new InterruptibleCommand(new TestCircuitBreaker(), true);
// when
cmd.toObservable().subscribe();
// then
Thread.sleep(500);
assertTrue(cmd.hasBeenInterrupted());
}
@Override
protected void assertHooksOnSuccess(Func0<TestHystrixObservableCommand<Integer>> ctor, Action1<TestHystrixObservableCommand<Integer>> assertion) {
assertBlockingObserve(ctor.call(), assertion, true);
assertNonBlockingObserve(ctor.call(), assertion, true);
}
@Override
protected void assertHooksOnFailure(Func0<TestHystrixObservableCommand<Integer>> ctor, Action1<TestHystrixObservableCommand<Integer>> assertion) {
assertBlockingObserve(ctor.call(), assertion, false);
assertNonBlockingObserve(ctor.call(), assertion, false);
}
@Override
void assertHooksOnFailure(Func0<TestHystrixObservableCommand<Integer>> ctor, Action1<TestHystrixObservableCommand<Integer>> assertion, boolean failFast) {
}
/**
*********************** HystrixObservableCommand-specific THREAD-ISOLATED Execution Hook Tests **************************************
*/
/**
* Short-circuitInteger : NO
* Thread/semaphore: THREAD
* Thread Pool fullInteger : NO
* Thread Pool Queue fullInteger: NO
* Timeout: NO
* Execution Result: EMITx4, SUCCESS
*/
@Test
public void testExecutionHookThreadMultipleEmitsAndThenSuccess() {
assertHooksOnSuccess(
new Func0<TestHystrixObservableCommand<Integer>>() {
@Override
public TestHystrixObservableCommand<Integer> call() {
return getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.MULTIPLE_EMITS_THEN_SUCCESS);
}
},
new Action1<TestHystrixObservableCommand<Integer>>() {
@Override
public void call(TestHystrixObservableCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(4, 0, 1));
assertTrue(hook.executionEventsMatch(4, 0, 1));
assertTrue(hook.fallbackEventsMatch(0, 0, 0));
assertEquals("onStart - onThreadStart - !onRunStart - onExecutionStart - onExecutionEmit - !onRunSuccess - !onComplete - onEmit - onExecutionEmit - !onRunSuccess - !onComplete - onEmit - onExecutionEmit - !onRunSuccess - !onComplete - onEmit - onExecutionEmit - !onRunSuccess - !onComplete - onEmit - onExecutionSuccess - onThreadComplete - onSuccess - ", command.getBuilder().executionHook.executionSequence.toString());
}
});
}
/**
* Short-circuitInteger : NO
* Thread/semaphore: THREAD
* Thread Pool fullInteger : NO
* Thread Pool Queue fullInteger: NO
* Timeout: NO
* Execution Result: EMITx4, FAILURE, FALLBACK_EMITx4, FALLBACK_SUCCESS
*/
@Test
public void testExecutionHookThreadMultipleEmitsThenErrorThenMultipleFallbackEmitsAndThenFallbackSuccess() {
assertHooksOnSuccess(
new Func0<TestHystrixObservableCommand<Integer>>() {
@Override
public TestHystrixObservableCommand<Integer> call() {
return getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.MULTIPLE_EMITS_THEN_FAILURE, 0, AbstractTestHystrixCommand.FallbackResult.MULTIPLE_EMITS_THEN_SUCCESS);
}
},
new Action1<TestHystrixObservableCommand<Integer>>() {
@Override
public void call(TestHystrixObservableCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(8, 0, 1));
assertTrue(hook.executionEventsMatch(4, 1, 0));
assertTrue(hook.fallbackEventsMatch(4, 0, 1));
assertEquals(RuntimeException.class, hook.getExecutionException().getClass());
assertEquals("onStart - onThreadStart - !onRunStart - onExecutionStart - " +
"onExecutionEmit - !onRunSuccess - !onComplete - onEmit - " +
"onExecutionEmit - !onRunSuccess - !onComplete - onEmit - " +
"onExecutionEmit - !onRunSuccess - !onComplete - onEmit - " +
"onExecutionEmit - !onRunSuccess - !onComplete - onEmit - " +
"onExecutionError - !onRunError - onThreadComplete - onFallbackStart - " +
"onFallbackEmit - !onFallbackSuccess - !onComplete - onEmit - " +
"onFallbackEmit - !onFallbackSuccess - !onComplete - onEmit - " +
"onFallbackEmit - !onFallbackSuccess - !onComplete - onEmit - " +
"onFallbackEmit - !onFallbackSuccess - !onComplete - onEmit - " +
"onFallbackSuccess - onSuccess - ", command.getBuilder().executionHook.executionSequence.toString());
}
});
}
/**
* Short-circuitInteger : NO
* Thread/semaphore: THREAD
* Thread Pool fullInteger : NO
* Thread Pool Queue fullInteger: NO
* Timeout: NO
* Execution Result: asynchronous HystrixBadRequestException
*/
@Test
public void testExecutionHookThreadAsyncBadRequestException() {
assertHooksOnFailure(
new Func0<TestHystrixObservableCommand<Integer>>() {
@Override
public TestHystrixObservableCommand<Integer> call() {
return getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.ASYNC_BAD_REQUEST);
}
},
new Action1<TestHystrixObservableCommand<Integer>>() {
@Override
public void call(TestHystrixObservableCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 1, 0));
assertTrue(hook.fallbackEventsMatch(0, 0, 0));
assertEquals(HystrixBadRequestException.class, hook.getCommandException().getClass());
assertEquals(HystrixBadRequestException.class, hook.getExecutionException().getClass());
assertEquals("onStart - onThreadStart - !onRunStart - onExecutionStart - onExecutionError - !onRunError - onThreadComplete - onError - ", command.getBuilder().executionHook.executionSequence.toString());
}
});
}
/**
* Short-circuitInteger : NO
* Thread/semaphore: THREAD
* Thread Pool fullInteger : NO
* Thread Pool Queue fullInteger: NO
* Timeout: NO
* Execution Result: async HystrixRuntimeException
* Fallback: UnsupportedOperationException
*/
@Test
public void testExecutionHookThreadAsyncExceptionNoFallback() {
assertHooksOnFailure(
new Func0<TestHystrixObservableCommand<Integer>>() {
@Override
public TestHystrixObservableCommand<Integer> call() {
return getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.ASYNC_FAILURE, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED);
}
},
new Action1<TestHystrixObservableCommand<Integer>>() {
@Override
public void call(TestHystrixObservableCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 1, 0));
assertTrue(hook.fallbackEventsMatch(0, 0, 0));
assertEquals(RuntimeException.class, hook.getCommandException().getClass());
assertEquals(RuntimeException.class, hook.getExecutionException().getClass());
assertNull(hook.getFallbackException());
assertEquals("onStart - onThreadStart - !onRunStart - onExecutionStart - onExecutionError - !onRunError - onThreadComplete - onError - ", command.getBuilder().executionHook.executionSequence.toString());
}
});
}
/**
* Short-circuitInteger : NO
* Thread/semaphore: THREAD
* Thread Pool fullInteger : NO
* Thread Pool Queue fullInteger: NO
* Timeout: NO
* Execution Result: async HystrixRuntimeException
* Fallback: SUCCESS
*/
@Test
public void testExecutionHookThreadAsyncExceptionSuccessfulFallback() {
assertHooksOnSuccess(
new Func0<TestHystrixObservableCommand<Integer>>() {
@Override
public TestHystrixObservableCommand<Integer> call() {
return getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.ASYNC_FAILURE, AbstractTestHystrixCommand.FallbackResult.SUCCESS);
}
},
new Action1<TestHystrixObservableCommand<Integer>>() {
@Override
public void call(TestHystrixObservableCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(1, 0, 1));
assertTrue(hook.executionEventsMatch(0, 1, 0));
assertTrue(hook.fallbackEventsMatch(1, 0, 1));
assertEquals(RuntimeException.class, hook.getExecutionException().getClass());
assertEquals("onStart - onThreadStart - !onRunStart - onExecutionStart - onExecutionError - !onRunError - onThreadComplete - onFallbackStart - onFallbackEmit - !onFallbackSuccess - !onComplete - onEmit - onFallbackSuccess - onSuccess - ", command.getBuilder().executionHook.executionSequence.toString());
}
});
}
/**
* Short-circuitInteger : NO
* Thread/semaphore: THREAD
* Thread Pool fullInteger : NO
* Thread Pool Queue fullInteger: NO
* Timeout: NO
* Execution Result: sync HystrixRuntimeException
* Fallback: async HystrixRuntimeException
*/
@Test
public void testExecutionHookThreadSyncExceptionAsyncUnsuccessfulFallback() {
assertHooksOnFailure(
new Func0<TestHystrixObservableCommand<Integer>>() {
@Override
public TestHystrixObservableCommand<Integer> call() {
return getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.FAILURE, AbstractTestHystrixCommand.FallbackResult.ASYNC_FAILURE);
}
},
new Action1<TestHystrixObservableCommand<Integer>>() {
@Override
public void call(TestHystrixObservableCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 1, 0));
assertTrue(hook.fallbackEventsMatch(0, 1, 0));
assertEquals(RuntimeException.class, hook.getCommandException().getClass());
assertEquals(RuntimeException.class, hook.getExecutionException().getClass());
assertEquals(RuntimeException.class, hook.getFallbackException().getClass());
assertEquals("onStart - onThreadStart - !onRunStart - onExecutionStart - onExecutionError - !onRunError - onThreadComplete - onFallbackStart - onFallbackError - onError - ", command.getBuilder().executionHook.executionSequence.toString());
}
});
}
/**
* Short-circuitInteger : NO
* Thread/semaphore: THREAD
* Thread Pool fullInteger : NO
* Thread Pool Queue fullInteger: NO
* Timeout: NO
* Execution Result: async HystrixRuntimeException
* Fallback: sync HystrixRuntimeException
*/
@Test
public void testExecutionHookThreadAsyncExceptionSyncUnsuccessfulFallback() {
assertHooksOnFailure(
new Func0<TestHystrixObservableCommand<Integer>>() {
@Override
public TestHystrixObservableCommand<Integer> call() {
return getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.ASYNC_FAILURE, AbstractTestHystrixCommand.FallbackResult.FAILURE);
}
},
new Action1<TestHystrixObservableCommand<Integer>>() {
@Override
public void call(TestHystrixObservableCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 1, 0));
assertTrue(hook.fallbackEventsMatch(0, 1, 0));
assertEquals(RuntimeException.class, hook.getCommandException().getClass());
assertEquals(RuntimeException.class, hook.getExecutionException().getClass());
assertEquals(RuntimeException.class, hook.getFallbackException().getClass());
assertEquals("onStart - onThreadStart - !onRunStart - onExecutionStart - onExecutionError - !onRunError - onThreadComplete - onFallbackStart - onFallbackError - onError - ", command.getBuilder().executionHook.executionSequence.toString());
}
});
}
/**
* Short-circuitInteger : NO
* Thread/semaphore: THREAD
* Thread Pool fullInteger : NO
* Thread Pool Queue fullInteger: NO
* Timeout: NO
* Execution Result: async HystrixRuntimeException
* Fallback: async HystrixRuntimeException
*/
@Test
public void testExecutionHookThreadAsyncExceptionAsyncUnsuccessfulFallback() {
assertHooksOnFailure(
new Func0<TestHystrixObservableCommand<Integer>>() {
@Override
public TestHystrixObservableCommand<Integer> call() {
return getCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.ExecutionResult.ASYNC_FAILURE, AbstractTestHystrixCommand.FallbackResult.ASYNC_FAILURE);
}
},
new Action1<TestHystrixObservableCommand<Integer>>() {
@Override
public void call(TestHystrixObservableCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 1, 0));
assertTrue(hook.fallbackEventsMatch(0, 1, 0));
assertEquals(RuntimeException.class, hook.getCommandException().getClass());
assertEquals(RuntimeException.class, hook.getExecutionException().getClass());
assertEquals(RuntimeException.class, hook.getFallbackException().getClass());
assertEquals("onStart - onThreadStart - !onRunStart - onExecutionStart - onExecutionError - !onRunError - onThreadComplete - onFallbackStart - onFallbackError - onError - ", command.getBuilder().executionHook.executionSequence.toString());
}
});
}
/**
* Short-circuitInteger : YES
* Thread/semaphore: THREAD
* Fallback: async HystrixRuntimeException
*/
@Test
public void testExecutionHookThreadShortCircuitAsyncUnsuccessfulFallback() {
assertHooksOnFailure(
new Func0<TestHystrixObservableCommand<Integer>>() {
@Override
public TestHystrixObservableCommand<Integer> call() {
return getCircuitOpenCommand(ExecutionIsolationStrategy.THREAD, AbstractTestHystrixCommand.FallbackResult.ASYNC_FAILURE);
}
},
new Action1<TestHystrixObservableCommand<Integer>>() {
@Override
public void call(TestHystrixObservableCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 0, 0));
assertTrue(hook.fallbackEventsMatch(0, 1, 0));
assertEquals(RuntimeException.class, hook.getCommandException().getClass());
assertEquals(RuntimeException.class, hook.getFallbackException().getClass());
assertEquals("onStart - onFallbackStart - onFallbackError - onError - ", command.getBuilder().executionHook.executionSequence.toString());
}
});
}
/**
*********************** END HystrixObservableCommand-specific THREAD-ISOLATED Execution Hook Tests **************************************
*/
/**
********************* HystrixObservableCommand-specific SEMAPHORE-ISOLATED Execution Hook Tests ***********************************
*/
/**
* Short-circuitInteger : NO
* Thread/semaphore: SEMAPHORE
* Semaphore Permit reachedInteger : NO
* Execution Result: HystrixRuntimeException
* Fallback: asynchronous HystrixRuntimeException
*/
@Test
public void testExecutionHookSemaphoreExceptionUnsuccessfulAsynchronousFallback() {
assertHooksOnFailure(
new Func0<TestHystrixObservableCommand<Integer>>() {
@Override
public TestHystrixObservableCommand<Integer> call() {
return getCommand(ExecutionIsolationStrategy.SEMAPHORE, AbstractTestHystrixCommand.ExecutionResult.FAILURE, AbstractTestHystrixCommand.FallbackResult.ASYNC_FAILURE);
}
},
new Action1<TestHystrixObservableCommand<Integer>>() {
@Override
public void call(TestHystrixObservableCommand<Integer> command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 1, 0));
assertTrue(hook.fallbackEventsMatch(0, 1, 0));
assertEquals(RuntimeException.class, hook.getCommandException().getClass());
assertEquals(RuntimeException.class, hook.getExecutionException().getClass());
assertEquals(RuntimeException.class, hook.getFallbackException().getClass());
assertEquals("onStart - !onRunStart - onExecutionStart - onExecutionError - !onRunError - onFallbackStart - onFallbackError - onError - ", command.getBuilder().executionHook.executionSequence.toString());
}
});
}
/**
********************* END HystrixObservableCommand-specific SEMAPHORE-ISOLATED Execution Hook Tests ***********************************
*/
/**
* Test a command execution that fails but has a fallback.
*/
@Test
public void testExecutionFailureWithFallbackImplementedButDisabled() {
TestHystrixObservableCommand<Boolean> commandEnabled = new KnownFailureTestCommandWithFallback(new TestCircuitBreaker(), true, true);
try {
assertEquals(false, commandEnabled.observe().toBlocking().single());
} catch (Exception e) {
e.printStackTrace();
fail("We should have received a response from the fallback.");
}
TestHystrixObservableCommand<Boolean> commandDisabled = new KnownFailureTestCommandWithFallback(new TestCircuitBreaker(), false, true);
try {
assertEquals(false, commandDisabled.observe().toBlocking().single());
fail("expect exception thrown");
} catch (Exception e) {
// expected
}
assertEquals("we failed with a simulated issue", commandDisabled.getFailedExecutionException().getMessage());
assertTrue(commandDisabled.isFailedExecution());
assertNotNull(commandDisabled.getExecutionException());
assertCommandExecutionEvents(commandEnabled, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
assertCommandExecutionEvents(commandDisabled, HystrixEventType.FAILURE);
assertEquals(0, commandDisabled.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(2);
}
/**
* Test that we can still use thread isolation if desired.
*/
@Test
public void testSynchronousExecutionTimeoutValueViaExecute() {
HystrixObservableCommand.Setter properties = HystrixObservableCommand.Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("TestKey"))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withExecutionIsolationStrategy(ExecutionIsolationStrategy.THREAD)
.withExecutionTimeoutInMilliseconds(50));
System.out.println(">>>>> Begin: " + System.currentTimeMillis());
final AtomicBoolean startedExecution = new AtomicBoolean();
HystrixObservableCommand<String> command = new HystrixObservableCommand<String>(properties) {
@Override
protected Observable<String> construct() {
return Observable.create(new OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> t1) {
try {
startedExecution.set(true);
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t1.onNext("hello");
t1.onCompleted();
}
});
}
@Override
protected Observable<String> resumeWithFallback() {
if (isResponseTimedOut()) {
return Observable.just("timed-out");
} else {
return Observable.just("abc");
}
}
};
System.out.println(">>>>> Start: " + System.currentTimeMillis());
String value = command.observe().toBlocking().single();
System.out.println(">>>>> End: " + System.currentTimeMillis());
assertTrue(command.isResponseTimedOut());
assertEquals("expected fallback value", "timed-out", value);
// Thread isolated
assertTrue(!startedExecution.get() || command.isExecutedInThread());
assertNotNull(command.getExecutionException());
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
}
@Test
public void testSynchronousExecutionUsingThreadIsolationTimeoutValueViaObserve() {
HystrixObservableCommand.Setter properties = HystrixObservableCommand.Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("TestKey"))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withExecutionIsolationStrategy(ExecutionIsolationStrategy.THREAD)
.withExecutionTimeoutInMilliseconds(50));
final AtomicBoolean startedExecution = new AtomicBoolean();
HystrixObservableCommand<String> command = new HystrixObservableCommand<String>(properties) {
@Override
protected Observable<String> construct() {
return Observable.create(new OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> t1) {
startedExecution.set(true);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t1.onNext("hello");
t1.onCompleted();
}
});
}
@Override
protected Observable<String> resumeWithFallback() {
if (isResponseTimedOut()) {
return Observable.just("timed-out");
} else {
return Observable.just("abc");
}
}
};
String value = command.observe().toBlocking().last();
assertTrue(command.isResponseTimedOut());
assertEquals("expected fallback value", "timed-out", value);
// Thread isolated
assertTrue(!startedExecution.get() || command.isExecutedInThread());
assertNotNull(command.getExecutionException());
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
}
@Test
public void testAsyncExecutionTimeoutValueViaObserve() {
HystrixObservableCommand.Setter properties = HystrixObservableCommand.Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("TestKey"))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withExecutionTimeoutInMilliseconds(50));
HystrixObservableCommand<String> command = new HystrixObservableCommand<String>(properties) {
@Override
protected Observable<String> construct() {
return Observable.create(new OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> t1) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("********** interrupted on timeout");
e.printStackTrace();
}
// should never reach here
t1.onNext("hello");
t1.onCompleted();
}
}).subscribeOn(Schedulers.newThread());
}
@Override
protected Observable<String> resumeWithFallback() {
if (isResponseTimedOut()) {
return Observable.just("timed-out");
} else {
return Observable.just("abc");
}
}
};
String value = command.observe().toBlocking().last();
assertTrue(command.isResponseTimedOut());
assertEquals("expected fallback value", "timed-out", value);
// semaphore isolated
assertFalse(command.isExecutedInThread());
assertNotNull(command.getExecutionException());
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertEquals(1, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
}
/**
* See https://github.com/Netflix/Hystrix/issues/212
*/
@Test
public void testObservableTimeoutNoFallbackThreadContext() {
TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
final AtomicReference<Thread> onErrorThread = new AtomicReference<Thread>();
final AtomicBoolean isRequestContextInitialized = new AtomicBoolean();
TestHystrixObservableCommand<Integer> command = getCommand(ExecutionIsolationStrategy.SEMAPHORE, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 200, AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED, 100);
command.toObservable().doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable t1) {
System.out.println("onError: " + t1);
System.out.println("onError Thread: " + Thread.currentThread());
System.out.println("ThreadContext in onError: " + HystrixRequestContext.isCurrentThreadInitialized());
onErrorThread.set(Thread.currentThread());
isRequestContextInitialized.set(HystrixRequestContext.isCurrentThreadInitialized());
}
}).subscribe(ts);
ts.awaitTerminalEvent();
assertTrue(isRequestContextInitialized.get());
assertTrue(onErrorThread.get().getName().startsWith("HystrixTimer"));
List<Throwable> errors = ts.getOnErrorEvents();
assertEquals(1, errors.size());
Throwable e = errors.get(0);
if (errors.get(0) instanceof HystrixRuntimeException) {
HystrixRuntimeException de = (HystrixRuntimeException) e;
assertNotNull(de.getFallbackException());
assertTrue(de.getFallbackException() instanceof UnsupportedOperationException);
assertNotNull(de.getImplementingClass());
assertNotNull(de.getCause());
assertTrue(de.getCause() instanceof TimeoutException);
} else {
fail("the exception should be ExecutionException with cause as HystrixRuntimeException");
}
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isResponseTimedOut());
assertNotNull(command.getExecutionException());
assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
assertFalse(command.isExecutedInThread());
}
/**
* See https://github.com/Netflix/Hystrix/issues/212
*/
@Test
public void testObservableTimeoutFallbackThreadContext() {
TestSubscriber<Object> ts = new TestSubscriber<Object>();
final AtomicReference<Thread> onErrorThread = new AtomicReference<Thread>();
final AtomicBoolean isRequestContextInitialized = new AtomicBoolean();
TestHystrixObservableCommand<Integer> command = getCommand(ExecutionIsolationStrategy.SEMAPHORE, AbstractTestHystrixCommand.ExecutionResult.SUCCESS, 200, AbstractTestHystrixCommand.FallbackResult.SUCCESS, 100);
command.toObservable().doOnNext(new Action1<Object>() {
@Override
public void call(Object t1) {
System.out.println("onNext: " + t1);
System.out.println("onNext Thread: " + Thread.currentThread());
System.out.println("ThreadContext in onNext: " + HystrixRequestContext.isCurrentThreadInitialized());
onErrorThread.set(Thread.currentThread());
isRequestContextInitialized.set(HystrixRequestContext.isCurrentThreadInitialized());
}
}).subscribe(ts);
ts.awaitTerminalEvent();
System.out.println("events: " + ts.getOnNextEvents());
assertTrue(isRequestContextInitialized.get());
assertTrue(onErrorThread.get().getName().startsWith("HystrixTimer"));
List<Object> onNexts = ts.getOnNextEvents();
assertEquals(1, onNexts.size());
//assertFalse( onNexts.get(0));
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isResponseTimedOut());
assertNotNull(command.getExecutionException());
assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
assertFalse(command.isExecutedInThread());
}
@Test
public void testRejectedViaSemaphoreIsolation() {
final TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
final ArrayBlockingQueue<Boolean> results = new ArrayBlockingQueue<Boolean>(2);
final TryableSemaphoreActual semaphore = new TryableSemaphoreActual(HystrixProperty.Factory.asProperty(1));
//used to wait until all commands have started
final CountDownLatch startLatch = new CountDownLatch(2);
// used to signal that all command can finish
final CountDownLatch sharedLatch = new CountDownLatch(1);
final LatchedSemaphoreCommand command1 = new LatchedSemaphoreCommand(circuitBreaker, semaphore, startLatch, sharedLatch);
final LatchedSemaphoreCommand command2 = new LatchedSemaphoreCommand(circuitBreaker, semaphore, startLatch, sharedLatch);
Observable<Boolean> merged = Observable.merge(command1.toObservable(), command2.toObservable())
.subscribeOn(Schedulers.newThread());
final CountDownLatch terminal = new CountDownLatch(1);
merged.subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
System.out.println(Thread.currentThread().getName() + " OnCompleted");
terminal.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(Thread.currentThread().getName() + " OnError : " + e);
terminal.countDown();
}
@Override
public void onNext(Boolean b) {
System.out.println(Thread.currentThread().getName() + " OnNext : " + b);
results.offer(b);
}
});
try {
assertTrue(startLatch.await(1000, TimeUnit.MILLISECONDS));
sharedLatch.countDown();
assertTrue(terminal.await(1000, TimeUnit.MILLISECONDS));
} catch (Throwable ex) {
ex.printStackTrace();
fail(ex.getMessage());
}
// one thread should have returned values
assertEquals(2, results.size());
//1 should have gotten the normal value, the other - the fallback
assertTrue(results.contains(Boolean.TRUE));
assertTrue(results.contains(Boolean.FALSE));
System.out.println("REQ LOG : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertCommandExecutionEvents(command1, HystrixEventType.EMIT, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command2, HystrixEventType.SEMAPHORE_REJECTED, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(2);
}
@Test
public void testRejectedViaThreadIsolation() throws InterruptedException {
final TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
final ArrayBlockingQueue<Boolean> results = new ArrayBlockingQueue<Boolean>(10);
final List<Thread> executionThreads = Collections.synchronizedList(new ArrayList<Thread>(20));
final List<Thread> responseThreads = Collections.synchronizedList(new ArrayList<Thread>(10));
final AtomicBoolean exceptionReceived = new AtomicBoolean();
final CountDownLatch scheduleLatch = new CountDownLatch(2);
final CountDownLatch successLatch = new CountDownLatch(1);
final AtomicInteger count = new AtomicInteger();
final AtomicReference<TestThreadIsolationWithSemaphoreSetSmallCommand> command1Ref = new AtomicReference<TestThreadIsolationWithSemaphoreSetSmallCommand>();
final AtomicReference<TestThreadIsolationWithSemaphoreSetSmallCommand> command2Ref = new AtomicReference<TestThreadIsolationWithSemaphoreSetSmallCommand>();
final AtomicReference<TestThreadIsolationWithSemaphoreSetSmallCommand> command3Ref = new AtomicReference<TestThreadIsolationWithSemaphoreSetSmallCommand>();
Runnable r1 = new HystrixContextRunnable(HystrixPlugins.getInstance().getConcurrencyStrategy(), new Runnable() {
@Override
public void run() {
final boolean shouldExecute = count.incrementAndGet() < 3;
try {
executionThreads.add(Thread.currentThread());
TestThreadIsolationWithSemaphoreSetSmallCommand command1 = new TestThreadIsolationWithSemaphoreSetSmallCommand(circuitBreaker, 2, new Action0() {
@Override
public void call() {
// make sure it's deterministic and we put 2 threads into the pool before the 3rd is submitted
if (shouldExecute) {
try {
scheduleLatch.countDown();
successLatch.await();
} catch (InterruptedException e) {
}
}
}
});
command1Ref.set(command1);
results.add(command1.toObservable().map(new Func1<Boolean, Boolean>() {
@Override
public Boolean call(Boolean b) {
responseThreads.add(Thread.currentThread());
return b;
}
}).doAfterTerminate(new Action0() {
@Override
public void call() {
if (!shouldExecute) {
// the final thread that shouldn't execute releases the latch once it has run
// so it is deterministic that the other two fill the thread pool until this one rejects
successLatch.countDown();
}
}
}).toBlocking().single());
} catch (Exception e) {
e.printStackTrace();
exceptionReceived.set(true);
}
}
});
Runnable r2 = new HystrixContextRunnable(HystrixPlugins.getInstance().getConcurrencyStrategy(), new Runnable() {
@Override
public void run() {
final boolean shouldExecute = count.incrementAndGet() < 3;
try {
executionThreads.add(Thread.currentThread());
TestThreadIsolationWithSemaphoreSetSmallCommand command2 = new TestThreadIsolationWithSemaphoreSetSmallCommand(circuitBreaker, 2, new Action0() {
@Override
public void call() {
// make sure it's deterministic and we put 2 threads into the pool before the 3rd is submitted
if (shouldExecute) {
try {
scheduleLatch.countDown();
successLatch.await();
} catch (InterruptedException e) {
}
}
}
});
command2Ref.set(command2);
results.add(command2.toObservable().map(new Func1<Boolean, Boolean>() {
@Override
public Boolean call(Boolean b) {
responseThreads.add(Thread.currentThread());
return b;
}
}).doAfterTerminate(new Action0() {
@Override
public void call() {
if (!shouldExecute) {
// the final thread that shouldn't execute releases the latch once it has run
// so it is deterministic that the other two fill the thread pool until this one rejects
successLatch.countDown();
}
}
}).toBlocking().single());
} catch (Exception e) {
e.printStackTrace();
exceptionReceived.set(true);
}
}
});
Runnable r3 = new HystrixContextRunnable(HystrixPlugins.getInstance().getConcurrencyStrategy(), new Runnable() {
@Override
public void run() {
final boolean shouldExecute = count.incrementAndGet() < 3;
try {
executionThreads.add(Thread.currentThread());
TestThreadIsolationWithSemaphoreSetSmallCommand command3 = new TestThreadIsolationWithSemaphoreSetSmallCommand(circuitBreaker, 2, new Action0() {
@Override
public void call() {
// make sure it's deterministic and we put 2 threads into the pool before the 3rd is submitted
if (shouldExecute) {
try {
scheduleLatch.countDown();
successLatch.await();
} catch (InterruptedException e) {
}
}
}
});
command3Ref.set(command3);
results.add(command3.toObservable().map(new Func1<Boolean, Boolean>() {
@Override
public Boolean call(Boolean b) {
responseThreads.add(Thread.currentThread());
return b;
}
}).doAfterTerminate(new Action0() {
@Override
public void call() {
if (!shouldExecute) {
// the final thread that shouldn't execute releases the latch once it has run
// so it is deterministic that the other two fill the thread pool until this one rejects
successLatch.countDown();
}
}
}).toBlocking().single());
} catch (Exception e) {
e.printStackTrace();
exceptionReceived.set(true);
}
}
});
// 2 threads, the second should be rejected by the semaphore and return fallback
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
Thread t3 = new Thread(r3);
t1.start();
t2.start();
// wait for the previous 2 thread to be running before starting otherwise it can race
scheduleLatch.await(500, TimeUnit.MILLISECONDS);
t3.start();
try {
t1.join();
t2.join();
t3.join();
} catch (Exception e) {
e.printStackTrace();
fail("failed waiting on threads");
}
// we should have 2 of the 3 return results
assertEquals(2, results.size());
// the other thread should have thrown an Exception
assertTrue(exceptionReceived.get());
assertCommandExecutionEvents(command1Ref.get(), HystrixEventType.EMIT, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command2Ref.get(), HystrixEventType.EMIT, HystrixEventType.SUCCESS);
assertCommandExecutionEvents(command3Ref.get(), HystrixEventType.THREAD_POOL_REJECTED, HystrixEventType.FALLBACK_MISSING);
assertEquals(0, circuitBreaker.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(3);
}
/* ******************************************************************************************************** */
/* *************************************** Request Context Testing Below ********************************** */
/* ******************************************************************************************************** */
private RequestContextTestResults testRequestContextOnSuccess(ExecutionIsolationStrategy isolation, final Scheduler userScheduler) {
final RequestContextTestResults results = new RequestContextTestResults();
TestHystrixObservableCommand<Boolean> command = new TestHystrixObservableCommand<Boolean>(TestHystrixObservableCommand.testPropsBuilder()
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(isolation))) {
@Override
protected Observable<Boolean> construct() {
return Observable.create(new OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> s) {
results.isContextInitialized.set(HystrixRequestContext.isCurrentThreadInitialized());
results.originThread.set(Thread.currentThread());
s.onNext(true);
s.onCompleted();
}
}).subscribeOn(userScheduler);
}
};
results.command = command;
command.toObservable().doOnEach(new Action1<Notification<? super Boolean>>() {
@Override
public void call(Notification<? super Boolean> n) {
results.isContextInitializedObserveOn.set(HystrixRequestContext.isCurrentThreadInitialized());
results.observeOnThread.set(Thread.currentThread());
}
}).subscribe(results.ts);
results.ts.awaitTerminalEvent();
System.out.println("Run => Initialized: " + results.isContextInitialized.get() + " Thread: " + results.originThread.get());
System.out.println("Observed => Initialized: " + results.isContextInitializedObserveOn.get() + " Thread: " + results.observeOnThread.get());
assertEquals(1, results.ts.getOnNextEvents().size());
assertTrue(results.ts.getOnNextEvents().get(0));
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isSuccessfulExecution());
assertCommandExecutionEvents(command, HystrixEventType.EMIT, HystrixEventType.SUCCESS);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
return results;
}
private RequestContextTestResults testRequestContextOnGracefulFailure(ExecutionIsolationStrategy isolation, final Scheduler userScheduler) {
final RequestContextTestResults results = new RequestContextTestResults();
final TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
TestHystrixObservableCommand<Boolean> command = new TestHystrixObservableCommand<Boolean>(TestHystrixObservableCommand.testPropsBuilder(circuitBreaker)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(isolation))) {
@Override
protected Observable<Boolean> construct() {
return Observable.create(new OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> s) {
results.isContextInitialized.set(HystrixRequestContext.isCurrentThreadInitialized());
results.originThread.set(Thread.currentThread());
s.onError(new RuntimeException("graceful onError"));
}
}).subscribeOn(userScheduler);
}
};
results.command = command;
command.toObservable().doOnEach(new Action1<Notification<? super Boolean>>() {
@Override
public void call(Notification<? super Boolean> n) {
results.isContextInitializedObserveOn.set(HystrixRequestContext.isCurrentThreadInitialized());
results.observeOnThread.set(Thread.currentThread());
}
}).subscribe(results.ts);
results.ts.awaitTerminalEvent();
System.out.println("Run => Initialized: " + results.isContextInitialized.get() + " Thread: " + results.originThread.get());
System.out.println("Observed => Initialized: " + results.isContextInitializedObserveOn.get() + " Thread: " + results.observeOnThread.get());
assertEquals(1, results.ts.getOnErrorEvents().size());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertFalse(command.isSuccessfulExecution());
assertTrue(command.isFailedExecution());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_MISSING);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
return results;
}
private RequestContextTestResults testRequestContextOnBadFailure(ExecutionIsolationStrategy isolation, final Scheduler userScheduler) {
final RequestContextTestResults results = new RequestContextTestResults();
TestHystrixObservableCommand<Boolean> command = new TestHystrixObservableCommand<Boolean>(TestHystrixObservableCommand.testPropsBuilder(new TestCircuitBreaker())
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(isolation))) {
@Override
protected Observable<Boolean> construct() {
return Observable.create(new OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> s) {
results.isContextInitialized.set(HystrixRequestContext.isCurrentThreadInitialized());
results.originThread.set(Thread.currentThread());
throw new RuntimeException("bad onError");
}
}).subscribeOn(userScheduler);
}
};
results.command = command;
command.toObservable().doOnEach(new Action1<Notification<? super Boolean>>() {
@Override
public void call(Notification<? super Boolean> n) {
results.isContextInitializedObserveOn.set(HystrixRequestContext.isCurrentThreadInitialized());
results.observeOnThread.set(Thread.currentThread());
}
}).subscribe(results.ts);
results.ts.awaitTerminalEvent();
System.out.println("Run => Initialized: " + results.isContextInitialized.get() + " Thread: " + results.originThread.get());
System.out.println("Observed => Initialized: " + results.isContextInitializedObserveOn.get() + " Thread: " + results.observeOnThread.get());
assertEquals(1, results.ts.getOnErrorEvents().size());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertFalse(command.isSuccessfulExecution());
assertTrue(command.isFailedExecution());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_MISSING);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
return results;
}
private RequestContextTestResults testRequestContextOnFailureWithFallback(ExecutionIsolationStrategy isolation, final Scheduler userScheduler) {
final RequestContextTestResults results = new RequestContextTestResults();
TestHystrixObservableCommand<Boolean> command = new TestHystrixObservableCommand<Boolean>(TestHystrixObservableCommand.testPropsBuilder(new TestCircuitBreaker())
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(isolation))) {
@Override
protected Observable<Boolean> construct() {
return Observable.create(new OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> s) {
s.onError(new RuntimeException("onError"));
}
}).subscribeOn(userScheduler);
}
@Override
protected Observable<Boolean> resumeWithFallback() {
return Observable.create(new OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> s) {
results.isContextInitialized.set(HystrixRequestContext.isCurrentThreadInitialized());
results.originThread.set(Thread.currentThread());
s.onNext(false);
s.onCompleted();
}
}).subscribeOn(userScheduler);
}
};
results.command = command;
command.toObservable().doOnEach(new Action1<Notification<? super Boolean>>() {
@Override
public void call(Notification<? super Boolean> n) {
results.isContextInitializedObserveOn.set(HystrixRequestContext.isCurrentThreadInitialized());
results.observeOnThread.set(Thread.currentThread());
}
}).subscribe(results.ts);
results.ts.awaitTerminalEvent();
System.out.println("Run => Initialized: " + results.isContextInitialized.get() + " Thread: " + results.originThread.get());
System.out.println("Observed => Initialized: " + results.isContextInitializedObserveOn.get() + " Thread: " + results.observeOnThread.get());
assertEquals(0, results.ts.getOnErrorEvents().size());
assertEquals(1, results.ts.getOnNextEvents().size());
assertEquals(false, results.ts.getOnNextEvents().get(0));
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertFalse(command.isSuccessfulExecution());
assertTrue(command.isFailedExecution());
assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
return results;
}
private RequestContextTestResults testRequestContextOnRejectionWithFallback(ExecutionIsolationStrategy isolation, final Scheduler userScheduler) {
final RequestContextTestResults results = new RequestContextTestResults();
TestHystrixObservableCommand<Boolean> command = new TestHystrixObservableCommand<Boolean>(TestHystrixObservableCommand.testPropsBuilder(new TestCircuitBreaker())
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter()
.withExecutionIsolationStrategy(isolation)
.withExecutionIsolationSemaphoreMaxConcurrentRequests(0))
.setThreadPool(new HystrixThreadPool() {
@Override
public ThreadPoolExecutor getExecutor() {
return null;
}
@Override
public void markThreadExecution() {
}
@Override
public void markThreadCompletion() {
}
@Override
public void markThreadRejection() {
}
@Override
public boolean isQueueSpaceAvailable() {
// always return false so we reject everything
return false;
}
@Override
public Scheduler getScheduler() {
return new HystrixContextScheduler(HystrixPlugins.getInstance().getConcurrencyStrategy(), this);
}
@Override
public Scheduler getScheduler(Func0<Boolean> shouldInterruptThread) {
return new HystrixContextScheduler(HystrixPlugins.getInstance().getConcurrencyStrategy(), this, shouldInterruptThread);
}
})) {
@Override
protected Observable<Boolean> construct() {
return Observable.create(new OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> s) {
s.onError(new RuntimeException("onError"));
}
}).subscribeOn(userScheduler);
}
@Override
protected Observable<Boolean> resumeWithFallback() {
return Observable.create(new OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> s) {
results.isContextInitialized.set(HystrixRequestContext.isCurrentThreadInitialized());
results.originThread.set(Thread.currentThread());
s.onNext(false);
s.onCompleted();
}
}).subscribeOn(userScheduler);
}
};
results.command = command;
command.toObservable().doOnEach(new Action1<Notification<? super Boolean>>() {
@Override
public void call(Notification<? super Boolean> n) {
results.isContextInitializedObserveOn.set(HystrixRequestContext.isCurrentThreadInitialized());
results.observeOnThread.set(Thread.currentThread());
}
}).subscribe(results.ts);
results.ts.awaitTerminalEvent();
System.out.println("Run => Initialized: " + results.isContextInitialized.get() + " Thread: " + results.originThread.get());
System.out.println("Observed => Initialized: " + results.isContextInitializedObserveOn.get() + " Thread: " + results.observeOnThread.get());
assertEquals(0, results.ts.getOnErrorEvents().size());
assertEquals(1, results.ts.getOnNextEvents().size());
assertEquals(false, results.ts.getOnNextEvents().get(0));
assertFalse(command.isSuccessfulExecution());
assertTrue(command.isResponseRejected());
if (isolation == ExecutionIsolationStrategy.SEMAPHORE) {
assertCommandExecutionEvents(command, HystrixEventType.SEMAPHORE_REJECTED, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
} else {
assertCommandExecutionEvents(command, HystrixEventType.THREAD_POOL_REJECTED, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
}
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
return results;
}
private RequestContextTestResults testRequestContextOnShortCircuitedWithFallback(ExecutionIsolationStrategy isolation, final Scheduler userScheduler) {
final RequestContextTestResults results = new RequestContextTestResults();
TestHystrixObservableCommand<Boolean> command = new TestHystrixObservableCommand<Boolean>(TestHystrixObservableCommand.testPropsBuilder(new TestCircuitBreaker())
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter()
.withExecutionIsolationStrategy(isolation))
.setCircuitBreaker(new TestCircuitBreaker().setForceShortCircuit(true))) {
@Override
protected Observable<Boolean> construct() {
return Observable.create(new OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> s) {
s.onError(new RuntimeException("onError"));
}
}).subscribeOn(userScheduler);
}
@Override
protected Observable<Boolean> resumeWithFallback() {
return Observable.create(new OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> s) {
results.isContextInitialized.set(HystrixRequestContext.isCurrentThreadInitialized());
results.originThread.set(Thread.currentThread());
s.onNext(false);
s.onCompleted();
}
}).subscribeOn(userScheduler);
}
};
results.command = command;
command.toObservable().doOnEach(new Action1<Notification<? super Boolean>>() {
@Override
public void call(Notification<? super Boolean> n) {
results.isContextInitializedObserveOn.set(HystrixRequestContext.isCurrentThreadInitialized());
results.observeOnThread.set(Thread.currentThread());
}
}).subscribe(results.ts);
results.ts.awaitTerminalEvent();
System.out.println("Run => Initialized: " + results.isContextInitialized.get() + " Thread: " + results.originThread.get());
System.out.println("Observed => Initialized: " + results.isContextInitializedObserveOn.get() + " Thread: " + results.observeOnThread.get());
assertEquals(0, results.ts.getOnErrorEvents().size());
assertEquals(1, results.ts.getOnNextEvents().size());
assertEquals(false, results.ts.getOnNextEvents().get(0));
assertTrue(command.getExecutionTimeInMilliseconds() == -1);
assertFalse(command.isSuccessfulExecution());
assertTrue(command.isResponseShortCircuited());
assertCommandExecutionEvents(command, HystrixEventType.SHORT_CIRCUITED, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
return results;
}
private RequestContextTestResults testRequestContextOnTimeout(ExecutionIsolationStrategy isolation, final Scheduler userScheduler) {
final RequestContextTestResults results = new RequestContextTestResults();
TestHystrixObservableCommand<Boolean> command = new TestHystrixObservableCommand<Boolean>(TestHystrixObservableCommand.testPropsBuilder(new TestCircuitBreaker())
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(isolation).withExecutionTimeoutInMilliseconds(50))) {
@Override
protected Observable<Boolean> construct() {
return Observable.create(new OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> s) {
results.isContextInitialized.set(HystrixRequestContext.isCurrentThreadInitialized());
results.originThread.set(Thread.currentThread());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// ignore the interrupted exception
}
}
}).subscribeOn(userScheduler);
}
};
results.command = command;
command.toObservable().doOnEach(new Action1<Notification<? super Boolean>>() {
@Override
public void call(Notification<? super Boolean> n) {
results.isContextInitializedObserveOn.set(HystrixRequestContext.isCurrentThreadInitialized());
results.observeOnThread.set(Thread.currentThread());
}
}).subscribe(results.ts);
results.ts.awaitTerminalEvent();
System.out.println("Run => Initialized: " + results.isContextInitialized.get() + " Thread: " + results.originThread.get());
System.out.println("Observed => Initialized: " + results.isContextInitializedObserveOn.get() + " Thread: " + results.observeOnThread.get());
assertEquals(1, results.ts.getOnErrorEvents().size());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertFalse(command.isSuccessfulExecution());
assertTrue(command.isResponseTimedOut());
assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_MISSING);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
return results;
}
private RequestContextTestResults testRequestContextOnTimeoutWithFallback(ExecutionIsolationStrategy isolation, final Scheduler userScheduler) {
final RequestContextTestResults results = new RequestContextTestResults();
TestHystrixObservableCommand<Boolean> command = new TestHystrixObservableCommand<Boolean>(TestHystrixObservableCommand.testPropsBuilder(new TestCircuitBreaker())
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(isolation).withExecutionTimeoutInMilliseconds(50))) {
@Override
protected Observable<Boolean> construct() {
return Observable.create(new OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> s) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// ignore the interrupted exception
}
}
}).subscribeOn(userScheduler);
}
@Override
protected Observable<Boolean> resumeWithFallback() {
return Observable.create(new OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> s) {
results.isContextInitialized.set(HystrixRequestContext.isCurrentThreadInitialized());
results.originThread.set(Thread.currentThread());
s.onNext(false);
s.onCompleted();
}
}).subscribeOn(userScheduler);
}
};
results.command = command;
command.toObservable().doOnEach(new Action1<Notification<? super Boolean>>() {
@Override
public void call(Notification<? super Boolean> n) {
System.out.println("timeoutWithFallback notification: " + n + " " + Thread.currentThread());
results.isContextInitializedObserveOn.set(HystrixRequestContext.isCurrentThreadInitialized());
results.observeOnThread.set(Thread.currentThread());
}
}).subscribe(results.ts);
results.ts.awaitTerminalEvent();
System.out.println("Fallback => Initialized: " + results.isContextInitialized.get() + " Thread: " + results.originThread.get());
System.out.println("Observed => Initialized: " + results.isContextInitializedObserveOn.get() + " Thread: " + results.observeOnThread.get());
assertEquals(1, results.ts.getOnNextEvents().size());
assertEquals(false, results.ts.getOnNextEvents().get(0));
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertFalse(command.isSuccessfulExecution());
assertTrue(command.isResponseTimedOut());
assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
return results;
}
private final class RequestContextTestResults {
volatile TestHystrixObservableCommand<Boolean> command;
final AtomicReference<Thread> originThread = new AtomicReference<Thread>();
final AtomicBoolean isContextInitialized = new AtomicBoolean();
TestSubscriber<Boolean> ts = new TestSubscriber<Boolean>();
final AtomicBoolean isContextInitializedObserveOn = new AtomicBoolean();
final AtomicReference<Thread> observeOnThread = new AtomicReference<Thread>();
}
/* *************************************** testSuccessfulRequestContext *********************************** */
/**
* Synchronous Observable and semaphore isolation. Only [Main] thread is involved in this.
*/
@Test
public void testSuccessfulRequestContextWithSemaphoreIsolatedSynchronousObservable() {
RequestContextTestResults results = testRequestContextOnSuccess(ExecutionIsolationStrategy.SEMAPHORE, Schedulers.immediate());
assertTrue(results.isContextInitialized.get());
assertTrue(results.originThread.get().equals(Thread.currentThread())); // all synchronous
assertTrue(results.isContextInitializedObserveOn.get());
assertTrue(results.observeOnThread.get().equals(Thread.currentThread())); // all synchronous
// semaphore isolated
assertFalse(results.command.isExecutedInThread());
}
/**
* Async Observable and semaphore isolation. User provided thread [RxNewThread] does everything.
*
* NOTE: RequestContext will NOT exist on that thread.
*
* An async Observable running on its own thread will not have access to the request context unless the user manages the context.
*/
@Test
public void testSuccessfulRequestContextWithSemaphoreIsolatedAsynchronousObservable() {
RequestContextTestResults results = testRequestContextOnSuccess(ExecutionIsolationStrategy.SEMAPHORE, Schedulers.newThread());
assertFalse(results.isContextInitialized.get()); // it won't have request context as it's on a user provided thread/scheduler
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // we capture and set the context once the user provided Observable emits
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
// semaphore isolated
assertFalse(results.command.isExecutedInThread());
}
/**
* Async Observable and semaphore isolation WITH functioning RequestContext
*
* Use HystrixContextScheduler to make the user provided scheduler capture context.
*/
@Test
public void testSuccessfulRequestContextWithSemaphoreIsolatedAsynchronousObservableAndCapturedContextScheduler() {
RequestContextTestResults results = testRequestContextOnSuccess(ExecutionIsolationStrategy.SEMAPHORE, new HystrixContextScheduler(Schedulers.newThread()));
assertTrue(results.isContextInitialized.get()); // the user scheduler captures context
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // the user scheduler captures context
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
// semaphore isolated
assertFalse(results.command.isExecutedInThread());
}
/**
* Synchronous Observable and thread isolation. Work done on [hystrix-OWNER_ONE] thread and then observed on [RxComputation]
*/
@Test
public void testSuccessfulRequestContextWithThreadIsolatedSynchronousObservable() {
RequestContextTestResults results = testRequestContextOnSuccess(ExecutionIsolationStrategy.THREAD, Schedulers.immediate());
assertTrue(results.isContextInitialized.get());
assertTrue(results.originThread.get().getName().startsWith("hystrix-OWNER_ONE")); // thread isolated on a HystrixThreadPool
assertTrue(results.isContextInitializedObserveOn.get());
assertTrue(results.observeOnThread.get().getName().startsWith("hystrix-OWNER_ONE"));
// thread isolated
assertTrue(results.command.isExecutedInThread());
}
/**
* Async Observable and thread isolation. User provided thread [RxNetThread] executes Observable and then [RxComputation] observes the onNext calls.
*
* NOTE: RequestContext will NOT exist on that thread.
*
* An async Observable running on its own thread will not have access to the request context unless the user manages the context.
*/
@Test
public void testSuccessfulRequestContextWithThreadIsolatedAsynchronousObservable() {
RequestContextTestResults results = testRequestContextOnSuccess(ExecutionIsolationStrategy.THREAD, Schedulers.newThread());
assertFalse(results.isContextInitialized.get()); // it won't have request context as it's on a user provided thread/scheduler
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // we capture and set the context once the user provided Observable emits
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread"));
// thread isolated
assertTrue(results.command.isExecutedInThread());
}
/**
* Async Observable and semaphore isolation WITH functioning RequestContext
*
* Use HystrixContextScheduler to make the user provided scheduler capture context.
*/
@Test
public void testSuccessfulRequestContextWithThreadIsolatedAsynchronousObservableAndCapturedContextScheduler() {
RequestContextTestResults results = testRequestContextOnSuccess(ExecutionIsolationStrategy.THREAD, new HystrixContextScheduler(Schedulers.newThread()));
assertTrue(results.isContextInitialized.get()); // the user scheduler captures context
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // the user scheduler captures context
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread"));
// thread isolated
assertTrue(results.command.isExecutedInThread());
}
/* *************************************** testGracefulFailureRequestContext *********************************** */
/**
* Synchronous Observable and semaphore isolation. Only [Main] thread is involved in this.
*/
@Test
public void testGracefulFailureRequestContextWithSemaphoreIsolatedSynchronousObservable() {
RequestContextTestResults results = testRequestContextOnGracefulFailure(ExecutionIsolationStrategy.SEMAPHORE, Schedulers.immediate());
assertTrue(results.isContextInitialized.get());
assertTrue(results.originThread.get().equals(Thread.currentThread())); // all synchronous
assertTrue(results.isContextInitializedObserveOn.get());
assertTrue(results.observeOnThread.get().equals(Thread.currentThread())); // all synchronous
// semaphore isolated
assertFalse(results.command.isExecutedInThread());
}
/**
* Async Observable and semaphore isolation. User provided thread [RxNewThread] does everything.
*
* NOTE: RequestContext will NOT exist on that thread.
*
* An async Observable running on its own thread will not have access to the request context unless the user manages the context.
*/
@Test
public void testGracefulFailureRequestContextWithSemaphoreIsolatedAsynchronousObservable() {
RequestContextTestResults results = testRequestContextOnGracefulFailure(ExecutionIsolationStrategy.SEMAPHORE, Schedulers.newThread());
assertFalse(results.isContextInitialized.get()); // it won't have request context as it's on a user provided thread/scheduler
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // we capture and set the context once the user provided Observable emits
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
// semaphore isolated
assertFalse(results.command.isExecutedInThread());
}
/**
* Async Observable and semaphore isolation WITH functioning RequestContext
*
* Use HystrixContextScheduler to make the user provided scheduler capture context.
*/
@Test
public void testGracefulFailureRequestContextWithSemaphoreIsolatedAsynchronousObservableAndCapturedContextScheduler() {
RequestContextTestResults results = testRequestContextOnGracefulFailure(ExecutionIsolationStrategy.SEMAPHORE, new HystrixContextScheduler(Schedulers.newThread()));
assertTrue(results.isContextInitialized.get()); // the user scheduler captures context
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // the user scheduler captures context
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
// semaphore isolated
assertFalse(results.command.isExecutedInThread());
}
/**
* Synchronous Observable and thread isolation. Work done on [hystrix-OWNER_ONE] thread and then observed on [RxComputation]
*/
@Test
public void testGracefulFailureRequestContextWithThreadIsolatedSynchronousObservable() {
RequestContextTestResults results = testRequestContextOnGracefulFailure(ExecutionIsolationStrategy.THREAD, Schedulers.immediate());
assertTrue(results.isContextInitialized.get());
assertTrue(results.originThread.get().getName().startsWith("hystrix-OWNER_ONE")); // thread isolated on a HystrixThreadPool
assertTrue(results.isContextInitializedObserveOn.get());
assertTrue(results.observeOnThread.get().getName().startsWith("hystrix-OWNER_ONE"));
// thread isolated
assertTrue(results.command.isExecutedInThread());
}
/**
* Async Observable and thread isolation. User provided thread [RxNetThread] executes Observable and then [RxComputation] observes the onNext calls.
*
* NOTE: RequestContext will NOT exist on that thread.
*
* An async Observable running on its own thread will not have access to the request context unless the user manages the context.
*/
@Test
public void testGracefulFailureRequestContextWithThreadIsolatedAsynchronousObservable() {
RequestContextTestResults results = testRequestContextOnGracefulFailure(ExecutionIsolationStrategy.THREAD, Schedulers.newThread());
assertFalse(results.isContextInitialized.get()); // it won't have request context as it's on a user provided thread/scheduler
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // we capture and set the context once the user provided Observable emits
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread"));
// thread isolated
assertTrue(results.command.isExecutedInThread());
}
/**
* Async Observable and semaphore isolation WITH functioning RequestContext
*
* Use HystrixContextScheduler to make the user provided scheduler capture context.
*/
@Test
public void testGracefulFailureRequestContextWithThreadIsolatedAsynchronousObservableAndCapturedContextScheduler() {
RequestContextTestResults results = testRequestContextOnGracefulFailure(ExecutionIsolationStrategy.THREAD, new HystrixContextScheduler(Schedulers.newThread()));
assertTrue(results.isContextInitialized.get()); // the user scheduler captures context
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // the user scheduler captures context
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread"));
// thread isolated
assertTrue(results.command.isExecutedInThread());
}
/* *************************************** testBadFailureRequestContext *********************************** */
/**
* Synchronous Observable and semaphore isolation. Only [Main] thread is involved in this.
*/
@Test
public void testBadFailureRequestContextWithSemaphoreIsolatedSynchronousObservable() {
RequestContextTestResults results = testRequestContextOnBadFailure(ExecutionIsolationStrategy.SEMAPHORE, Schedulers.immediate());
assertTrue(results.isContextInitialized.get());
assertTrue(results.originThread.get().equals(Thread.currentThread())); // all synchronous
assertTrue(results.isContextInitializedObserveOn.get());
assertTrue(results.observeOnThread.get().equals(Thread.currentThread())); // all synchronous
// semaphore isolated
assertFalse(results.command.isExecutedInThread());
}
/**
* Async Observable and semaphore isolation. User provided thread [RxNewThread] does everything.
*
* NOTE: RequestContext will NOT exist on that thread.
*
* An async Observable running on its own thread will not have access to the request context unless the user manages the context.
*/
@Test
public void testBadFailureRequestContextWithSemaphoreIsolatedAsynchronousObservable() {
RequestContextTestResults results = testRequestContextOnBadFailure(ExecutionIsolationStrategy.SEMAPHORE, Schedulers.newThread());
assertFalse(results.isContextInitialized.get()); // it won't have request context as it's on a user provided thread/scheduler
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // we capture and set the context once the user provided Observable emits
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
// semaphore isolated
assertFalse(results.command.isExecutedInThread());
}
/**
* Async Observable and semaphore isolation WITH functioning RequestContext
*
* Use HystrixContextScheduler to make the user provided scheduler capture context.
*/
@Test
public void testBadFailureRequestContextWithSemaphoreIsolatedAsynchronousObservableAndCapturedContextScheduler() {
RequestContextTestResults results = testRequestContextOnBadFailure(ExecutionIsolationStrategy.SEMAPHORE, new HystrixContextScheduler(Schedulers.newThread()));
assertTrue(results.isContextInitialized.get()); // the user scheduler captures context
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // the user scheduler captures context
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
// semaphore isolated
assertFalse(results.command.isExecutedInThread());
}
/**
* Synchronous Observable and thread isolation. Work done on [hystrix-OWNER_ONE] thread and then observed on [RxComputation]
*/
@Test
public void testBadFailureRequestContextWithThreadIsolatedSynchronousObservable() {
RequestContextTestResults results = testRequestContextOnBadFailure(ExecutionIsolationStrategy.THREAD, Schedulers.immediate());
assertTrue(results.isContextInitialized.get());
assertTrue(results.originThread.get().getName().startsWith("hystrix-OWNER_ONE")); // thread isolated on a HystrixThreadPool
assertTrue(results.isContextInitializedObserveOn.get());
assertTrue(results.observeOnThread.get().getName().startsWith("hystrix-OWNER_ONE"));
// thread isolated
assertTrue(results.command.isExecutedInThread());
}
/**
* Async Observable and thread isolation. User provided thread [RxNetThread] executes Observable and then [RxComputation] observes the onNext calls.
*
* NOTE: RequestContext will NOT exist on that thread.
*
* An async Observable running on its own thread will not have access to the request context unless the user manages the context.
*/
@Test
public void testBadFailureRequestContextWithThreadIsolatedAsynchronousObservable() {
RequestContextTestResults results = testRequestContextOnBadFailure(ExecutionIsolationStrategy.THREAD, Schedulers.newThread());
assertFalse(results.isContextInitialized.get()); // it won't have request context as it's on a user provided thread/scheduler
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // we capture and set the context once the user provided Observable emits
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread"));
// thread isolated
assertTrue(results.command.isExecutedInThread());
}
/**
* Async Observable and semaphore isolation WITH functioning RequestContext
*
* Use HystrixContextScheduler to make the user provided scheduler capture context.
*/
@Test
public void testBadFailureRequestContextWithThreadIsolatedAsynchronousObservableAndCapturedContextScheduler() {
RequestContextTestResults results = testRequestContextOnBadFailure(ExecutionIsolationStrategy.THREAD, new HystrixContextScheduler(Schedulers.newThread()));
assertTrue(results.isContextInitialized.get()); // the user scheduler captures context
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // the user scheduler captures context
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread"));
// thread isolated
assertTrue(results.command.isExecutedInThread());
}
/* *************************************** testFailureWithFallbackRequestContext *********************************** */
/**
* Synchronous Observable and semaphore isolation. Only [Main] thread is involved in this.
*/
@Test
public void testFailureWithFallbackRequestContextWithSemaphoreIsolatedSynchronousObservable() {
RequestContextTestResults results = testRequestContextOnFailureWithFallback(ExecutionIsolationStrategy.SEMAPHORE, Schedulers.immediate());
assertTrue(results.isContextInitialized.get());
assertTrue(results.originThread.get().equals(Thread.currentThread())); // all synchronous
assertTrue(results.isContextInitializedObserveOn.get());
assertTrue(results.observeOnThread.get().equals(Thread.currentThread())); // all synchronous
// semaphore isolated
assertFalse(results.command.isExecutedInThread());
}
/**
* Async Observable and semaphore isolation. User provided thread [RxNewThread] does everything.
*
* NOTE: RequestContext will NOT exist on that thread.
*
* An async Observable running on its own thread will not have access to the request context unless the user manages the context.
*/
@Test
public void testFailureWithFallbackRequestContextWithSemaphoreIsolatedAsynchronousObservable() {
RequestContextTestResults results = testRequestContextOnFailureWithFallback(ExecutionIsolationStrategy.SEMAPHORE, Schedulers.newThread());
assertFalse(results.isContextInitialized.get()); // it won't have request context as it's on a user provided thread/scheduler
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // we capture and set the context once the user provided Observable emits
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
// semaphore isolated
assertFalse(results.command.isExecutedInThread());
}
/**
* Async Observable and semaphore isolation WITH functioning RequestContext
*
* Use HystrixContextScheduler to make the user provided scheduler capture context.
*/
@Test
public void testFailureWithFallbackRequestContextWithSemaphoreIsolatedAsynchronousObservableAndCapturedContextScheduler() {
RequestContextTestResults results = testRequestContextOnFailureWithFallback(ExecutionIsolationStrategy.SEMAPHORE, new HystrixContextScheduler(Schedulers.newThread()));
assertTrue(results.isContextInitialized.get()); // the user scheduler captures context
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // the user scheduler captures context
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
// semaphore isolated
assertFalse(results.command.isExecutedInThread());
}
/**
* Synchronous Observable and thread isolation. Work done on [hystrix-OWNER_ONE] thread and then observed on [RxComputation]
*/
@Test
public void testFailureWithFallbackRequestContextWithThreadIsolatedSynchronousObservable() {
RequestContextTestResults results = testRequestContextOnFailureWithFallback(ExecutionIsolationStrategy.THREAD, Schedulers.immediate());
assertTrue(results.isContextInitialized.get());
assertTrue(results.originThread.get().getName().startsWith("hystrix-OWNER_ONE")); // thread isolated on a HystrixThreadPool
assertTrue(results.isContextInitializedObserveOn.get());
assertTrue(results.observeOnThread.get().getName().startsWith("hystrix-OWNER_ONE"));
// thread isolated
assertTrue(results.command.isExecutedInThread());
}
/**
* Async Observable and thread isolation. User provided thread [RxNetThread] executes Observable and then [RxComputation] observes the onNext calls.
*
* NOTE: RequestContext will NOT exist on that thread.
*
* An async Observable running on its own thread will not have access to the request context unless the user manages the context.
*/
@Test
public void testFailureWithFallbackRequestContextWithThreadIsolatedAsynchronousObservable() {
RequestContextTestResults results = testRequestContextOnFailureWithFallback(ExecutionIsolationStrategy.THREAD, Schedulers.newThread());
assertFalse(results.isContextInitialized.get()); // it won't have request context as it's on a user provided thread/scheduler
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // we capture and set the context once the user provided Observable emits
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread"));
// thread isolated
assertTrue(results.command.isExecutedInThread());
}
/**
* Async Observable and semaphore isolation WITH functioning RequestContext
*
* Use HystrixContextScheduler to make the user provided scheduler capture context.
*/
@Test
public void testFailureWithFallbackRequestContextWithThreadIsolatedAsynchronousObservableAndCapturedContextScheduler() {
RequestContextTestResults results = testRequestContextOnFailureWithFallback(ExecutionIsolationStrategy.THREAD, new HystrixContextScheduler(Schedulers.newThread()));
assertTrue(results.isContextInitialized.get()); // the user scheduler captures context
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // the user scheduler captures context
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread"));
// thread isolated
assertTrue(results.command.isExecutedInThread());
}
/* *************************************** testRejectionWithFallbackRequestContext *********************************** */
/**
* Synchronous Observable and semaphore isolation. Only [Main] thread is involved in this.
*/
@Test
public void testRejectionWithFallbackRequestContextWithSemaphoreIsolatedSynchronousObservable() {
RequestContextTestResults results = testRequestContextOnRejectionWithFallback(ExecutionIsolationStrategy.SEMAPHORE, Schedulers.immediate());
assertTrue(results.isContextInitialized.get());
assertTrue(results.originThread.get().equals(Thread.currentThread())); // all synchronous
assertTrue(results.isContextInitializedObserveOn.get());
assertTrue(results.observeOnThread.get().equals(Thread.currentThread())); // all synchronous
// semaphore isolated
assertFalse(results.command.isExecutedInThread());
}
/**
* Async Observable and semaphore isolation. User provided thread [RxNewThread] does everything.
*
* NOTE: RequestContext will NOT exist on that thread.
*
* An async Observable running on its own thread will not have access to the request context unless the user manages the context.
*/
@Test
public void testRejectionWithFallbackRequestContextWithSemaphoreIsolatedAsynchronousObservable() {
RequestContextTestResults results = testRequestContextOnRejectionWithFallback(ExecutionIsolationStrategy.SEMAPHORE, Schedulers.newThread());
assertFalse(results.isContextInitialized.get()); // it won't have request context as it's on a user provided thread/scheduler
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // we capture and set the context once the user provided Observable emits
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
// semaphore isolated
assertFalse(results.command.isExecutedInThread());
}
/**
* Async Observable and semaphore isolation WITH functioning RequestContext
*
* Use HystrixContextScheduler to make the user provided scheduler capture context.
*/
@Test
public void testRejectionWithFallbackRequestContextWithSemaphoreIsolatedAsynchronousObservableAndCapturedContextScheduler() {
RequestContextTestResults results = testRequestContextOnRejectionWithFallback(ExecutionIsolationStrategy.SEMAPHORE, new HystrixContextScheduler(Schedulers.newThread()));
assertTrue(results.isContextInitialized.get()); // the user scheduler captures context
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // the user scheduler captures context
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
// semaphore isolated
assertFalse(results.command.isExecutedInThread());
}
/**
* Synchronous Observable and thread isolation. Work done on [hystrix-OWNER_ONE] thread and then observed on [RxComputation]
*/
@Test
public void testRejectionWithFallbackRequestContextWithThreadIsolatedSynchronousObservable() {
RequestContextTestResults results = testRequestContextOnRejectionWithFallback(ExecutionIsolationStrategy.THREAD, Schedulers.immediate());
assertTrue(results.isContextInitialized.get());
assertTrue(results.originThread.get().equals(Thread.currentThread())); // fallback is performed by the calling thread
assertTrue(results.isContextInitializedObserveOn.get());
System.out.println("results.observeOnThread.get(): " + results.observeOnThread.get() + " " + Thread.currentThread());
assertTrue(results.observeOnThread.get().equals(Thread.currentThread())); // rejected so we stay on calling thread
// thread isolated, but rejected, so this is false
assertFalse(results.command.isExecutedInThread());
}
/**
* Async Observable and thread isolation. User provided thread [RxNetThread] executes Observable and then [RxComputation] observes the onNext calls.
*
* NOTE: RequestContext will NOT exist on that thread.
*
* An async Observable running on its own thread will not have access to the request context unless the user manages the context.
*/
@Test
public void testRejectionWithFallbackRequestContextWithThreadIsolatedAsynchronousObservable() {
RequestContextTestResults results = testRequestContextOnRejectionWithFallback(ExecutionIsolationStrategy.THREAD, Schedulers.newThread());
assertFalse(results.isContextInitialized.get()); // it won't have request context as it's on a user provided thread/scheduler
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // we capture and set the context once the user provided Observable emits
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread"));
// thread isolated, but rejected, so this is false
assertFalse(results.command.isExecutedInThread());
}
/**
* Async Observable and semaphore isolation WITH functioning RequestContext
*
* Use HystrixContextScheduler to make the user provided scheduler capture context.
*/
@Test
public void testRejectionWithFallbackRequestContextWithThreadIsolatedAsynchronousObservableAndCapturedContextScheduler() {
RequestContextTestResults results = testRequestContextOnRejectionWithFallback(ExecutionIsolationStrategy.THREAD, new HystrixContextScheduler(Schedulers.newThread()));
assertTrue(results.isContextInitialized.get()); // the user scheduler captures context
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // the user scheduler captures context
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler for getFallback
// thread isolated, but rejected, so this is false
assertFalse(results.command.isExecutedInThread());
}
/* *************************************** testShortCircuitedWithFallbackRequestContext *********************************** */
/**
* Synchronous Observable and semaphore isolation. Only [Main] thread is involved in this.
*/
@Test
public void testShortCircuitedWithFallbackRequestContextWithSemaphoreIsolatedSynchronousObservable() {
RequestContextTestResults results = testRequestContextOnShortCircuitedWithFallback(ExecutionIsolationStrategy.SEMAPHORE, Schedulers.immediate());
assertTrue(results.isContextInitialized.get());
assertTrue(results.originThread.get().equals(Thread.currentThread())); // all synchronous
assertTrue(results.isContextInitializedObserveOn.get());
assertTrue(results.observeOnThread.get().equals(Thread.currentThread())); // all synchronous
// semaphore isolated
assertFalse(results.command.isExecutedInThread());
}
/**
* Async Observable and semaphore isolation. User provided thread [RxNewThread] does everything.
*
* NOTE: RequestContext will NOT exist on that thread.
*
* An async Observable running on its own thread will not have access to the request context unless the user manages the context.
*/
@Test
public void testShortCircuitedWithFallbackRequestContextWithSemaphoreIsolatedAsynchronousObservable() {
RequestContextTestResults results = testRequestContextOnShortCircuitedWithFallback(ExecutionIsolationStrategy.SEMAPHORE, Schedulers.newThread());
assertFalse(results.isContextInitialized.get()); // it won't have request context as it's on a user provided thread/scheduler
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // we capture and set the context once the user provided Observable emits
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
// semaphore isolated
assertFalse(results.command.isExecutedInThread());
}
/**
* Async Observable and semaphore isolation WITH functioning RequestContext
*
* Use HystrixContextScheduler to make the user provided scheduler capture context.
*/
@Test
public void testShortCircuitedWithFallbackRequestContextWithSemaphoreIsolatedAsynchronousObservableAndCapturedContextScheduler() {
RequestContextTestResults results = testRequestContextOnShortCircuitedWithFallback(ExecutionIsolationStrategy.SEMAPHORE, new HystrixContextScheduler(Schedulers.newThread()));
assertTrue(results.isContextInitialized.get()); // the user scheduler captures context
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // the user scheduler captures context
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
// semaphore isolated
assertFalse(results.command.isExecutedInThread());
}
/**
* Synchronous Observable and thread isolation. Work done on [hystrix-OWNER_ONE] thread and then observed on [RxComputation]
*/
@Test
public void testShortCircuitedWithFallbackRequestContextWithThreadIsolatedSynchronousObservable() {
RequestContextTestResults results = testRequestContextOnShortCircuitedWithFallback(ExecutionIsolationStrategy.THREAD, Schedulers.immediate());
assertTrue(results.isContextInitialized.get());
assertTrue(results.originThread.get().equals(Thread.currentThread())); // fallback is performed by the calling thread
assertTrue(results.isContextInitializedObserveOn.get());
assertTrue(results.observeOnThread.get().equals(Thread.currentThread())); // rejected so we stay on calling thread
// thread isolated ... but rejected so not executed in a thread
assertFalse(results.command.isExecutedInThread());
}
/**
* Async Observable and thread isolation. User provided thread [RxNetThread] executes Observable and then [RxComputation] observes the onNext calls.
*
* NOTE: RequestContext will NOT exist on that thread.
*
* An async Observable running on its own thread will not have access to the request context unless the user manages the context.
*/
@Test
public void testShortCircuitedWithFallbackRequestContextWithThreadIsolatedAsynchronousObservable() {
RequestContextTestResults results = testRequestContextOnShortCircuitedWithFallback(ExecutionIsolationStrategy.THREAD, Schedulers.newThread());
assertFalse(results.isContextInitialized.get()); // it won't have request context as it's on a user provided thread/scheduler
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // we capture and set the context once the user provided Observable emits
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler from getFallback
// thread isolated ... but rejected so not executed in a thread
assertFalse(results.command.isExecutedInThread());
}
/**
* Async Observable and semaphore isolation WITH functioning RequestContext
*
* Use HystrixContextScheduler to make the user provided scheduler capture context.
*/
@Test
public void testShortCircuitedWithFallbackRequestContextWithThreadIsolatedAsynchronousObservableAndCapturedContextScheduler() {
RequestContextTestResults results = testRequestContextOnShortCircuitedWithFallback(ExecutionIsolationStrategy.THREAD, new HystrixContextScheduler(Schedulers.newThread()));
assertTrue(results.isContextInitialized.get()); // the user scheduler captures context
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // the user scheduler captures context
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler from getFallback
// thread isolated ... but rejected so not executed in a thread
assertFalse(results.command.isExecutedInThread());
}
/* *************************************** testTimeoutRequestContext *********************************** */
/**
* Synchronous Observable and semaphore isolation. Only [Main] thread is involved in this.
*/
@Test
public void testTimeoutRequestContextWithSemaphoreIsolatedSynchronousObservable() {
RequestContextTestResults results = testRequestContextOnTimeout(ExecutionIsolationStrategy.SEMAPHORE, Schedulers.immediate());
assertTrue(results.isContextInitialized.get());
assertTrue(results.originThread.get().equals(Thread.currentThread())); // all synchronous
assertTrue(results.isContextInitializedObserveOn.get());
assertTrue(results.observeOnThread.get().getName().startsWith("HystrixTimer")); // timeout schedules on HystrixTimer since the original thread was timed out
// semaphore isolated
assertFalse(results.command.isExecutedInThread());
HystrixCircuitBreaker.Factory.reset();
}
/**
* Async Observable and semaphore isolation. User provided thread [RxNewThread] does everything.
*
* NOTE: RequestContext will NOT exist on that thread.
*
* An async Observable running on its own thread will not have access to the request context unless the user manages the context.
*/
@Test
public void testTimeoutRequestContextWithSemaphoreIsolatedAsynchronousObservable() {
RequestContextTestResults results = testRequestContextOnTimeout(ExecutionIsolationStrategy.SEMAPHORE, Schedulers.newThread());
assertFalse(results.isContextInitialized.get()); // it won't have request context as it's on a user provided thread/scheduler
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // the timeout captures the context so it exists
assertTrue(results.observeOnThread.get().getName().startsWith("HystrixTimer")); // timeout schedules on HystrixTimer since the original thread was timed out
// semaphore isolated
assertFalse(results.command.isExecutedInThread());
HystrixCircuitBreaker.Factory.reset();
}
/**
* Async Observable and semaphore isolation WITH functioning RequestContext
*
* Use HystrixContextScheduler to make the user provided scheduler capture context.
*/
@Test
public void testTimeoutRequestContextWithSemaphoreIsolatedAsynchronousObservableAndCapturedContextScheduler() {
RequestContextTestResults results = testRequestContextOnTimeout(ExecutionIsolationStrategy.SEMAPHORE, new HystrixContextScheduler(Schedulers.newThread()));
assertTrue(results.isContextInitialized.get()); // the user scheduler captures context
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // the user scheduler captures context
assertTrue(results.observeOnThread.get().getName().startsWith("HystrixTimer")); // timeout schedules on HystrixTimer since the original thread was timed out
// semaphore isolated
assertFalse(results.command.isExecutedInThread());
HystrixCircuitBreaker.Factory.reset();
}
/* *************************************** testTimeoutWithFallbackRequestContext *********************************** */
/**
* Synchronous Observable and semaphore isolation.
*/
@Test
public void testTimeoutWithFallbackRequestContextWithSemaphoreIsolatedSynchronousObservable() {
RequestContextTestResults results = testRequestContextOnTimeoutWithFallback(ExecutionIsolationStrategy.SEMAPHORE, Schedulers.immediate());
assertTrue(results.isContextInitialized.get());
assertTrue(results.originThread.get().getName().startsWith("HystrixTimer")); // timeout uses HystrixTimer thread
//(this use case is a little odd as it should generally not be the case that we are "timing out" a synchronous observable on semaphore isolation)
assertTrue(results.isContextInitializedObserveOn.get());
assertTrue(results.observeOnThread.get().getName().startsWith("HystrixTimer")); // timeout uses HystrixTimer thread
// semaphore isolated
assertFalse(results.command.isExecutedInThread());
HystrixCircuitBreaker.Factory.reset();
}
/**
* Async Observable and semaphore isolation. User provided thread [RxNewThread] does everything.
*
* NOTE: RequestContext will NOT exist on that thread.
*
* An async Observable running on its own thread will not have access to the request context unless the user manages the context.
*/
@Test
public void testTimeoutWithFallbackRequestContextWithSemaphoreIsolatedAsynchronousObservable() {
RequestContextTestResults results = testRequestContextOnTimeoutWithFallback(ExecutionIsolationStrategy.SEMAPHORE, Schedulers.newThread());
assertFalse(results.isContextInitialized.get()); // it won't have request context as it's on a user provided thread/scheduler
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // the timeout captures the context so it exists
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
// semaphore isolated
assertFalse(results.command.isExecutedInThread());
HystrixCircuitBreaker.Factory.reset();
}
/**
* Async Observable and semaphore isolation WITH functioning RequestContext
*
* Use HystrixContextScheduler to make the user provided scheduler capture context.
*/
@Test
public void testTimeoutWithFallbackRequestContextWithSemaphoreIsolatedAsynchronousObservableAndCapturedContextScheduler() {
RequestContextTestResults results = testRequestContextOnTimeoutWithFallback(ExecutionIsolationStrategy.SEMAPHORE, new HystrixContextScheduler(Schedulers.newThread()));
assertTrue(results.isContextInitialized.get()); // the user scheduler captures context
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // the user scheduler captures context
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
// semaphore isolated
assertFalse(results.command.isExecutedInThread());
HystrixCircuitBreaker.Factory.reset();
}
/**
* Synchronous Observable and thread isolation. Work done on [hystrix-OWNER_ONE] thread and then observed on [HystrixTimer]
*/
@Test
public void testTimeoutWithFallbackRequestContextWithThreadIsolatedSynchronousObservable() {
RequestContextTestResults results = testRequestContextOnTimeoutWithFallback(ExecutionIsolationStrategy.THREAD, Schedulers.immediate());
assertTrue(results.isContextInitialized.get());
assertTrue(results.originThread.get().getName().startsWith("HystrixTimer")); // timeout uses HystrixTimer thread for fallback
assertTrue(results.isContextInitializedObserveOn.get());
assertTrue(results.observeOnThread.get().getName().startsWith("HystrixTimer")); // fallback uses the timeout thread
// thread isolated
assertTrue(results.command.isExecutedInThread());
HystrixCircuitBreaker.Factory.reset();
}
/**
* Async Observable and thread isolation. User provided thread [RxNetThread] executes Observable and then [RxComputation] observes the onNext calls.
*
* NOTE: RequestContext will NOT exist on that thread.
*
* An async Observable running on its own thread will not have access to the request context unless the user manages the context.
*/
@Test
public void testTimeoutWithFallbackRequestContextWithThreadIsolatedAsynchronousObservable() {
RequestContextTestResults results = testRequestContextOnTimeoutWithFallback(ExecutionIsolationStrategy.THREAD, Schedulers.newThread());
assertFalse(results.isContextInitialized.get()); // it won't have request context as it's on a user provided thread/scheduler
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // the timeout captures the context so it exists
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
// thread isolated
assertTrue(results.command.isExecutedInThread());
HystrixCircuitBreaker.Factory.reset();
}
/**
* Async Observable and semaphore isolation WITH functioning RequestContext
*
* Use HystrixContextScheduler to make the user provided scheduler capture context.
*/
@Test
public void testTimeoutWithFallbackRequestContextWithThreadIsolatedAsynchronousObservableAndCapturedContextScheduler() {
RequestContextTestResults results = testRequestContextOnTimeoutWithFallback(ExecutionIsolationStrategy.THREAD, new HystrixContextScheduler(Schedulers.newThread()));
assertTrue(results.isContextInitialized.get()); // the user scheduler captures context
assertTrue(results.originThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
assertTrue(results.isContextInitializedObserveOn.get()); // the user scheduler captures context
assertTrue(results.observeOnThread.get().getName().startsWith("RxNewThread")); // the user provided thread/scheduler
// thread isolated
assertTrue(results.command.isExecutedInThread());
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
}
//HystrixCircuitBreaker.Factory.reset();
}
/**
* Test support of multiple onNext events.
*/
@Test
public void testExecutionSuccessWithMultipleEvents() {
try {
TestCommandWithMultipleValues command = new TestCommandWithMultipleValues();
assertEquals(Arrays.asList(true, false, true), command.observe().toList().toBlocking().single());
assertEquals(null, command.getFailedExecutionException());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertTrue(command.isSuccessfulExecution());
assertCommandExecutionEvents(command, HystrixEventType.EMIT, HystrixEventType.EMIT, HystrixEventType.EMIT, HystrixEventType.SUCCESS);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
// semaphore isolated
assertFalse(command.isExecutedInThread());
} catch (Exception e) {
e.printStackTrace();
fail("We received an exception.");
}
}
/**
* Test behavior when some onNext are received and then a failure.
*/
@Test
public void testExecutionPartialSuccess() {
try {
TestPartialSuccess command = new TestPartialSuccess();
TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
command.toObservable().subscribe(ts);
ts.awaitTerminalEvent();
ts.assertReceivedOnNext(Arrays.asList(1, 2, 3));
assertEquals(1, ts.getOnErrorEvents().size());
assertFalse(command.isSuccessfulExecution());
assertTrue(command.isFailedExecution());
// we will have an exception
assertNotNull(command.getFailedExecutionException());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertCommandExecutionEvents(command, HystrixEventType.EMIT, HystrixEventType.EMIT, HystrixEventType.EMIT, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_MISSING);
assertSaneHystrixRequestLog(1);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
// semaphore isolated
assertFalse(command.isExecutedInThread());
} catch (Exception e) {
e.printStackTrace();
fail("We received an exception.");
}
}
/**
* Test behavior when some onNext are received and then a failure.
*/
@Test
public void testExecutionPartialSuccessWithFallback() {
try {
TestPartialSuccessWithFallback command = new TestPartialSuccessWithFallback();
TestSubscriber<Boolean> ts = new TestSubscriber<Boolean>();
command.toObservable().subscribe(ts);
ts.awaitTerminalEvent();
ts.assertReceivedOnNext(Arrays.asList(false, true, false, true, false, true, false));
ts.assertNoErrors();
assertFalse(command.isSuccessfulExecution());
assertTrue(command.isFailedExecution());
assertNotNull(command.getFailedExecutionException());
assertTrue(command.getExecutionTimeInMilliseconds() > -1);
assertCommandExecutionEvents(command, HystrixEventType.EMIT, HystrixEventType.EMIT, HystrixEventType.EMIT, HystrixEventType.FAILURE,
HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
assertSaneHystrixRequestLog(1);
// semaphore isolated
assertFalse(command.isExecutedInThread());
} catch (Exception e) {
e.printStackTrace();
fail("We received an exception.");
}
}
@Test
public void testEarlyUnsubscribeDuringExecutionViaToObservable() {
class AsyncCommand extends HystrixObservableCommand<Boolean> {
public AsyncCommand() {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ASYNC")));
}
@Override
protected Observable<Boolean> construct() {
return Observable.defer(new Func0<Observable<Boolean>>() {
@Override
public Observable<Boolean> call() {
try {
Thread.sleep(100);
return Observable.just(true);
} catch (InterruptedException ex) {
return Observable.error(ex);
}
}
}).subscribeOn(Schedulers.io());
}
}
HystrixObservableCommand<Boolean> cmd = new AsyncCommand();
final CountDownLatch latch = new CountDownLatch(1);
Observable<Boolean> o = cmd.toObservable();
Subscription s = o.
doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println("OnUnsubscribe");
latch.countDown();
}
}).
subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
System.out.println("OnCompleted");
latch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println("OnError : " + e);
}
@Override
public void onNext(Boolean b) {
System.out.println("OnNext : " + b);
}
});
try {
s.unsubscribe();
assertTrue(latch.await(200, TimeUnit.MILLISECONDS));
assertEquals("Number of execution semaphores in use", 0, cmd.getExecutionSemaphore().getNumberOfPermitsUsed());
assertEquals("Number of fallback semaphores in use", 0, cmd.getFallbackSemaphore().getNumberOfPermitsUsed());
assertFalse(cmd.isExecutionComplete());
assertFalse(cmd.isExecutedInThread());
System.out.println("EventCounts : " + cmd.getEventCounts());
System.out.println("Execution Time : " + cmd.getExecutionTimeInMilliseconds());
System.out.println("Is Successful : " + cmd.isSuccessfulExecution());
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
@Test
public void testEarlyUnsubscribeDuringExecutionViaObserve() {
class AsyncCommand extends HystrixObservableCommand<Boolean> {
public AsyncCommand() {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ASYNC")));
}
@Override
protected Observable<Boolean> construct() {
return Observable.defer(new Func0<Observable<Boolean>>() {
@Override
public Observable<Boolean> call() {
try {
Thread.sleep(100);
return Observable.just(true);
} catch (InterruptedException ex) {
return Observable.error(ex);
}
}
}).subscribeOn(Schedulers.io());
}
}
HystrixObservableCommand<Boolean> cmd = new AsyncCommand();
final CountDownLatch latch = new CountDownLatch(1);
Observable<Boolean> o = cmd.observe();
Subscription s = o.
doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println("OnUnsubscribe");
latch.countDown();
}
}).
subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
System.out.println("OnCompleted");
latch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println("OnError : " + e);
}
@Override
public void onNext(Boolean b) {
System.out.println("OnNext : " + b);
}
});
try {
s.unsubscribe();
assertTrue(latch.await(200, TimeUnit.MILLISECONDS));
assertEquals("Number of execution semaphores in use", 0, cmd.getExecutionSemaphore().getNumberOfPermitsUsed());
assertEquals("Number of fallback semaphores in use", 0, cmd.getFallbackSemaphore().getNumberOfPermitsUsed());
assertFalse(cmd.isExecutionComplete());
assertFalse(cmd.isExecutedInThread());
System.out.println("EventCounts : " + cmd.getEventCounts());
System.out.println("Execution Time : " + cmd.getExecutionTimeInMilliseconds());
System.out.println("Is Successful : " + cmd.isSuccessfulExecution());
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
@Test
public void testEarlyUnsubscribeDuringFallback() {
class AsyncCommand extends HystrixObservableCommand<Boolean> {
public AsyncCommand() {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ASYNC")));
}
@Override
protected Observable<Boolean> construct() {
return Observable.error(new RuntimeException("construct failure"));
}
@Override
protected Observable<Boolean> resumeWithFallback() {
return Observable.defer(new Func0<Observable<Boolean>>() {
@Override
public Observable<Boolean> call() {
try {
Thread.sleep(100);
return Observable.just(false);
} catch (InterruptedException ex) {
return Observable.error(ex);
}
}
}).subscribeOn(Schedulers.io());
}
}
HystrixObservableCommand<Boolean> cmd = new AsyncCommand();
final CountDownLatch latch = new CountDownLatch(1);
Observable<Boolean> o = cmd.toObservable();
Subscription s = o.
doOnUnsubscribe(new Action0() {
@Override
public void call() {
System.out.println("OnUnsubscribe");
latch.countDown();
}
}).
subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
System.out.println("OnCompleted");
latch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println("OnError : " + e);
}
@Override
public void onNext(Boolean b) {
System.out.println("OnNext : " + b);
}
});
try {
Thread.sleep(10); //give fallback a chance to fire
s.unsubscribe();
assertTrue(latch.await(200, TimeUnit.MILLISECONDS));
assertEquals("Number of execution semaphores in use", 0, cmd.getExecutionSemaphore().getNumberOfPermitsUsed());
assertEquals("Number of fallback semaphores in use", 0, cmd.getFallbackSemaphore().getNumberOfPermitsUsed());
assertFalse(cmd.isExecutionComplete());
assertFalse(cmd.isExecutedInThread());
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
/* ******************************************************************************** */
/* ******************************************************************************** */
/* private HystrixCommand class implementations for unit testing */
/* ******************************************************************************** */
/* ******************************************************************************** */
static AtomicInteger uniqueNameCounter = new AtomicInteger(0);
@Override
TestHystrixObservableCommand<Integer> getCommand(ExecutionIsolationStrategy isolationStrategy, AbstractTestHystrixCommand.ExecutionResult executionResult, int executionLatency, AbstractTestHystrixCommand.FallbackResult fallbackResult, int fallbackLatency, TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int timeout, AbstractTestHystrixCommand.CacheEnabled cacheEnabled, Object value, AbstractCommand.TryableSemaphore executionSemaphore, AbstractCommand.TryableSemaphore fallbackSemaphore, boolean circuitBreakerDisabled) {
HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey("FlexibleObservable-" + uniqueNameCounter.getAndIncrement());
return FlexibleTestHystrixObservableCommand.from(commandKey, isolationStrategy, executionResult, executionLatency, fallbackResult, fallbackLatency, circuitBreaker, threadPool, timeout, cacheEnabled, value, executionSemaphore, fallbackSemaphore, circuitBreakerDisabled);
}
@Override
TestHystrixObservableCommand<Integer> getCommand(HystrixCommandKey commandKey, ExecutionIsolationStrategy isolationStrategy, AbstractTestHystrixCommand.ExecutionResult executionResult, int executionLatency, AbstractTestHystrixCommand.FallbackResult fallbackResult, int fallbackLatency, TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int timeout, AbstractTestHystrixCommand.CacheEnabled cacheEnabled, Object value, AbstractCommand.TryableSemaphore executionSemaphore, AbstractCommand.TryableSemaphore fallbackSemaphore, boolean circuitBreakerDisabled) {
return FlexibleTestHystrixObservableCommand.from(commandKey, isolationStrategy, executionResult, executionLatency, fallbackResult, fallbackLatency, circuitBreaker, threadPool, timeout, cacheEnabled, value, executionSemaphore, fallbackSemaphore, circuitBreakerDisabled);
}
private static class FlexibleTestHystrixObservableCommand {
public static Integer EXECUTE_VALUE = 1;
public static Integer FALLBACK_VALUE = 11;
public static AbstractFlexibleTestHystrixObservableCommand from(HystrixCommandKey commandKey, ExecutionIsolationStrategy isolationStrategy, AbstractTestHystrixCommand.ExecutionResult executionResult, int executionLatency, AbstractTestHystrixCommand.FallbackResult fallbackResult, int fallbackLatency, TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int timeout, AbstractTestHystrixCommand.CacheEnabled cacheEnabled, Object value, AbstractCommand.TryableSemaphore executionSemaphore, AbstractCommand.TryableSemaphore fallbackSemaphore, boolean circuitBreakerDisabled) {
if (fallbackResult.equals(AbstractTestHystrixCommand.FallbackResult.UNIMPLEMENTED)) {
return new FlexibleTestHystrixObservableCommandNoFallback(commandKey, isolationStrategy, executionResult, executionLatency, circuitBreaker, threadPool, timeout, cacheEnabled, value, executionSemaphore, fallbackSemaphore, circuitBreakerDisabled);
} else {
return new FlexibleTestHystrixObservableCommandWithFallback(commandKey, isolationStrategy, executionResult, executionLatency, fallbackResult, fallbackLatency, circuitBreaker, threadPool, timeout, cacheEnabled, value, executionSemaphore, fallbackSemaphore, circuitBreakerDisabled);
}
}
}
private static class AbstractFlexibleTestHystrixObservableCommand extends TestHystrixObservableCommand<Integer> {
private final AbstractTestHystrixCommand.ExecutionResult executionResult;
private final int executionLatency;
private final CacheEnabled cacheEnabled;
private final Object value;
public AbstractFlexibleTestHystrixObservableCommand(HystrixCommandKey commandKey, ExecutionIsolationStrategy isolationStrategy, AbstractTestHystrixCommand.ExecutionResult executionResult, int executionLatency, TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int timeout, CacheEnabled cacheEnabled, Object value, TryableSemaphore executionSemaphore, TryableSemaphore fallbackSemaphore, boolean circuitBreakerDisabled) {
super(testPropsBuilder(circuitBreaker)
.setCommandKey(commandKey)
.setCircuitBreaker(circuitBreaker)
.setMetrics(circuitBreaker.metrics)
.setThreadPool(threadPool)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter()
.withExecutionIsolationStrategy(isolationStrategy)
.withExecutionTimeoutInMilliseconds(timeout)
.withCircuitBreakerEnabled(!circuitBreakerDisabled))
.setExecutionSemaphore(executionSemaphore)
.setFallbackSemaphore(fallbackSemaphore));
this.executionResult = executionResult;
this.executionLatency = executionLatency;
this.cacheEnabled = cacheEnabled;
this.value = value;
}
@Override
protected Observable<Integer> construct() {
if (executionResult == AbstractTestHystrixCommand.ExecutionResult.FAILURE) {
addLatency(executionLatency);
throw new RuntimeException("Execution Sync Failure for TestHystrixObservableCommand");
} else if (executionResult == AbstractTestHystrixCommand.ExecutionResult.HYSTRIX_FAILURE) {
addLatency(executionLatency);
throw new HystrixRuntimeException(HystrixRuntimeException.FailureType.COMMAND_EXCEPTION, AbstractFlexibleTestHystrixObservableCommand.class, "Execution Hystrix Failure for TestHystrixObservableCommand", new RuntimeException("Execution Failure for TestHystrixObservableCommand"), new RuntimeException("Fallback Failure for TestHystrixObservableCommand"));
} else if (executionResult == AbstractTestHystrixCommand.ExecutionResult.NOT_WRAPPED_FAILURE) {
addLatency(executionLatency);
throw new NotWrappedByHystrixTestRuntimeException();
} else if (executionResult == AbstractTestHystrixCommand.ExecutionResult.RECOVERABLE_ERROR) {
addLatency(executionLatency);
throw new java.lang.Error("Execution Sync Error for TestHystrixObservableCommand");
} else if (executionResult == AbstractTestHystrixCommand.ExecutionResult.UNRECOVERABLE_ERROR) {
addLatency(executionLatency);
throw new OutOfMemoryError("Execution Sync OOME for TestHystrixObservableCommand");
} else if (executionResult == AbstractTestHystrixCommand.ExecutionResult.BAD_REQUEST) {
addLatency(executionLatency);
throw new HystrixBadRequestException("Execution Bad Request Exception for TestHystrixObservableCommand");
}
return Observable.create(new OnSubscribe<Integer>() {
@Override
public void call(Subscriber<? super Integer> subscriber) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " construct() method has been subscribed to");
addLatency(executionLatency);
if (executionResult == AbstractTestHystrixCommand.ExecutionResult.SUCCESS) {
subscriber.onNext(1);
subscriber.onCompleted();
} else if (executionResult == AbstractTestHystrixCommand.ExecutionResult.MULTIPLE_EMITS_THEN_SUCCESS) {
subscriber.onNext(2);
subscriber.onNext(3);
subscriber.onNext(4);
subscriber.onNext(5);
subscriber.onCompleted();
} else if (executionResult == AbstractTestHystrixCommand.ExecutionResult.MULTIPLE_EMITS_THEN_FAILURE) {
subscriber.onNext(6);
subscriber.onNext(7);
subscriber.onNext(8);
subscriber.onNext(9);
subscriber.onError(new RuntimeException("Execution Async Failure For TestHystrixObservableCommand after 4 emits"));
} else if (executionResult == AbstractTestHystrixCommand.ExecutionResult.ASYNC_FAILURE) {
subscriber.onError(new RuntimeException("Execution Async Failure for TestHystrixObservableCommand after 0 emits"));
} else if (executionResult == AbstractTestHystrixCommand.ExecutionResult.ASYNC_HYSTRIX_FAILURE) {
subscriber.onError(new HystrixRuntimeException(HystrixRuntimeException.FailureType.COMMAND_EXCEPTION, AbstractFlexibleTestHystrixObservableCommand.class, "Execution Hystrix Failure for TestHystrixObservableCommand", new RuntimeException("Execution Failure for TestHystrixObservableCommand"), new RuntimeException("Fallback Failure for TestHystrixObservableCommand")));
} else if (executionResult == AbstractTestHystrixCommand.ExecutionResult.ASYNC_RECOVERABLE_ERROR) {
subscriber.onError(new java.lang.Error("Execution Async Error for TestHystrixObservableCommand"));
} else if (executionResult == AbstractTestHystrixCommand.ExecutionResult.ASYNC_UNRECOVERABLE_ERROR) {
subscriber.onError(new OutOfMemoryError("Execution Async OOME for TestHystrixObservableCommand"));
} else if (executionResult == AbstractTestHystrixCommand.ExecutionResult.ASYNC_BAD_REQUEST) {
subscriber.onError(new HystrixBadRequestException("Execution Async Bad Request Exception for TestHystrixObservableCommand"));
} else {
subscriber.onError(new RuntimeException("You passed in a executionResult enum that can't be represented in HystrixObservableCommand: " + executionResult));
}
}
});
}
@Override
public String getCacheKey() {
if (cacheEnabled == CacheEnabled.YES)
return value.toString();
else
return null;
}
protected void addLatency(int latency) {
if (latency > 0) {
try {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " About to sleep for : " + latency);
Thread.sleep(latency);
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Woke up from sleep!");
} catch (InterruptedException e) {
e.printStackTrace();
// ignore and sleep some more to simulate a dependency that doesn't obey interrupts
try {
Thread.sleep(latency);
} catch (Exception e2) {
// ignore
}
System.out.println("after interruption with extra sleep");
}
}
}
}
private static class FlexibleTestHystrixObservableCommandWithFallback extends AbstractFlexibleTestHystrixObservableCommand {
private final AbstractTestHystrixCommand.FallbackResult fallbackResult;
private final int fallbackLatency;
public FlexibleTestHystrixObservableCommandWithFallback(HystrixCommandKey commandKey, ExecutionIsolationStrategy isolationStrategy, AbstractTestHystrixCommand.ExecutionResult executionResult, int executionLatency, FallbackResult fallbackResult, int fallbackLatency, TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int timeout, CacheEnabled cacheEnabled, Object value, TryableSemaphore executionSemaphore, TryableSemaphore fallbackSemaphore, boolean circuitBreakerDisabled) {
super(commandKey, isolationStrategy, executionResult, executionLatency, circuitBreaker, threadPool, timeout, cacheEnabled, value, executionSemaphore, fallbackSemaphore, circuitBreakerDisabled);
this.fallbackResult = fallbackResult;
this.fallbackLatency = fallbackLatency;
}
@Override
protected Observable<Integer> resumeWithFallback() {
if (fallbackResult == AbstractTestHystrixCommand.FallbackResult.FAILURE) {
addLatency(fallbackLatency);
throw new RuntimeException("Fallback Sync Failure for TestHystrixCommand");
} else if (fallbackResult == FallbackResult.UNIMPLEMENTED) {
addLatency(fallbackLatency);
return super.resumeWithFallback();
}
return Observable.create(new OnSubscribe<Integer>() {
@Override
public void call(Subscriber<? super Integer> subscriber) {
addLatency(fallbackLatency);
if (fallbackResult == AbstractTestHystrixCommand.FallbackResult.SUCCESS) {
subscriber.onNext(11);
subscriber.onCompleted();
} else if (fallbackResult == FallbackResult.MULTIPLE_EMITS_THEN_SUCCESS) {
subscriber.onNext(12);
subscriber.onNext(13);
subscriber.onNext(14);
subscriber.onNext(15);
subscriber.onCompleted();
} else if (fallbackResult == FallbackResult.MULTIPLE_EMITS_THEN_FAILURE) {
subscriber.onNext(16);
subscriber.onNext(17);
subscriber.onNext(18);
subscriber.onNext(19);
subscriber.onError(new RuntimeException("Fallback Async Failure For TestHystrixObservableCommand after 4 emits"));
} else if (fallbackResult == AbstractTestHystrixCommand.FallbackResult.ASYNC_FAILURE) {
subscriber.onError(new RuntimeException("Fallback Async Failure for TestHystrixCommand after 0 fallback emits"));
} else {
subscriber.onError(new RuntimeException("You passed in a fallbackResult enum that can't be represented in HystrixObservableCommand: " + fallbackResult));
}
}
});
}
}
private static class FlexibleTestHystrixObservableCommandNoFallback extends AbstractFlexibleTestHystrixObservableCommand {
public FlexibleTestHystrixObservableCommandNoFallback(HystrixCommandKey commandKey, ExecutionIsolationStrategy isolationStrategy, AbstractTestHystrixCommand.ExecutionResult executionResult, int executionLatency, TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int timeout, CacheEnabled cacheEnabled, Object value, TryableSemaphore executionSemaphore, TryableSemaphore fallbackSemaphore, boolean circuitBreakerDisabled) {
super(commandKey, isolationStrategy, executionResult, executionLatency, circuitBreaker, threadPool, timeout, cacheEnabled, value, executionSemaphore, fallbackSemaphore, circuitBreakerDisabled);
}
}
/**
* Successful execution - no fallback implementation.
*/
private static class SuccessfulTestCommand extends TestHystrixObservableCommand<Boolean> {
public SuccessfulTestCommand(ExecutionIsolationStrategy isolationStrategy) {
this(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(isolationStrategy));
}
public SuccessfulTestCommand(HystrixCommandProperties.Setter properties) {
super(testPropsBuilder().setCommandPropertiesDefaults(properties));
}
@Override
protected Observable<Boolean> construct() {
return Observable.just(true).subscribeOn(Schedulers.computation());
}
}
/**
* Successful execution - no fallback implementation.
*/
private static class TestCommandWithMultipleValues extends TestHystrixObservableCommand<Boolean> {
public TestCommandWithMultipleValues() {
this(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE));
}
public TestCommandWithMultipleValues(HystrixCommandProperties.Setter properties) {
super(testPropsBuilder().setCommandPropertiesDefaults(properties));
}
@Override
protected Observable<Boolean> construct() {
return Observable.just(true, false, true).subscribeOn(Schedulers.computation());
}
}
private static class TestPartialSuccess extends TestHystrixObservableCommand<Integer> {
TestPartialSuccess() {
super(TestHystrixObservableCommand.testPropsBuilder());
}
@Override
protected Observable<Integer> construct() {
return Observable.just(1, 2, 3)
.concatWith(Observable.<Integer> error(new RuntimeException("forced error")))
.subscribeOn(Schedulers.computation());
}
}
private static class TestPartialSuccessWithFallback extends TestHystrixObservableCommand<Boolean> {
TestPartialSuccessWithFallback() {
super(TestHystrixObservableCommand.testPropsBuilder());
}
public TestPartialSuccessWithFallback(ExecutionIsolationStrategy isolationStrategy) {
this(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(isolationStrategy));
}
public TestPartialSuccessWithFallback(HystrixCommandProperties.Setter properties) {
super(testPropsBuilder().setCommandPropertiesDefaults(properties));
}
@Override
protected Observable<Boolean> construct() {
return Observable.just(false, true, false)
.concatWith(Observable.<Boolean>error(new RuntimeException("forced error")))
.subscribeOn(Schedulers.computation());
}
@Override
protected Observable<Boolean> resumeWithFallback() {
return Observable.just(true, false, true, false);
}
}
/**
* Successful execution - no fallback implementation.
*/
private static class DynamicOwnerTestCommand extends TestHystrixObservableCommand<Boolean> {
public DynamicOwnerTestCommand(HystrixCommandGroupKey owner) {
super(testPropsBuilder().setOwner(owner));
}
@Override
protected Observable<Boolean> construct() {
System.out.println("successfully executed");
return Observable.just(true).subscribeOn(Schedulers.computation());
}
}
/**
* Successful execution - no fallback implementation.
*/
private static class DynamicOwnerAndKeyTestCommand extends TestHystrixObservableCommand<Boolean> {
public DynamicOwnerAndKeyTestCommand(HystrixCommandGroupKey owner, HystrixCommandKey key) {
super(testPropsBuilder().setOwner(owner).setCommandKey(key).setCircuitBreaker(null).setMetrics(null));
// we specifically are NOT passing in a circuit breaker here so we test that it creates a new one correctly based on the dynamic key
}
@Override
protected Observable<Boolean> construct() {
System.out.println("successfully executed");
return Observable.just(true).subscribeOn(Schedulers.computation());
}
}
/**
* Failed execution with unknown exception (not HystrixException) - no fallback implementation.
*/
private static class UnknownFailureTestCommandWithoutFallback extends TestHystrixObservableCommand<Boolean> {
private final boolean asyncException;
private UnknownFailureTestCommandWithoutFallback(ExecutionIsolationStrategy isolationStrategy, boolean asyncException) {
super(testPropsBuilder(isolationStrategy, new TestCircuitBreaker()));
this.asyncException = asyncException;
}
@Override
protected Observable<Boolean> construct() {
System.out.println("*** simulated failed execution ***");
RuntimeException ex = new RuntimeException("we failed with an unknown issue");
if (asyncException) {
return Observable.error(ex);
} else {
throw ex;
}
}
}
/**
* Failed execution with known exception (HystrixException) - no fallback implementation.
*/
private static class KnownFailureTestCommandWithoutFallback extends TestHystrixObservableCommand<Boolean> {
final boolean asyncException;
private KnownFailureTestCommandWithoutFallback(TestCircuitBreaker circuitBreaker, ExecutionIsolationStrategy isolationStrategy, boolean asyncException) {
super(testPropsBuilder(isolationStrategy, circuitBreaker).setMetrics(circuitBreaker.metrics));
this.asyncException = asyncException;
}
@Override
protected Observable<Boolean> construct() {
System.out.println("*** simulated failed execution ***");
RuntimeException ex = new RuntimeException("we failed with a simulated issue");
if (asyncException) {
return Observable.error(ex);
} else {
throw ex;
}
}
}
/**
* Failed execution - fallback implementation successfully returns value.
*/
private static class KnownFailureTestCommandWithFallback extends TestHystrixObservableCommand<Boolean> {
private final boolean asyncException;
public KnownFailureTestCommandWithFallback(TestCircuitBreaker circuitBreaker, ExecutionIsolationStrategy isolationStrategy, boolean asyncException) {
super(testPropsBuilder(isolationStrategy, circuitBreaker).setMetrics(circuitBreaker.metrics));
this.asyncException = asyncException;
}
public KnownFailureTestCommandWithFallback(TestCircuitBreaker circuitBreaker, boolean fallbackEnabled, boolean asyncException) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withFallbackEnabled(fallbackEnabled).withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)));
this.asyncException = asyncException;
}
@Override
protected Observable<Boolean> construct() {
System.out.println("*** simulated failed execution ***");
RuntimeException ex = new RuntimeException("we failed with a simulated issue");
if (asyncException) {
return Observable.error(ex);
} else {
throw ex;
}
}
@Override
protected Observable<Boolean> resumeWithFallback() {
return Observable.just(false).subscribeOn(Schedulers.computation());
}
}
/**
* Failed execution with {@link HystrixBadRequestException}
*/
private static class KnownHystrixBadRequestFailureTestCommand extends TestHystrixObservableCommand<Boolean> {
public final static boolean ASYNC_EXCEPTION = true;
public final static boolean SYNC_EXCEPTION = false;
private final boolean asyncException;
public KnownHystrixBadRequestFailureTestCommand(TestCircuitBreaker circuitBreaker, ExecutionIsolationStrategy isolationStrategy, boolean asyncException) {
super(testPropsBuilder(isolationStrategy, circuitBreaker).setMetrics(circuitBreaker.metrics));
this.asyncException = asyncException;
}
@Override
protected Observable<Boolean> construct() {
System.out.println("*** simulated failed with HystrixBadRequestException ***");
RuntimeException ex = new HystrixBadRequestException("we failed with a simulated issue");
if (asyncException) {
return Observable.error(ex);
} else {
throw ex;
}
}
}
/**
* Failed execution - fallback implementation throws exception.
*/
private static class KnownFailureTestCommandWithFallbackFailure extends TestHystrixObservableCommand<Boolean> {
private final boolean asyncConstructException;
private final boolean asyncFallbackException;
private KnownFailureTestCommandWithFallbackFailure(TestCircuitBreaker circuitBreaker, ExecutionIsolationStrategy isolationStrategy, boolean asyncConstructException, boolean asyncFallbackException) {
super(testPropsBuilder(isolationStrategy, circuitBreaker).setMetrics(circuitBreaker.metrics));
this.asyncConstructException = asyncConstructException;
this.asyncFallbackException = asyncFallbackException;
}
@Override
protected Observable<Boolean> construct() {
RuntimeException ex = new RuntimeException("we failed with a simulated issue");
System.out.println("*** simulated failed execution ***");
if (asyncConstructException) {
return Observable.error(ex);
} else {
throw ex;
}
}
@Override
protected Observable<Boolean> resumeWithFallback() {
RuntimeException ex = new RuntimeException("failed while getting fallback");
if (asyncFallbackException) {
return Observable.error(ex);
} else {
throw ex;
}
}
}
/**
* A Command implementation that supports caching.
*/
private static class SuccessfulCacheableCommand<T> extends TestHystrixObservableCommand<T> {
private final boolean cacheEnabled;
private volatile boolean executed = false;
private final T value;
public SuccessfulCacheableCommand(TestCircuitBreaker circuitBreaker, boolean cacheEnabled, T value) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(ExecutionIsolationStrategy.THREAD)));
this.value = value;
this.cacheEnabled = cacheEnabled;
}
@Override
protected Observable<T> construct() {
executed = true;
System.out.println("successfully executed");
return Observable.just(value).subscribeOn(Schedulers.computation());
}
public boolean isCommandRunningInThread() {
return super.getProperties().executionIsolationStrategy().get().equals(ExecutionIsolationStrategy.THREAD);
}
@Override
public String getCacheKey() {
if (cacheEnabled)
return value.toString();
else
return null;
}
}
/**
* A Command implementation that supports caching.
*/
private static class SuccessfulCacheableCommandViaSemaphore extends TestHystrixObservableCommand<String> {
private final boolean cacheEnabled;
private volatile boolean executed = false;
private final String value;
public SuccessfulCacheableCommandViaSemaphore(TestCircuitBreaker circuitBreaker, boolean cacheEnabled, String value) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)));
this.value = value;
this.cacheEnabled = cacheEnabled;
}
@Override
protected Observable<String> construct() {
executed = true;
System.out.println("successfully executed");
return Observable.just(value).subscribeOn(Schedulers.computation());
}
public boolean isCommandRunningInThread() {
return super.getProperties().executionIsolationStrategy().get().equals(ExecutionIsolationStrategy.THREAD);
}
@Override
public String getCacheKey() {
if (cacheEnabled)
return value;
else
return null;
}
}
/**
* A Command implementation that supports caching and execution takes a while.
* <p>
* Used to test scenario where Futures are returned with a backing call still executing.
*/
private static class SlowCacheableCommand extends TestHystrixObservableCommand<String> {
private final String value;
private final int duration;
private volatile boolean executed = false;
public SlowCacheableCommand(TestCircuitBreaker circuitBreaker, String value, int duration) {
super(testPropsBuilder()
.setCommandKey(HystrixCommandKey.Factory.asKey("ObservableSlowCacheable"))
.setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics));
this.value = value;
this.duration = duration;
}
@Override
protected Observable<String> construct() {
executed = true;
return Observable.just(value).delay(duration, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.computation())
.doOnNext(new Action1<String>() {
@Override
public void call(String t1) {
System.out.println("successfully executed");
}
});
}
@Override
public String getCacheKey() {
return value;
}
}
/**
* Successful execution - no fallback implementation, circuit-breaker disabled.
*/
private static class TestCommandWithoutCircuitBreaker extends TestHystrixObservableCommand<Boolean> {
private TestCommandWithoutCircuitBreaker() {
super(testPropsBuilder().setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE).withCircuitBreakerEnabled(false)));
}
@Override
protected Observable<Boolean> construct() {
System.out.println("successfully executed");
return Observable.just(true).subscribeOn(Schedulers.computation());
}
}
private static class NoRequestCacheTimeoutWithoutFallback extends TestHystrixObservableCommand<Boolean> {
public NoRequestCacheTimeoutWithoutFallback(TestCircuitBreaker circuitBreaker) {
super(testPropsBuilder(circuitBreaker).setMetrics(circuitBreaker.metrics)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE).withExecutionTimeoutInMilliseconds(200).withCircuitBreakerEnabled(false)));
// we want it to timeout
}
@Override
protected Observable<Boolean> construct() {
return Observable.create(new OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> s) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(">>>> Sleep Interrupted: " + e.getMessage());
// e.printStackTrace();
}
s.onNext(true);
s.onCompleted();
}
}).subscribeOn(Schedulers.computation());
}
@Override
public String getCacheKey() {
return null;
}
}
/**
* The run() will take time. Configurable fallback implementation.
*/
private static class TestSemaphoreCommand extends TestHystrixObservableCommand<Boolean> {
private final long executionSleep;
private final static int RESULT_SUCCESS = 1;
private final static int RESULT_FAILURE = 2;
private final static int RESULT_BAD_REQUEST_EXCEPTION = 3;
private final int resultBehavior;
private final static int FALLBACK_SUCCESS = 10;
private final static int FALLBACK_NOT_IMPLEMENTED = 11;
private final static int FALLBACK_FAILURE = 12;
private final int fallbackBehavior;
private final static boolean FALLBACK_FAILURE_SYNC = false;
private final static boolean FALLBACK_FAILURE_ASYNC = true;
private final boolean asyncFallbackException;
private TestSemaphoreCommand(TestCircuitBreaker circuitBreaker, int executionSemaphoreCount, long executionSleep, int resultBehavior, int fallbackBehavior) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter()
.withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)
.withExecutionIsolationSemaphoreMaxConcurrentRequests(executionSemaphoreCount)));
this.executionSleep = executionSleep;
this.resultBehavior = resultBehavior;
this.fallbackBehavior = fallbackBehavior;
this.asyncFallbackException = FALLBACK_FAILURE_ASYNC;
}
private TestSemaphoreCommand(TestCircuitBreaker circuitBreaker, TryableSemaphore semaphore, long executionSleep, int resultBehavior, int fallbackBehavior) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter()
.withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE))
.setExecutionSemaphore(semaphore));
this.executionSleep = executionSleep;
this.resultBehavior = resultBehavior;
this.fallbackBehavior = fallbackBehavior;
this.asyncFallbackException = FALLBACK_FAILURE_ASYNC;
}
@Override
protected Observable<Boolean> construct() {
return Observable.create(new OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> subscriber) {
try {
Thread.sleep(executionSleep);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (resultBehavior == RESULT_SUCCESS) {
subscriber.onNext(true);
subscriber.onCompleted();
} else if (resultBehavior == RESULT_FAILURE) {
subscriber.onError(new RuntimeException("TestSemaphoreCommand failure"));
} else if (resultBehavior == RESULT_BAD_REQUEST_EXCEPTION) {
subscriber.onError(new HystrixBadRequestException("TestSemaphoreCommand BadRequestException"));
} else {
subscriber.onError(new IllegalStateException("Didn't use a proper enum for result behavior"));
}
}
});
}
@Override
protected Observable<Boolean> resumeWithFallback() {
if (fallbackBehavior == FALLBACK_SUCCESS) {
return Observable.just(false);
} else if (fallbackBehavior == FALLBACK_FAILURE) {
RuntimeException ex = new RuntimeException("fallback failure");
if (asyncFallbackException) {
return Observable.error(ex);
} else {
throw ex;
}
} else { //FALLBACK_NOT_IMPLEMENTED
return super.resumeWithFallback();
}
}
}
/**
* The construct() will take time once subscribed to. No fallback implementation.
*
* Used for making sure Thread and Semaphore isolation are separated from each other.
*/
private static class TestThreadIsolationWithSemaphoreSetSmallCommand extends TestHystrixObservableCommand<Boolean> {
private final Action0 action;
private TestThreadIsolationWithSemaphoreSetSmallCommand(TestCircuitBreaker circuitBreaker, int poolSize, Action0 action) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)
.setThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(TestThreadIsolationWithSemaphoreSetSmallCommand.class.getSimpleName()))
.setThreadPoolPropertiesDefaults(HystrixThreadPoolPropertiesTest.getUnitTestPropertiesBuilder()
.withCoreSize(poolSize).withMaximumSize(poolSize).withMaxQueueSize(0))
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter()
.withExecutionIsolationStrategy(ExecutionIsolationStrategy.THREAD)
.withExecutionIsolationSemaphoreMaxConcurrentRequests(1)));
this.action = action;
}
@Override
protected Observable<Boolean> construct() {
return Observable.create(new OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> s) {
action.call();
s.onNext(true);
s.onCompleted();
}
});
}
}
/**
* Semaphore based command that allows caller to use latches to know when it has started and signal when it
* would like the command to finish
*/
private static class LatchedSemaphoreCommand extends TestHystrixObservableCommand<Boolean> {
private final CountDownLatch startLatch, waitLatch;
/**
*
* @param circuitBreaker circuit breaker (passed in so it may be shared)
* @param semaphore semaphore (passed in so it may be shared)
* @param startLatch
* this command calls {@link CountDownLatch#countDown()} immediately upon running
* @param waitLatch
* this command calls {@link CountDownLatch#await()} once it starts
* to run. The caller can use the latch to signal the command to finish
*/
private LatchedSemaphoreCommand(TestCircuitBreaker circuitBreaker, TryableSemaphoreActual semaphore, CountDownLatch startLatch, CountDownLatch waitLatch) {
this("Latched", circuitBreaker, semaphore, startLatch, waitLatch);
}
private LatchedSemaphoreCommand(String commandName, TestCircuitBreaker circuitBreaker, TryableSemaphoreActual semaphore, CountDownLatch startLatch, CountDownLatch waitLatch) {
super(testPropsBuilder()
.setCommandKey(HystrixCommandKey.Factory.asKey(commandName))
.setCircuitBreaker(circuitBreaker)
.setMetrics(circuitBreaker.metrics)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter()
.withExecutionTimeoutEnabled(false)
.withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)
.withCircuitBreakerEnabled(false))
.setExecutionSemaphore(semaphore));
this.startLatch = startLatch;
this.waitLatch = waitLatch;
}
@Override
protected Observable<Boolean> construct() {
return Observable.create(new OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> s) {
//signals caller that run has started
startLatch.countDown();
try {
// waits for caller to countDown latch
waitLatch.await();
s.onNext(true);
s.onCompleted();
} catch (InterruptedException e) {
e.printStackTrace();
s.onNext(false);
s.onCompleted();
}
}
}).subscribeOn(Schedulers.newThread());
}
@Override
protected Observable<Boolean> resumeWithFallback() {
return Observable.defer(new Func0<Observable<Boolean>>() {
@Override
public Observable<Boolean> call() {
startLatch.countDown();
return Observable.just(false);
}
});
}
}
/**
* The construct() will take time once subscribed to. Contains fallback.
*/
private static class TestSemaphoreCommandWithFallback extends TestHystrixObservableCommand<Boolean> {
private final long executionSleep;
private final Observable<Boolean> fallback;
private TestSemaphoreCommandWithFallback(TestCircuitBreaker circuitBreaker, int executionSemaphoreCount, long executionSleep, Boolean fallback) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE).withExecutionIsolationSemaphoreMaxConcurrentRequests(executionSemaphoreCount)));
this.executionSleep = executionSleep;
this.fallback = Observable.just(fallback);
}
@Override
protected Observable<Boolean> construct() {
return Observable.create(new OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> s) {
try {
Thread.sleep(executionSleep);
} catch (InterruptedException e) {
e.printStackTrace();
}
s.onNext(true);
s.onCompleted();
}
}).subscribeOn(Schedulers.io());
}
@Override
protected Observable<Boolean> resumeWithFallback() {
return fallback;
}
}
private static class InterruptibleCommand extends TestHystrixObservableCommand<Boolean> {
public InterruptibleCommand(TestCircuitBreaker circuitBreaker, boolean shouldInterrupt) {
super(testPropsBuilder()
.setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter()
.withExecutionIsolationThreadInterruptOnTimeout(shouldInterrupt)
.withExecutionTimeoutInMilliseconds(100)));
}
private volatile boolean hasBeenInterrupted;
public boolean hasBeenInterrupted()
{
return hasBeenInterrupted;
}
@Override
protected Observable<Boolean> construct() {
return Observable.defer(new Func0<Observable<Boolean>>() {
@Override
public Observable<Boolean> call() {
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
System.out.println("Interrupted!");
e.printStackTrace();
hasBeenInterrupted = true;
}
return Observable.just(hasBeenInterrupted);
}
}).subscribeOn(Schedulers.io());
}
}
private static class RequestCacheNullPointerExceptionCase extends TestHystrixObservableCommand<Boolean> {
public RequestCacheNullPointerExceptionCase(TestCircuitBreaker circuitBreaker) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE).withExecutionTimeoutInMilliseconds(200)));
// we want it to timeout
}
@Override
protected Observable<Boolean> construct() {
return Observable.create(new OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> s) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
s.onNext(true);
s.onCompleted();
}
}).subscribeOn(Schedulers.computation());
}
@Override
protected Observable<Boolean> resumeWithFallback() {
return Observable.just(false).subscribeOn(Schedulers.computation());
}
@Override
public String getCacheKey() {
return "A";
}
}
private static class RequestCacheTimeoutWithoutFallback extends TestHystrixObservableCommand<Boolean> {
public RequestCacheTimeoutWithoutFallback(TestCircuitBreaker circuitBreaker) {
super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE).withExecutionTimeoutInMilliseconds(200)));
// we want it to timeout
}
@Override
protected Observable<Boolean> construct() {
return Observable.create(new OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> s) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(">>>> Sleep Interrupted: " + e.getMessage());
// e.printStackTrace();
}
s.onNext(true);
s.onCompleted();
}
}).subscribeOn(Schedulers.computation());
}
@Override
public String getCacheKey() {
return "A";
}
}
private static class RequestCacheThreadRejectionWithoutFallback extends TestHystrixObservableCommand<Boolean> {
final CountDownLatch completionLatch;
public RequestCacheThreadRejectionWithoutFallback(TestCircuitBreaker circuitBreaker, CountDownLatch completionLatch) {
super(testPropsBuilder()
.setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(ExecutionIsolationStrategy.THREAD))
.setCircuitBreaker(circuitBreaker)
.setMetrics(circuitBreaker.metrics)
.setThreadPool(new HystrixThreadPool() {
@Override
public ThreadPoolExecutor getExecutor() {
return null;
}
@Override
public void markThreadExecution() {
}
@Override
public void markThreadCompletion() {
}
@Override
public void markThreadRejection() {
}
@Override
public boolean isQueueSpaceAvailable() {
// always return false so we reject everything
return false;
}
@Override
public Scheduler getScheduler() {
return new HystrixContextScheduler(HystrixPlugins.getInstance().getConcurrencyStrategy(), this);
}
@Override
public Scheduler getScheduler(Func0<Boolean> shouldInterruptThread) {
return new HystrixContextScheduler(HystrixPlugins.getInstance().getConcurrencyStrategy(), this, shouldInterruptThread);
}
}));
this.completionLatch = completionLatch;
}
@Override
protected Observable<Boolean> construct() {
try {
if (completionLatch.await(1000, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("timed out waiting on completionLatch");
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return Observable.just(true);
}
@Override
public String getCacheKey() {
return "A";
}
}
private static class CommandWithErrorThrown extends TestHystrixObservableCommand<Boolean> {
private final boolean asyncException;
public CommandWithErrorThrown(TestCircuitBreaker circuitBreaker, boolean asyncException) {
super(testPropsBuilder()
.setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics));
this.asyncException = asyncException;
}
@Override
protected Observable<Boolean> construct() {
Error error = new Error("simulated java.lang.Error message");
if (asyncException) {
return Observable.error(error);
} else {
throw error;
}
}
}
private static class CommandWithCheckedException extends TestHystrixObservableCommand<Boolean> {
public CommandWithCheckedException(TestCircuitBreaker circuitBreaker) {
super(testPropsBuilder()
.setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics));
}
@Override
protected Observable<Boolean> construct() {
return Observable.error(new IOException("simulated checked exception message"));
}
}
}
| 4,568 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/HystrixCommandMetricsTest.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import com.hystrix.junit.HystrixRequestContextRule;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import rx.Observable;
import rx.Subscriber;
import rx.observers.SafeSubscriber;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class HystrixCommandMetricsTest {
@Rule
public HystrixRequestContextRule ctx = new HystrixRequestContextRule();
@Before
public void init() {
HystrixCommandMetrics.reset();
Hystrix.reset();
}
@Test
public void testGetErrorPercentage() {
String key = "cmd-metrics-A";
try {
HystrixCommand<Boolean> cmd1 = new SuccessCommand(key, 1);
HystrixCommandMetrics metrics = cmd1.metrics;
cmd1.execute();
Thread.sleep(100);
assertEquals(0, metrics.getHealthCounts().getErrorPercentage());
HystrixCommand<Boolean> cmd2 = new FailureCommand(key, 1);
cmd2.execute();
Thread.sleep(100);
assertEquals(50, metrics.getHealthCounts().getErrorPercentage());
HystrixCommand<Boolean> cmd3 = new SuccessCommand(key, 1);
HystrixCommand<Boolean> cmd4 = new SuccessCommand(key, 1);
cmd3.execute();
cmd4.execute();
Thread.sleep(100);
assertEquals(25, metrics.getHealthCounts().getErrorPercentage());
HystrixCommand<Boolean> cmd5 = new TimeoutCommand(key);
HystrixCommand<Boolean> cmd6 = new TimeoutCommand(key);
cmd5.execute();
cmd6.execute();
Thread.sleep(100);
assertEquals(50, metrics.getHealthCounts().getErrorPercentage());
HystrixCommand<Boolean> cmd7 = new SuccessCommand(key, 1);
HystrixCommand<Boolean> cmd8 = new SuccessCommand(key, 1);
HystrixCommand<Boolean> cmd9 = new SuccessCommand(key, 1);
cmd7.execute();
cmd8.execute();
cmd9.execute();
// latent
HystrixCommand<Boolean> cmd10 = new SuccessCommand(key, 60);
cmd10.execute();
// 6 success + 1 latent success + 1 failure + 2 timeout = 10 total
// latent success not considered error
// error percentage = 1 failure + 2 timeout / 10
Thread.sleep(100);
assertEquals(30, metrics.getHealthCounts().getErrorPercentage());
} catch (Exception e) {
e.printStackTrace();
fail("Error occurred: " + e.getMessage());
}
}
@Test
public void testBadRequestsDoNotAffectErrorPercentage() {
String key = "cmd-metrics-B";
try {
HystrixCommand<Boolean> cmd1 = new SuccessCommand(key ,1);
HystrixCommandMetrics metrics = cmd1.metrics;
cmd1.execute();
Thread.sleep(100);
assertEquals(0, metrics.getHealthCounts().getErrorPercentage());
HystrixCommand<Boolean> cmd2 = new FailureCommand(key, 1);
cmd2.execute();
Thread.sleep(100);
assertEquals(50, metrics.getHealthCounts().getErrorPercentage());
HystrixCommand<Boolean> cmd3 = new BadRequestCommand(key, 1);
HystrixCommand<Boolean> cmd4 = new BadRequestCommand(key, 1);
try {
cmd3.execute();
} catch (HystrixBadRequestException ex) {
System.out.println("Caught expected HystrixBadRequestException from cmd3");
}
try {
cmd4.execute();
} catch (HystrixBadRequestException ex) {
System.out.println("Caught expected HystrixBadRequestException from cmd4");
}
Thread.sleep(100);
assertEquals(50, metrics.getHealthCounts().getErrorPercentage());
HystrixCommand<Boolean> cmd5 = new FailureCommand(key, 1);
HystrixCommand<Boolean> cmd6 = new FailureCommand(key, 1);
cmd5.execute();
cmd6.execute();
Thread.sleep(100);
assertEquals(75, metrics.getHealthCounts().getErrorPercentage());
} catch (Exception e) {
e.printStackTrace();
fail("Error occurred : " + e.getMessage());
}
}
@Test
public void testCurrentConcurrentExecutionCount() throws InterruptedException {
String key = "cmd-metrics-C";
HystrixCommandMetrics metrics = null;
List<Observable<Boolean>> cmdResults = new ArrayList<Observable<Boolean>>();
int NUM_CMDS = 8;
for (int i = 0; i < NUM_CMDS; i++) {
HystrixCommand<Boolean> cmd = new SuccessCommand(key, 900);
if (metrics == null) {
metrics = cmd.metrics;
}
Observable<Boolean> eagerObservable = cmd.observe();
cmdResults.add(eagerObservable);
}
try {
Thread.sleep(150);
} catch (InterruptedException ie) {
fail(ie.getMessage());
}
System.out.println("ReqLog: " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertEquals(NUM_CMDS, metrics.getCurrentConcurrentExecutionCount());
final CountDownLatch latch = new CountDownLatch(1);
Observable.merge(cmdResults).subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
System.out.println("All commands done");
latch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println("Error duing command execution");
e.printStackTrace();
latch.countDown();
}
@Override
public void onNext(Boolean aBoolean) {
}
});
latch.await(10000, TimeUnit.MILLISECONDS);
assertEquals(0, metrics.getCurrentConcurrentExecutionCount());
}
private class Command extends HystrixCommand<Boolean> {
private final boolean shouldFail;
private final boolean shouldFailWithBadRequest;
private final long latencyToAdd;
public Command(String commandKey, boolean shouldFail, boolean shouldFailWithBadRequest, long latencyToAdd) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("Command"))
.andCommandKey(HystrixCommandKey.Factory.asKey(commandKey))
.andCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter()
.withExecutionTimeoutInMilliseconds(1000)
.withCircuitBreakerRequestVolumeThreshold(20)));
this.shouldFail = shouldFail;
this.shouldFailWithBadRequest = shouldFailWithBadRequest;
this.latencyToAdd = latencyToAdd;
}
@Override
protected Boolean run() throws Exception {
Thread.sleep(latencyToAdd);
if (shouldFail) {
throw new RuntimeException("induced failure");
}
if (shouldFailWithBadRequest) {
throw new HystrixBadRequestException("bad request");
}
return true;
}
@Override
protected Boolean getFallback() {
return false;
}
}
private class SuccessCommand extends Command {
SuccessCommand(String commandKey, long latencyToAdd) {
super(commandKey, false, false, latencyToAdd);
}
}
private class FailureCommand extends Command {
FailureCommand(String commandKey, long latencyToAdd) {
super(commandKey, true, false, latencyToAdd);
}
}
private class TimeoutCommand extends Command {
TimeoutCommand(String commandKey) {
super(commandKey, false, false, 2000);
}
}
private class BadRequestCommand extends Command {
BadRequestCommand(String commandKey, long latencyToAdd) {
super(commandKey, false, true, latencyToAdd);
}
}
}
| 4,569 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/HystrixThreadPoolMetricsTest.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix;
import com.netflix.hystrix.metric.consumer.RollingThreadPoolEventCounterStream;
import org.junit.Before;
import org.junit.Test;
import java.util.Collection;
import static org.junit.Assert.assertEquals;
public class HystrixThreadPoolMetricsTest {
private static final HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("HystrixThreadPoolMetrics-UnitTest");
private static final HystrixThreadPoolKey tpKey = HystrixThreadPoolKey.Factory.asKey("HystrixThreadPoolMetrics-ThreadPool");
@Before
public void resetAll() {
HystrixThreadPoolMetrics.reset();
}
@Test
public void shouldYieldNoExecutedTasksOnStartup() throws Exception {
//given
final Collection<HystrixThreadPoolMetrics> instances = HystrixThreadPoolMetrics.getInstances();
//then
assertEquals(0, instances.size());
}
@Test
public void shouldReturnOneExecutedTask() throws Exception {
//given
RollingThreadPoolEventCounterStream.getInstance(tpKey, 10, 100).startCachingStreamValuesIfUnstarted();
new NoOpHystrixCommand().execute();
Thread.sleep(100);
final Collection<HystrixThreadPoolMetrics> instances = HystrixThreadPoolMetrics.getInstances();
//then
assertEquals(1, instances.size());
HystrixThreadPoolMetrics metrics = instances.iterator().next();
assertEquals(1, instances.iterator().next().getRollingCountThreadsExecuted());
}
private static class NoOpHystrixCommand extends HystrixCommand<Void> {
public NoOpHystrixCommand() {
super(Setter.withGroupKey(groupKey)
.andThreadPoolKey(tpKey)
.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter().withMetricsRollingStatisticalWindowInMilliseconds(100)));
}
@Override
protected Void run() throws Exception {
System.out.println("Run in thread : " + Thread.currentThread().getName());
return null;
}
}
} | 4,570 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/HystrixSubclassCommandTest.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix;
import com.hystrix.junit.HystrixRequestContextRule;
import org.junit.Rule;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class HystrixSubclassCommandTest {
private final static HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("GROUP");
@Rule
public HystrixRequestContextRule ctx = new HystrixRequestContextRule();
@Test
public void testFallback() {
HystrixCommand<Integer> superCmd = new SuperCommand("cache", false);
assertEquals(2, superCmd.execute().intValue());
HystrixCommand<Integer> subNoOverridesCmd = new SubCommandNoOverride("cache", false);
assertEquals(2, subNoOverridesCmd.execute().intValue());
HystrixCommand<Integer> subOverriddenFallbackCmd = new SubCommandOverrideFallback("cache", false);
assertEquals(3, subOverriddenFallbackCmd.execute().intValue());
}
@Test
public void testRequestCacheSuperClass() {
HystrixCommand<Integer> superCmd1 = new SuperCommand("cache", true);
assertEquals(1, superCmd1.execute().intValue());
HystrixCommand<Integer> superCmd2 = new SuperCommand("cache", true);
assertEquals(1, superCmd2.execute().intValue());
HystrixCommand<Integer> superCmd3 = new SuperCommand("no-cache", true);
assertEquals(1, superCmd3.execute().intValue());
System.out.println("REQ LOG : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
HystrixRequestLog reqLog = HystrixRequestLog.getCurrentRequest();
assertEquals(3, reqLog.getAllExecutedCommands().size());
List<HystrixInvokableInfo<?>> infos = new ArrayList<HystrixInvokableInfo<?>>(reqLog.getAllExecutedCommands());
HystrixInvokableInfo<?> info1 = infos.get(0);
assertEquals("SuperCommand", info1.getCommandKey().name());
assertEquals(1, info1.getExecutionEvents().size());
HystrixInvokableInfo<?> info2 = infos.get(1);
assertEquals("SuperCommand", info2.getCommandKey().name());
assertEquals(2, info2.getExecutionEvents().size());
assertEquals(HystrixEventType.RESPONSE_FROM_CACHE, info2.getExecutionEvents().get(1));
HystrixInvokableInfo<?> info3 = infos.get(2);
assertEquals("SuperCommand", info3.getCommandKey().name());
assertEquals(1, info3.getExecutionEvents().size());
}
@Test
public void testRequestCacheSubclassNoOverrides() {
HystrixCommand<Integer> subCmd1 = new SubCommandNoOverride("cache", true);
assertEquals(1, subCmd1.execute().intValue());
HystrixCommand<Integer> subCmd2 = new SubCommandNoOverride("cache", true);
assertEquals(1, subCmd2.execute().intValue());
HystrixCommand<Integer> subCmd3 = new SubCommandNoOverride("no-cache", true);
assertEquals(1, subCmd3.execute().intValue());
System.out.println("REQ LOG : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
HystrixRequestLog reqLog = HystrixRequestLog.getCurrentRequest();
assertEquals(3, reqLog.getAllExecutedCommands().size());
List<HystrixInvokableInfo<?>> infos = new ArrayList<HystrixInvokableInfo<?>>(reqLog.getAllExecutedCommands());
HystrixInvokableInfo<?> info1 = infos.get(0);
assertEquals("SubCommandNoOverride", info1.getCommandKey().name());
assertEquals(1, info1.getExecutionEvents().size());
HystrixInvokableInfo<?> info2 = infos.get(1);
assertEquals("SubCommandNoOverride", info2.getCommandKey().name());
assertEquals(2, info2.getExecutionEvents().size());
assertEquals(HystrixEventType.RESPONSE_FROM_CACHE, info2.getExecutionEvents().get(1));
HystrixInvokableInfo<?> info3 = infos.get(2);
assertEquals("SubCommandNoOverride", info3.getCommandKey().name());
assertEquals(1, info3.getExecutionEvents().size());
}
@Test
public void testRequestLogSuperClass() {
HystrixCommand<Integer> superCmd = new SuperCommand("cache", true);
assertEquals(1, superCmd.execute().intValue());
System.out.println("REQ LOG : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
HystrixRequestLog reqLog = HystrixRequestLog.getCurrentRequest();
assertEquals(1, reqLog.getAllExecutedCommands().size());
HystrixInvokableInfo<?> info = reqLog.getAllExecutedCommands().iterator().next();
assertEquals("SuperCommand", info.getCommandKey().name());
}
@Test
public void testRequestLogSubClassNoOverrides() {
HystrixCommand<Integer> subCmd = new SubCommandNoOverride("cache", true);
assertEquals(1, subCmd.execute().intValue());
System.out.println("REQ LOG : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
HystrixRequestLog reqLog = HystrixRequestLog.getCurrentRequest();
assertEquals(1, reqLog.getAllExecutedCommands().size());
HystrixInvokableInfo<?> info = reqLog.getAllExecutedCommands().iterator().next();
assertEquals("SubCommandNoOverride", info.getCommandKey().name());
}
public static class SuperCommand extends HystrixCommand<Integer> {
private final String uniqueArg;
private final boolean shouldSucceed;
SuperCommand(String uniqueArg, boolean shouldSucceed) {
super(Setter.withGroupKey(groupKey));
this.uniqueArg = uniqueArg;
this.shouldSucceed = shouldSucceed;
}
@Override
protected Integer run() throws Exception {
if (shouldSucceed) {
return 1;
} else {
throw new RuntimeException("unit test failure");
}
}
@Override
protected Integer getFallback() {
return 2;
}
@Override
protected String getCacheKey() {
return uniqueArg;
}
}
public static class SubCommandNoOverride extends SuperCommand {
SubCommandNoOverride(String uniqueArg, boolean shouldSucceed) {
super(uniqueArg, shouldSucceed);
}
}
public static class SubCommandOverrideFallback extends SuperCommand {
SubCommandOverrideFallback(String uniqueArg, boolean shouldSucceed) {
super(uniqueArg, shouldSucceed);
}
@Override
protected Integer getFallback() {
return 3;
}
}
}
| 4,571 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/CommonHystrixCommandTests.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix;
import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy;
import com.netflix.hystrix.AbstractTestHystrixCommand.CacheEnabled;
import com.netflix.hystrix.AbstractTestHystrixCommand.ExecutionResult;
import com.netflix.hystrix.AbstractTestHystrixCommand.FallbackResult;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import com.netflix.hystrix.strategy.HystrixPlugins;
import com.netflix.hystrix.strategy.concurrency.HystrixContextScheduler;
import com.netflix.hystrix.strategy.properties.HystrixProperty;
import org.junit.Test;
import rx.Observable;
import rx.Scheduler;
import rx.Subscriber;
import rx.functions.Action1;
import rx.functions.Func0;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.Assert.*;
/**
* Place to share code and tests between {@link HystrixCommandTest} and {@link HystrixObservableCommandTest}.
* @param <C>
*/
public abstract class CommonHystrixCommandTests<C extends AbstractTestHystrixCommand<Integer>> {
/**
* Run the command in multiple modes and check that the hook assertions hold in each and that the command succeeds
* @param ctor {@link AbstractTestHystrixCommand} constructor
* @param assertion sequence of assertions to check after the command has completed
*/
abstract void assertHooksOnSuccess(Func0<C> ctor, Action1<C> assertion);
/**
* Run the command in multiple modes and check that the hook assertions hold in each and that the command fails
* @param ctor {@link AbstractTestHystrixCommand} constructor
* @param assertion sequence of assertions to check after the command has completed
*/
abstract void assertHooksOnFailure(Func0<C> ctor, Action1<C> assertion);
/**
* Run the command in multiple modes and check that the hook assertions hold in each and that the command fails
* @param ctor {@link AbstractTestHystrixCommand} constructor
* @param assertion sequence of assertions to check after the command has completed
*/
abstract void assertHooksOnFailure(Func0<C> ctor, Action1<C> assertion, boolean failFast);
/**
* Run the command in multiple modes and check that the hook assertions hold in each and that the command fails as soon as possible
* @param ctor {@link AbstractTestHystrixCommand} constructor
* @param assertion sequence of assertions to check after the command has completed
*/
protected void assertHooksOnFailFast(Func0<C> ctor, Action1<C> assertion) {
assertHooksOnFailure(ctor, assertion, true);
}
/**
* Run the command via {@link com.netflix.hystrix.HystrixCommand#observe()}, immediately block and then assert
* @param command command to run
* @param assertion assertions to check
* @param isSuccess should the command succeed?
*/
protected void assertBlockingObserve(C command, Action1<C> assertion, boolean isSuccess) {
System.out.println("Running command.observe(), immediately blocking and then running assertions...");
if (isSuccess) {
try {
command.observe().toList().toBlocking().single();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
} else {
try {
command.observe().toList().toBlocking().single();
fail("Expected a command failure!");
} catch (Exception ex) {
System.out.println("Received expected ex : " + ex);
ex.printStackTrace();
}
}
assertion.call(command);
}
/**
* Run the command via {@link com.netflix.hystrix.HystrixCommand#observe()}, let the {@link rx.Observable} terminal
* states unblock a {@link java.util.concurrent.CountDownLatch} and then assert
* @param command command to run
* @param assertion assertions to check
* @param isSuccess should the command succeed?
*/
protected void assertNonBlockingObserve(C command, Action1<C> assertion, boolean isSuccess) {
System.out.println("Running command.observe(), awaiting terminal state of Observable, then running assertions...");
final CountDownLatch latch = new CountDownLatch(1);
Observable<Integer> o = command.observe();
o.subscribe(new Subscriber<Integer>() {
@Override
public void onCompleted() {
latch.countDown();
}
@Override
public void onError(Throwable e) {
latch.countDown();
}
@Override
public void onNext(Integer i) {
//do nothing
}
});
try {
latch.await(3, TimeUnit.SECONDS);
assertion.call(command);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (isSuccess) {
try {
o.toList().toBlocking().single();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
} else {
try {
o.toList().toBlocking().single();
fail("Expected a command failure!");
} catch (Exception ex) {
System.out.println("Received expected ex : " + ex);
ex.printStackTrace();
}
}
}
protected void assertSaneHystrixRequestLog(final int numCommands) {
HystrixRequestLog currentRequestLog = HystrixRequestLog.getCurrentRequest();
try {
assertEquals(numCommands, currentRequestLog.getAllExecutedCommands().size());
assertFalse(currentRequestLog.getExecutedCommandsAsString().contains("Executed"));
assertTrue(currentRequestLog.getAllExecutedCommands().iterator().next().getExecutionEvents().size() >= 1);
//Most commands should have 1 execution event, but fallbacks / responses from cache can cause more than 1. They should never have 0
} catch (Throwable ex) {
System.out.println("Problematic Request log : " + currentRequestLog.getExecutedCommandsAsString() + " , expected : " + numCommands);
throw new RuntimeException(ex);
}
}
protected void assertCommandExecutionEvents(HystrixInvokableInfo<?> command, HystrixEventType... expectedEventTypes) {
boolean emitExpected = false;
int expectedEmitCount = 0;
boolean fallbackEmitExpected = false;
int expectedFallbackEmitCount = 0;
List<HystrixEventType> condensedEmitExpectedEventTypes = new ArrayList<HystrixEventType>();
for (HystrixEventType expectedEventType: expectedEventTypes) {
if (expectedEventType.equals(HystrixEventType.EMIT)) {
if (!emitExpected) {
//first EMIT encountered, add it to condensedEmitExpectedEventTypes
condensedEmitExpectedEventTypes.add(HystrixEventType.EMIT);
}
emitExpected = true;
expectedEmitCount++;
} else if (expectedEventType.equals(HystrixEventType.FALLBACK_EMIT)) {
if (!fallbackEmitExpected) {
//first FALLBACK_EMIT encountered, add it to condensedEmitExpectedEventTypes
condensedEmitExpectedEventTypes.add(HystrixEventType.FALLBACK_EMIT);
}
fallbackEmitExpected = true;
expectedFallbackEmitCount++;
} else {
condensedEmitExpectedEventTypes.add(expectedEventType);
}
}
List<HystrixEventType> actualEventTypes = command.getExecutionEvents();
assertEquals(expectedEmitCount, command.getNumberEmissions());
assertEquals(expectedFallbackEmitCount, command.getNumberFallbackEmissions());
assertEquals(condensedEmitExpectedEventTypes, actualEventTypes);
}
/**
* Threadpool with 1 thread, queue of size 1
*/
protected static class SingleThreadedPoolWithQueue implements HystrixThreadPool {
final LinkedBlockingQueue<Runnable> queue;
final ThreadPoolExecutor pool;
private final int rejectionQueueSizeThreshold;
public SingleThreadedPoolWithQueue(int queueSize) {
this(queueSize, 100);
}
public SingleThreadedPoolWithQueue(int queueSize, int rejectionQueueSizeThreshold) {
queue = new LinkedBlockingQueue<Runnable>(queueSize);
pool = new ThreadPoolExecutor(1, 1, 1, TimeUnit.MINUTES, queue);
this.rejectionQueueSizeThreshold = rejectionQueueSizeThreshold;
}
@Override
public ThreadPoolExecutor getExecutor() {
return pool;
}
@Override
public Scheduler getScheduler() {
return new HystrixContextScheduler(HystrixPlugins.getInstance().getConcurrencyStrategy(), this);
}
@Override
public Scheduler getScheduler(Func0<Boolean> shouldInterruptThread) {
return new HystrixContextScheduler(HystrixPlugins.getInstance().getConcurrencyStrategy(), this, shouldInterruptThread);
}
@Override
public void markThreadExecution() {
// not used for this test
}
@Override
public void markThreadCompletion() {
// not used for this test
}
@Override
public void markThreadRejection() {
// not used for this test
}
@Override
public boolean isQueueSpaceAvailable() {
return queue.size() < rejectionQueueSizeThreshold;
}
}
/**
* Threadpool with 1 thread, queue of size 1
*/
protected static class SingleThreadedPoolWithNoQueue implements HystrixThreadPool {
final SynchronousQueue<Runnable> queue;
final ThreadPoolExecutor pool;
public SingleThreadedPoolWithNoQueue() {
queue = new SynchronousQueue<Runnable>();
pool = new ThreadPoolExecutor(1, 1, 1, TimeUnit.MINUTES, queue);
}
@Override
public ThreadPoolExecutor getExecutor() {
return pool;
}
@Override
public Scheduler getScheduler() {
return new HystrixContextScheduler(HystrixPlugins.getInstance().getConcurrencyStrategy(), this);
}
@Override
public Scheduler getScheduler(Func0<Boolean> shouldInterruptThread) {
return new HystrixContextScheduler(HystrixPlugins.getInstance().getConcurrencyStrategy(), this, shouldInterruptThread);
}
@Override
public void markThreadExecution() {
// not used for this test
}
@Override
public void markThreadCompletion() {
// not used for this test
}
@Override
public void markThreadRejection() {
// not used for this test
}
@Override
public boolean isQueueSpaceAvailable() {
return true; //let the thread pool reject
}
}
/**
********************* SEMAPHORE-ISOLATED Execution Hook Tests ***********************************
*/
/**
* Short-circuit? : NO
* Thread/semaphore: SEMAPHORE
* Semaphore Permit reached? : NO
* Execution Result: SUCCESS
*/
@Test
public void testExecutionHookSemaphoreSuccess() {
assertHooksOnSuccess(
new Func0<C>() {
@Override
public C call() {
return getCommand(ExecutionIsolationStrategy.SEMAPHORE, ExecutionResult.SUCCESS, FallbackResult.SUCCESS);
}
},
new Action1<C>() {
@Override
public void call(C command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(1, 0, 1));
assertTrue(hook.executionEventsMatch(1, 0, 1));
assertTrue(hook.fallbackEventsMatch(0, 0, 0));
assertEquals("onStart - !onRunStart - onExecutionStart - onExecutionEmit - !onRunSuccess - !onComplete - onEmit - onExecutionSuccess - onSuccess - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : NO
* Thread/semaphore: SEMAPHORE
* Semaphore Permit reached? : NO
* Execution Result: synchronous HystrixBadRequestException
*/
@Test
public void testExecutionHookSemaphoreBadRequestException() {
assertHooksOnFailure(
new Func0<C>() {
@Override
public C call() {
return getCommand(ExecutionIsolationStrategy.SEMAPHORE, ExecutionResult.BAD_REQUEST, FallbackResult.SUCCESS);
}
},
new Action1<C>() {
@Override
public void call(C command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 1, 0));
assertTrue(hook.fallbackEventsMatch(0, 0, 0));
assertEquals(HystrixBadRequestException.class, hook.getCommandException().getClass());
assertEquals(HystrixBadRequestException.class, hook.getExecutionException().getClass());
assertEquals("onStart - !onRunStart - onExecutionStart - onExecutionError - !onRunError - onError - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : NO
* Thread/semaphore: SEMAPHORE
* Semaphore Permit reached? : NO
* Execution Result: synchronous HystrixRuntimeException
* Fallback: UnsupportedOperationException
*/
@Test
public void testExecutionHookSemaphoreExceptionNoFallback() {
assertHooksOnFailure(
new Func0<C>() {
@Override
public C call() {
return getCommand(ExecutionIsolationStrategy.SEMAPHORE, ExecutionResult.FAILURE, FallbackResult.UNIMPLEMENTED);
}
},
new Action1<C>() {
@Override
public void call(C command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 1, 0));
assertTrue(hook.fallbackEventsMatch(0, 0, 0));
assertEquals(RuntimeException.class, hook.getCommandException().getClass());
assertEquals(RuntimeException.class, hook.getExecutionException().getClass());
assertNull(hook.getFallbackException());
assertEquals("onStart - !onRunStart - onExecutionStart - onExecutionError - !onRunError - onError - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : NO
* Thread/semaphore: SEMAPHORE
* Semaphore Permit reached? : NO
* Execution Result: synchronous HystrixRuntimeException
* Fallback: SUCCESS
*/
@Test
public void testExecutionHookSemaphoreExceptionSuccessfulFallback() {
assertHooksOnSuccess(
new Func0<C>() {
@Override
public C call() {
return getCommand(ExecutionIsolationStrategy.SEMAPHORE, ExecutionResult.FAILURE, FallbackResult.SUCCESS);
}
},
new Action1<C>() {
@Override
public void call(C command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(1, 0, 1));
assertTrue(hook.executionEventsMatch(0, 1, 0));
assertTrue(hook.fallbackEventsMatch(1, 0, 1));
assertEquals(RuntimeException.class, hook.getExecutionException().getClass());
assertEquals("onStart - !onRunStart - onExecutionStart - onExecutionError - !onRunError - onFallbackStart - onFallbackEmit - !onFallbackSuccess - !onComplete - onEmit - onFallbackSuccess - onSuccess - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : NO
* Thread/semaphore: SEMAPHORE
* Semaphore Permit reached? : NO
* Execution Result: synchronous HystrixRuntimeException
* Fallback: synchronous HystrixRuntimeException
*/
@Test
public void testExecutionHookSemaphoreExceptionUnsuccessfulFallback() {
assertHooksOnFailure(
new Func0<C>() {
@Override
public C call() {
return getCommand(ExecutionIsolationStrategy.SEMAPHORE, ExecutionResult.FAILURE, FallbackResult.FAILURE);
}
},
new Action1<C>() {
@Override
public void call(C command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 1, 0));
assertTrue(hook.fallbackEventsMatch(0, 1, 0));
assertEquals(RuntimeException.class, hook.getCommandException().getClass());
assertEquals(RuntimeException.class, hook.getExecutionException().getClass());
assertEquals(RuntimeException.class, hook.getFallbackException().getClass());
assertEquals("onStart - !onRunStart - onExecutionStart - onExecutionError - !onRunError - onFallbackStart - onFallbackError - onError - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : NO
* Thread/semaphore: SEMAPHORE
* Semaphore Permit reached? : YES
* Fallback: UnsupportedOperationException
*/
@Test
public void testExecutionHookSemaphoreRejectedNoFallback() {
assertHooksOnFailFast(
new Func0<C>() {
@Override
public C call() {
AbstractCommand.TryableSemaphore semaphore = new AbstractCommand.TryableSemaphoreActual(HystrixProperty.Factory.asProperty(2));
final C cmd1 = getLatentCommand(ExecutionIsolationStrategy.SEMAPHORE, ExecutionResult.SUCCESS, 500, FallbackResult.UNIMPLEMENTED, semaphore);
final C cmd2 = getLatentCommand(ExecutionIsolationStrategy.SEMAPHORE, ExecutionResult.SUCCESS, 500, FallbackResult.UNIMPLEMENTED, semaphore);
//saturate the semaphore
new Thread() {
@Override
public void run() {
cmd1.observe();
}
}.start();
new Thread() {
@Override
public void run() {
cmd2.observe();
}
}.start();
try {
//give the saturating threads a chance to run before we run the command we want to get rejected
Thread.sleep(200);
} catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
return getLatentCommand(ExecutionIsolationStrategy.SEMAPHORE, ExecutionResult.SUCCESS, 500, FallbackResult.UNIMPLEMENTED, semaphore);
}
},
new Action1<C>() {
@Override
public void call(C command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 0, 0));
assertTrue(hook.fallbackEventsMatch(0, 0, 0));
assertEquals(RuntimeException.class, hook.getCommandException().getClass());
assertNull(hook.getFallbackException());
assertEquals("onStart - onError - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : NO
* Thread/semaphore: SEMAPHORE
* Semaphore Permit reached? : YES
* Fallback: SUCCESS
*/
@Test
public void testExecutionHookSemaphoreRejectedSuccessfulFallback() {
assertHooksOnSuccess(
new Func0<C>() {
@Override
public C call() {
AbstractCommand.TryableSemaphore semaphore = new AbstractCommand.TryableSemaphoreActual(HystrixProperty.Factory.asProperty(2));
final C cmd1 = getLatentCommand(ExecutionIsolationStrategy.SEMAPHORE, ExecutionResult.SUCCESS, 1500, FallbackResult.SUCCESS, semaphore);
final C cmd2 = getLatentCommand(ExecutionIsolationStrategy.SEMAPHORE, ExecutionResult.SUCCESS, 1500, FallbackResult.SUCCESS, semaphore);
//saturate the semaphore
new Thread() {
@Override
public void run() {
cmd1.observe();
}
}.start();
new Thread() {
@Override
public void run() {
cmd2.observe();
}
}.start();
try {
//give the saturating threads a chance to run before we run the command we want to get rejected
Thread.sleep(200);
} catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
return getLatentCommand(ExecutionIsolationStrategy.SEMAPHORE, ExecutionResult.SUCCESS, 500, FallbackResult.SUCCESS, semaphore);
}
},
new Action1<C>() {
@Override
public void call(C command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(1, 0, 1));
assertTrue(hook.executionEventsMatch(0, 0, 0));
assertTrue(hook.fallbackEventsMatch(1, 0, 1));
assertEquals("onStart - onFallbackStart - onFallbackEmit - !onFallbackSuccess - !onComplete - onEmit - onFallbackSuccess - onSuccess - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : NO
* Thread/semaphore: SEMAPHORE
* Semaphore Permit reached? : YES
* Fallback: synchronous HystrixRuntimeException
*/
@Test
public void testExecutionHookSemaphoreRejectedUnsuccessfulFallback() {
assertHooksOnFailFast(
new Func0<C>() {
@Override
public C call() {
AbstractCommand.TryableSemaphore semaphore = new AbstractCommand.TryableSemaphoreActual(HystrixProperty.Factory.asProperty(2));
final C cmd1 = getLatentCommand(ExecutionIsolationStrategy.SEMAPHORE, ExecutionResult.SUCCESS, 500, FallbackResult.FAILURE, semaphore);
final C cmd2 = getLatentCommand(ExecutionIsolationStrategy.SEMAPHORE, ExecutionResult.SUCCESS, 500, FallbackResult.FAILURE, semaphore);
//saturate the semaphore
new Thread() {
@Override
public void run() {
cmd1.observe();
}
}.start();
new Thread() {
@Override
public void run() {
cmd2.observe();
}
}.start();
try {
//give the saturating threads a chance to run before we run the command we want to get rejected
Thread.sleep(200);
} catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
return getLatentCommand(ExecutionIsolationStrategy.SEMAPHORE, ExecutionResult.SUCCESS, 500, FallbackResult.FAILURE, semaphore);
}
},
new Action1<C>() {
@Override
public void call(C command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 0, 0));
assertTrue(hook.fallbackEventsMatch(0, 1, 0));
assertEquals(RuntimeException.class, hook.getCommandException().getClass());
assertEquals(RuntimeException.class, hook.getFallbackException().getClass());
assertEquals("onStart - onFallbackStart - onFallbackError - onError - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : YES
* Thread/semaphore: SEMAPHORE
* Fallback: UnsupportedOperationException
*/
@Test
public void testExecutionHookSemaphoreShortCircuitNoFallback() {
assertHooksOnFailFast(
new Func0<C>() {
@Override
public C call() {
return getCircuitOpenCommand(ExecutionIsolationStrategy.SEMAPHORE, FallbackResult.UNIMPLEMENTED);
}
},
new Action1<C>() {
@Override
public void call(C command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 0, 0));
assertTrue(hook.fallbackEventsMatch(0, 0, 0));
assertEquals(RuntimeException.class, hook.getCommandException().getClass());
assertNull(hook.getFallbackException());
assertEquals("onStart - onError - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : YES
* Thread/semaphore: SEMAPHORE
* Fallback: SUCCESS
*/
@Test
public void testExecutionHookSemaphoreShortCircuitSuccessfulFallback() {
assertHooksOnSuccess(
new Func0<C>() {
@Override
public C call() {
return getCircuitOpenCommand(ExecutionIsolationStrategy.SEMAPHORE, FallbackResult.SUCCESS);
}
},
new Action1<C>() {
@Override
public void call(C command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(1, 0, 1));
assertTrue(hook.executionEventsMatch(0, 0, 0));
assertTrue(hook.fallbackEventsMatch(1, 0, 1));
assertEquals("onStart - onFallbackStart - onFallbackEmit - !onFallbackSuccess - !onComplete - onEmit - onFallbackSuccess - onSuccess - ", hook.executionSequence.toString());
}
});
}
/**
* Short-circuit? : YES
* Thread/semaphore: SEMAPHORE
* Fallback: synchronous HystrixRuntimeException
*/
@Test
public void testExecutionHookSemaphoreShortCircuitUnsuccessfulFallback() {
assertHooksOnFailFast(
new Func0<C>() {
@Override
public C call() {
return getCircuitOpenCommand(ExecutionIsolationStrategy.SEMAPHORE, FallbackResult.FAILURE);
}
},
new Action1<C>() {
@Override
public void call(C command) {
TestableExecutionHook hook = command.getBuilder().executionHook;
assertTrue(hook.commandEmissionsMatch(0, 1, 0));
assertTrue(hook.executionEventsMatch(0, 0, 0));
assertTrue(hook.fallbackEventsMatch(0, 1, 0));
assertEquals(RuntimeException.class, hook.getCommandException().getClass());
assertEquals(RuntimeException.class, hook.getFallbackException().getClass());
assertEquals("onStart - onFallbackStart - onFallbackError - onError - ", hook.executionSequence.toString());
}
});
}
/**
********************* END SEMAPHORE-ISOLATED Execution Hook Tests ***********************************
*/
/**
* Abstract methods defining a way to instantiate each of the described commands.
* {@link HystrixCommandTest} and {@link HystrixObservableCommandTest} should each provide concrete impls for
* {@link HystrixCommand}s and {@link} HystrixObservableCommand}s, respectively.
*/
C getCommand(ExecutionIsolationStrategy isolationStrategy, ExecutionResult executionResult) {
return getCommand(isolationStrategy, executionResult, FallbackResult.UNIMPLEMENTED);
}
C getCommand(ExecutionIsolationStrategy isolationStrategy, ExecutionResult executionResult, int executionLatency) {
return getCommand(isolationStrategy, executionResult, executionLatency, FallbackResult.UNIMPLEMENTED);
}
C getCommand(ExecutionIsolationStrategy isolationStrategy, ExecutionResult executionResult, FallbackResult fallbackResult) {
return getCommand(isolationStrategy, executionResult, 0, fallbackResult);
}
C getCommand(ExecutionIsolationStrategy isolationStrategy, ExecutionResult executionResult, int executionLatency, FallbackResult fallbackResult) {
return getCommand(isolationStrategy, executionResult, executionLatency, fallbackResult, 0, new HystrixCircuitBreakerTest.TestCircuitBreaker(), null, (executionLatency * 2) + 200, CacheEnabled.NO, "foo", 10, 10);
}
C getCommand(ExecutionIsolationStrategy isolationStrategy, ExecutionResult executionResult, int executionLatency, FallbackResult fallbackResult, int timeout) {
return getCommand(isolationStrategy, executionResult, executionLatency, fallbackResult, 0, new HystrixCircuitBreakerTest.TestCircuitBreaker(), null, timeout, CacheEnabled.NO, "foo", 10, 10);
}
C getCommand(ExecutionIsolationStrategy isolationStrategy, ExecutionResult executionResult, int executionLatency, FallbackResult fallbackResult, int fallbackLatency, HystrixCircuitBreakerTest.TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int timeout, CacheEnabled cacheEnabled, Object value, int executionSemaphoreCount, int fallbackSemaphoreCount) {
return getCommand(isolationStrategy, executionResult, executionLatency, fallbackResult, fallbackLatency, circuitBreaker, threadPool, timeout, cacheEnabled, value, executionSemaphoreCount, fallbackSemaphoreCount, false);
}
C getCommand(HystrixCommandKey key, ExecutionIsolationStrategy isolationStrategy, ExecutionResult executionResult, int executionLatency, FallbackResult fallbackResult, int fallbackLatency, HystrixCircuitBreakerTest.TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int timeout, CacheEnabled cacheEnabled, Object value, int executionSemaphoreCount, int fallbackSemaphoreCount) {
AbstractCommand.TryableSemaphoreActual executionSemaphore = new AbstractCommand.TryableSemaphoreActual(HystrixProperty.Factory.asProperty(executionSemaphoreCount));
AbstractCommand.TryableSemaphoreActual fallbackSemaphore = new AbstractCommand.TryableSemaphoreActual(HystrixProperty.Factory.asProperty(fallbackSemaphoreCount));
return getCommand(key, isolationStrategy, executionResult, executionLatency, fallbackResult, fallbackLatency, circuitBreaker, threadPool, timeout, cacheEnabled, value, executionSemaphore, fallbackSemaphore, false);
}
C getCommand(ExecutionIsolationStrategy isolationStrategy, ExecutionResult executionResult, int executionLatency, FallbackResult fallbackResult, int fallbackLatency, HystrixCircuitBreakerTest.TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int timeout, CacheEnabled cacheEnabled, Object value, int executionSemaphoreCount, int fallbackSemaphoreCount, boolean circuitBreakerDisabled) {
AbstractCommand.TryableSemaphoreActual executionSemaphore = new AbstractCommand.TryableSemaphoreActual(HystrixProperty.Factory.asProperty(executionSemaphoreCount));
AbstractCommand.TryableSemaphoreActual fallbackSemaphore = new AbstractCommand.TryableSemaphoreActual(HystrixProperty.Factory.asProperty(fallbackSemaphoreCount));
return getCommand(isolationStrategy, executionResult, executionLatency, fallbackResult, fallbackLatency, circuitBreaker, threadPool, timeout, cacheEnabled, value, executionSemaphore, fallbackSemaphore, circuitBreakerDisabled);
}
C getCommand(ExecutionIsolationStrategy isolationStrategy, ExecutionResult executionResult, int executionLatency, FallbackResult fallbackResult, int fallbackLatency, HystrixCircuitBreakerTest.TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int timeout, CacheEnabled cacheEnabled, Object value, int executionSemaphoreCount, AbstractCommand.TryableSemaphore fallbackSemaphore, boolean circuitBreakerDisabled) {
AbstractCommand.TryableSemaphoreActual executionSemaphore = new AbstractCommand.TryableSemaphoreActual(HystrixProperty.Factory.asProperty(executionSemaphoreCount));
return getCommand(isolationStrategy, executionResult, executionLatency, fallbackResult, fallbackLatency, circuitBreaker, threadPool, timeout, cacheEnabled, value, executionSemaphore, fallbackSemaphore, circuitBreakerDisabled);
}
abstract C getCommand(ExecutionIsolationStrategy isolationStrategy, ExecutionResult executionResult, int executionLatency, FallbackResult fallbackResult, int fallbackLatency, HystrixCircuitBreakerTest.TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int timeout, CacheEnabled cacheEnabled, Object value, AbstractCommand.TryableSemaphore executionSemaphore, AbstractCommand.TryableSemaphore fallbackSemaphore, boolean circuitBreakerDisabled);
abstract C getCommand(HystrixCommandKey commandKey, ExecutionIsolationStrategy isolationStrategy, ExecutionResult executionResult, int executionLatency, FallbackResult fallbackResult, int fallbackLatency, HystrixCircuitBreakerTest.TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int timeout, CacheEnabled cacheEnabled, Object value, AbstractCommand.TryableSemaphore executionSemaphore, AbstractCommand.TryableSemaphore fallbackSemaphore, boolean circuitBreakerDisabled);
C getLatentCommand(ExecutionIsolationStrategy isolationStrategy, ExecutionResult executionResult, int executionLatency, FallbackResult fallbackResult, int timeout) {
return getCommand(isolationStrategy, executionResult, executionLatency, fallbackResult, 0, new HystrixCircuitBreakerTest.TestCircuitBreaker(), null, timeout, CacheEnabled.NO, "foo", 10, 10);
}
C getLatentCommand(ExecutionIsolationStrategy isolationStrategy, ExecutionResult executionResult, int executionLatency, FallbackResult fallbackResult, HystrixCircuitBreakerTest.TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int timeout) {
return getCommand(isolationStrategy, executionResult, executionLatency, fallbackResult, 0, circuitBreaker, threadPool, timeout, CacheEnabled.NO, "foo", 10, 10);
}
C getLatentCommand(ExecutionIsolationStrategy isolationStrategy, ExecutionResult executionResult, int executionLatency, FallbackResult fallbackResult, AbstractCommand.TryableSemaphore executionSemaphore) {
AbstractCommand.TryableSemaphoreActual fallbackSemaphore = new AbstractCommand.TryableSemaphoreActual(HystrixProperty.Factory.asProperty(10));
return getCommand(isolationStrategy, executionResult, executionLatency, fallbackResult, 0, new HystrixCircuitBreakerTest.TestCircuitBreaker(), null, (executionLatency * 2) + 200, CacheEnabled.NO, "foo", executionSemaphore, fallbackSemaphore, false);
}
C getCircuitOpenCommand(ExecutionIsolationStrategy isolationStrategy, FallbackResult fallbackResult) {
HystrixCircuitBreakerTest.TestCircuitBreaker openCircuit = new HystrixCircuitBreakerTest.TestCircuitBreaker().setForceShortCircuit(true);
return getCommand(isolationStrategy, ExecutionResult.SUCCESS, 0, fallbackResult, 0, openCircuit, null, 500, CacheEnabled.NO, "foo", 10, 10, false);
}
C getSharedCircuitBreakerCommand(HystrixCommandKey commandKey, ExecutionIsolationStrategy isolationStrategy, FallbackResult fallbackResult, HystrixCircuitBreakerTest.TestCircuitBreaker circuitBreaker) {
return getCommand(commandKey, isolationStrategy, ExecutionResult.FAILURE, 0, fallbackResult, 0, circuitBreaker, null, 500, CacheEnabled.NO, "foo", 10, 10);
}
C getCircuitBreakerDisabledCommand(ExecutionIsolationStrategy isolationStrategy, ExecutionResult executionResult) {
return getCommand(isolationStrategy, executionResult, 0, FallbackResult.UNIMPLEMENTED, 0, new HystrixCircuitBreakerTest.TestCircuitBreaker(), null, 500, CacheEnabled.NO, "foo", 10, 10, true);
}
C getRecoverableErrorCommand(ExecutionIsolationStrategy isolationStrategy, FallbackResult fallbackResult) {
return getCommand(isolationStrategy, ExecutionResult.RECOVERABLE_ERROR, 0, fallbackResult);
}
C getUnrecoverableErrorCommand(ExecutionIsolationStrategy isolationStrategy, FallbackResult fallbackResult) {
return getCommand(isolationStrategy, ExecutionResult.UNRECOVERABLE_ERROR, 0, fallbackResult);
}
}
| 4,572 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/HystrixCommandTestWithCustomConcurrencyStrategy.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix;
import com.netflix.hystrix.strategy.HystrixPlugins;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariable;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableDefault;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableLifecycle;
import com.netflix.hystrix.strategy.properties.HystrixPropertiesFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.Callable;
import static org.junit.Assert.*;
public class HystrixCommandTestWithCustomConcurrencyStrategy {
@Before
public void init() {
HystrixPlugins.reset();
}
@After
public void reset() {
HystrixRequestContext.setContextOnCurrentThread(null);
HystrixPropertiesFactory.reset();
HystrixPlugins.reset();
}
/**
* HystrixConcurrencyStrategy
** useDefaultRequestContext : true
* HystrixCommand
** useRequestCache : true
** useRequestLog : true
*
* OUTCOME: RequestLog set up properly in command
*/
@Test
public void testCommandRequiresContextConcurrencyStrategyProvidesItContextSetUpCorrectly() {
HystrixConcurrencyStrategy strategy = new CustomConcurrencyStrategy(true);
HystrixPlugins.getInstance().registerConcurrencyStrategy(strategy);
//context is set up properly
HystrixRequestContext context = HystrixRequestContext.initializeContext();
HystrixCommand<Boolean> cmd = new TestCommand(true, true);
assertTrue(cmd.execute());
printRequestLog();
assertNotNull(HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertNotNull(cmd.currentRequestLog);
context.shutdown();
}
/**
* HystrixConcurrencyStrategy
** useDefaultRequestContext : true
* HystrixCommand
** useRequestCache : true
** useRequestLog : true
*
* OUTCOME: RequestLog not set up properly in command, static access is null
*/
@Test
public void testCommandRequiresContextConcurrencyStrategyProvidesItContextLeftUninitialized() {
HystrixConcurrencyStrategy strategy = new CustomConcurrencyStrategy(true);
HystrixPlugins.getInstance().registerConcurrencyStrategy(strategy);
//context is not set up
HystrixRequestContext.setContextOnCurrentThread(null);
HystrixCommand<Boolean> cmd = new TestCommand(true, true);
assertTrue(cmd.execute()); //command execution not affected by missing context
printRequestLog();
assertNull(HystrixRequestLog.getCurrentRequest());
assertNull(HystrixRequestLog.getCurrentRequest(strategy));
assertNull(cmd.currentRequestLog);
}
/**
* HystrixConcurrencyStrategy
** useDefaultRequestContext : false
* HystrixCommand
** useRequestCache : true
** useRequestLog : true
*
* OUTCOME: RequestLog not set up in command, not available statically
*/
@Test
public void testCommandRequiresContextConcurrencyStrategyDoesNotProvideItContextSetUpCorrectly() {
HystrixConcurrencyStrategy strategy = new CustomConcurrencyStrategy(false);
HystrixPlugins.getInstance().registerConcurrencyStrategy(strategy);
//context is set up properly
HystrixRequestContext context = HystrixRequestContext.initializeContext();
HystrixCommand<Boolean> cmd = new TestCommand(true, true);
assertTrue(cmd.execute());
printRequestLog();
assertNull(HystrixRequestLog.getCurrentRequest());
assertNull(HystrixRequestLog.getCurrentRequest(strategy));
assertNull(cmd.currentRequestLog);
context.shutdown();
}
/**
* HystrixConcurrencyStrategy
** useDefaultRequestContext : false
* HystrixCommand
** useRequestCache : true
** useRequestLog : true
*
* OUTCOME: RequestLog not set up in command, not available statically
*/
@Test
public void testCommandRequiresContextConcurrencyStrategyDoesNotProvideItContextLeftUninitialized() {
HystrixConcurrencyStrategy strategy = new CustomConcurrencyStrategy(false);
HystrixPlugins.getInstance().registerConcurrencyStrategy(strategy);
//context is not set up
HystrixRequestContext.setContextOnCurrentThread(null);
HystrixCommand<Boolean> cmd = new TestCommand(true, true);
assertTrue(cmd.execute()); //command execution not affected by missing context
printRequestLog();
assertNull(HystrixRequestLog.getCurrentRequest());
assertNull(HystrixRequestLog.getCurrentRequest(strategy));
assertNull(cmd.currentRequestLog);
}
/**
* HystrixConcurrencyStrategy
** useDefaultRequestContext : true
* HystrixCommand
** useRequestCache : false
** useRequestLog : false
*
* OUTCOME: RequestLog not set up in command, static access works properly
*/
@Test
public void testCommandDoesNotRequireContextConcurrencyStrategyProvidesItContextSetUpCorrectly() {
HystrixConcurrencyStrategy strategy = new CustomConcurrencyStrategy(true);
HystrixPlugins.getInstance().registerConcurrencyStrategy(strategy);
//context is set up properly
HystrixRequestContext context = HystrixRequestContext.initializeContext();
HystrixCommand<Boolean> cmd = new TestCommand(false, false);
assertTrue(cmd.execute());
printRequestLog();
assertNotNull(HystrixRequestLog.getCurrentRequest());
assertNotNull(HystrixRequestLog.getCurrentRequest(strategy));
assertNull(cmd.currentRequestLog);
context.shutdown();
}
/**
* HystrixConcurrencyStrategy
** useDefaultRequestContext : true
* HystrixCommand
** useRequestCache : false
** useRequestLog : false
*
* OUTCOME: RequestLog not set up in command, static access is null
*/
@Test
public void testCommandDoesNotRequireContextConcurrencyStrategyProvidesItContextLeftUninitialized() {
HystrixConcurrencyStrategy strategy = new CustomConcurrencyStrategy(true);
HystrixPlugins.getInstance().registerConcurrencyStrategy(strategy);
//context is not set up
HystrixRequestContext.setContextOnCurrentThread(null);
HystrixCommand<Boolean> cmd = new TestCommand(false, false);
assertTrue(cmd.execute()); //command execution not affected by missing context
printRequestLog();
assertNull(HystrixRequestLog.getCurrentRequest());
assertNull(HystrixRequestLog.getCurrentRequest(strategy));
assertNull(cmd.currentRequestLog);
}
/**
* HystrixConcurrencyStrategy
** useDefaultRequestContext : false
* HystrixCommand
** useRequestCache : false
** useRequestLog : false
*
* OUTCOME: RequestLog not set up in command, not available statically
*/
@Test
public void testCommandDoesNotRequireContextConcurrencyStrategyDoesNotProvideItContextSetUpCorrectly() {
HystrixConcurrencyStrategy strategy = new CustomConcurrencyStrategy(false);
HystrixPlugins.getInstance().registerConcurrencyStrategy(strategy);
//context is set up properly
HystrixRequestContext context = HystrixRequestContext.initializeContext();
HystrixCommand<Boolean> cmd = new TestCommand(true, true);
assertTrue(cmd.execute());
printRequestLog();
assertNull(HystrixRequestLog.getCurrentRequest());
assertNull(HystrixRequestLog.getCurrentRequest(strategy));
assertNull(cmd.currentRequestLog);
context.shutdown();
}
/**
* HystrixConcurrencyStrategy
** useDefaultRequestContext : false
* HystrixCommand
** useRequestCache : false
** useRequestLog : false
*
* OUTCOME: RequestLog not set up in command, not available statically
*/
@Test
public void testCommandDoesNotRequireContextConcurrencyStrategyDoesNotProvideItContextLeftUninitialized() {
HystrixConcurrencyStrategy strategy = new CustomConcurrencyStrategy(false);
HystrixPlugins.getInstance().registerConcurrencyStrategy(strategy);
//context is not set up
HystrixRequestContext.setContextOnCurrentThread(null);
HystrixCommand<Boolean> cmd = new TestCommand(true, true);
assertTrue(cmd.execute()); //command execution unaffected by missing context
printRequestLog();
assertNull(HystrixRequestLog.getCurrentRequest());
assertNull(HystrixRequestLog.getCurrentRequest(strategy));
assertNull(cmd.currentRequestLog);
}
public static class TestCommand extends HystrixCommand<Boolean> {
public TestCommand(boolean cacheEnabled, boolean logEnabled) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("TEST")).andCommandPropertiesDefaults(new HystrixCommandProperties.Setter().withRequestCacheEnabled(cacheEnabled).withRequestLogEnabled(logEnabled)));
}
@Override
protected Boolean run() throws Exception {
return true;
}
}
private static void printRequestLog() {
HystrixRequestLog currentLog = HystrixRequestLog.getCurrentRequest();
if (currentLog != null) {
System.out.println("RequestLog contents : " + currentLog.getExecutedCommandsAsString());
} else {
System.out.println("<NULL> HystrixRequestLog");
}
}
public static class CustomConcurrencyStrategy extends HystrixConcurrencyStrategy {
private final boolean useDefaultRequestContext;
public CustomConcurrencyStrategy(boolean useDefaultRequestContext) {
this.useDefaultRequestContext = useDefaultRequestContext;
}
@Override
public <T> Callable<T> wrapCallable(Callable<T> callable) {
return new LoggingCallable<T>(callable);
}
@Override
public <T> HystrixRequestVariable<T> getRequestVariable(HystrixRequestVariableLifecycle<T> rv) {
if (useDefaultRequestContext) {
//this is the default RequestVariable implementation that requires a HystrixRequestContext
return super.getRequestVariable(rv);
} else {
//this ignores the HystrixRequestContext
return new HystrixRequestVariableDefault<T>() {
@Override
public T initialValue() {
return null;
}
@Override
public T get() {
return null;
}
@Override
public void set(T value) {
//do nothing
}
@Override
public void remove() {
//do nothing
}
@Override
public void shutdown(T value) {
//do nothing
}
};
}
}
}
public static class LoggingCallable<T> implements Callable<T> {
private final Callable<T> callable;
public LoggingCallable(Callable<T> callable) {
this.callable = callable;
}
@Override
public T call() throws Exception {
System.out.println("********start call()");
return callable.call();
}
}
}
| 4,573 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/HystrixThreadPoolPropertiesTest.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.hystrix;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Test;
import com.netflix.config.ConfigurationManager;
import com.netflix.hystrix.strategy.properties.HystrixProperty;
public class HystrixThreadPoolPropertiesTest {
/**
* Base properties for unit testing.
*/
/* package */static HystrixThreadPoolProperties.Setter getUnitTestPropertiesBuilder() {
return HystrixThreadPoolProperties.Setter()
.withCoreSize(10)// core size of thread pool
.withMaximumSize(15) //maximum size of thread pool
.withKeepAliveTimeMinutes(1)// minutes to keep a thread alive (though in practice this doesn't get used as by default we set a fixed size)
.withMaxQueueSize(100)// size of queue (but we never allow it to grow this big ... this can't be dynamically changed so we use 'queueSizeRejectionThreshold' to artificially limit and reject)
.withQueueSizeRejectionThreshold(10)// number of items in queue at which point we reject (this can be dyamically changed)
.withMetricsRollingStatisticalWindowInMilliseconds(10000)// milliseconds for rolling number
.withMetricsRollingStatisticalWindowBuckets(10);// number of buckets in rolling number (10 1-second buckets)
}
/**
* Return a static representation of the properties with values from the Builder so that UnitTests can create properties that are not affected by the actual implementations which pick up their
* values dynamically.
*
* @param builder builder for a {@link HystrixThreadPoolProperties}
* @return HystrixThreadPoolProperties
*/
/* package */static HystrixThreadPoolProperties asMock(final HystrixThreadPoolProperties.Setter builder) {
return new HystrixThreadPoolProperties(TestThreadPoolKey.TEST) {
@Override
public HystrixProperty<Integer> coreSize() {
return HystrixProperty.Factory.asProperty(builder.getCoreSize());
}
@Override
public HystrixProperty<Integer> maximumSize() {
return HystrixProperty.Factory.asProperty(builder.getMaximumSize());
}
@Override
public HystrixProperty<Integer> keepAliveTimeMinutes() {
return HystrixProperty.Factory.asProperty(builder.getKeepAliveTimeMinutes());
}
@Override
public HystrixProperty<Integer> maxQueueSize() {
return HystrixProperty.Factory.asProperty(builder.getMaxQueueSize());
}
@Override
public HystrixProperty<Integer> queueSizeRejectionThreshold() {
return HystrixProperty.Factory.asProperty(builder.getQueueSizeRejectionThreshold());
}
@Override
public HystrixProperty<Integer> metricsRollingStatisticalWindowInMilliseconds() {
return HystrixProperty.Factory.asProperty(builder.getMetricsRollingStatisticalWindowInMilliseconds());
}
@Override
public HystrixProperty<Integer> metricsRollingStatisticalWindowBuckets() {
return HystrixProperty.Factory.asProperty(builder.getMetricsRollingStatisticalWindowBuckets());
}
};
}
private static enum TestThreadPoolKey implements HystrixThreadPoolKey {
TEST
}
@After
public void cleanup() {
ConfigurationManager.getConfigInstance().clear();
}
@Test
public void testSetNeitherCoreNorMaximumSizeWithDivergenceDisallowed() {
HystrixThreadPoolProperties properties = new HystrixThreadPoolProperties(TestThreadPoolKey.TEST,
HystrixThreadPoolProperties.Setter()
.withAllowMaximumSizeToDivergeFromCoreSize(false)) {
};
assertEquals(HystrixThreadPoolProperties.default_coreSize, properties.coreSize().get().intValue());
assertEquals(HystrixThreadPoolProperties.default_maximumSize, properties.maximumSize().get().intValue());
assertEquals(HystrixThreadPoolProperties.default_coreSize, (int) properties.actualMaximumSize());
}
@Test
public void testSetNeitherCoreNorMaximumSizeWithDivergenceAllowed() {
HystrixThreadPoolProperties properties = new HystrixThreadPoolProperties(TestThreadPoolKey.TEST,
HystrixThreadPoolProperties.Setter()
.withAllowMaximumSizeToDivergeFromCoreSize(true)) {
};
assertEquals(HystrixThreadPoolProperties.default_coreSize, properties.coreSize().get().intValue());
assertEquals(HystrixThreadPoolProperties.default_maximumSize, properties.maximumSize().get().intValue());
assertEquals(HystrixThreadPoolProperties.default_maximumSize, (int) properties.actualMaximumSize());
}
@Test
public void testSetCoreSizeOnlyWithDivergenceDisallowed() {
HystrixThreadPoolProperties properties = new HystrixThreadPoolProperties(TestThreadPoolKey.TEST,
HystrixThreadPoolProperties.Setter()
.withCoreSize(14)
.withAllowMaximumSizeToDivergeFromCoreSize(false)) {
};
assertEquals(14, properties.coreSize().get().intValue());
assertEquals(HystrixThreadPoolProperties.default_maximumSize, properties.maximumSize().get().intValue());
assertEquals(14, (int) properties.actualMaximumSize());
}
@Test
public void testSetCoreSizeOnlyWithDivergenceAllowed() {
HystrixThreadPoolProperties properties = new HystrixThreadPoolProperties(TestThreadPoolKey.TEST,
HystrixThreadPoolProperties.Setter()
.withCoreSize(14)
.withAllowMaximumSizeToDivergeFromCoreSize(true)) {
};
assertEquals(14, properties.coreSize().get().intValue());
assertEquals(HystrixThreadPoolProperties.default_maximumSize, properties.maximumSize().get().intValue());
assertEquals(14, (int) properties.actualMaximumSize());
}
@Test
public void testSetMaximumSizeOnlyLowerThanDefaultCoreSizeWithDivergenceDisallowed() {
HystrixThreadPoolProperties properties = new HystrixThreadPoolProperties(TestThreadPoolKey.TEST,
HystrixThreadPoolProperties.Setter()
.withMaximumSize(3)
.withAllowMaximumSizeToDivergeFromCoreSize(false)) {
};
assertEquals(HystrixThreadPoolProperties.default_coreSize, properties.coreSize().get().intValue());
assertEquals(3, properties.maximumSize().get().intValue());
assertEquals(HystrixThreadPoolProperties.default_coreSize, (int) properties.actualMaximumSize());
}
@Test
public void testSetMaximumSizeOnlyLowerThanDefaultCoreSizeWithDivergenceAllowed() {
HystrixThreadPoolProperties properties = new HystrixThreadPoolProperties(TestThreadPoolKey.TEST,
HystrixThreadPoolProperties.Setter()
.withMaximumSize(3)
.withAllowMaximumSizeToDivergeFromCoreSize(true)) {
};
assertEquals(HystrixThreadPoolProperties.default_coreSize, properties.coreSize().get().intValue());
assertEquals(3, properties.maximumSize().get().intValue());
assertEquals(HystrixThreadPoolProperties.default_coreSize, (int) properties.actualMaximumSize());
}
@Test
public void testSetMaximumSizeOnlyGreaterThanDefaultCoreSizeWithDivergenceDisallowed() {
HystrixThreadPoolProperties properties = new HystrixThreadPoolProperties(TestThreadPoolKey.TEST,
HystrixThreadPoolProperties.Setter()
.withMaximumSize(21)
.withAllowMaximumSizeToDivergeFromCoreSize(false)) {
};
assertEquals(HystrixThreadPoolProperties.default_coreSize, properties.coreSize().get().intValue());
assertEquals(21, properties.maximumSize().get().intValue());
assertEquals(HystrixThreadPoolProperties.default_coreSize, (int) properties.actualMaximumSize());
}
@Test
public void testSetMaximumSizeOnlyGreaterThanDefaultCoreSizeWithDivergenceAllowed() {
HystrixThreadPoolProperties properties = new HystrixThreadPoolProperties(TestThreadPoolKey.TEST,
HystrixThreadPoolProperties.Setter()
.withMaximumSize(21)
.withAllowMaximumSizeToDivergeFromCoreSize(true)) {
};
assertEquals(HystrixThreadPoolProperties.default_coreSize, properties.coreSize().get().intValue());
assertEquals(21, properties.maximumSize().get().intValue());
assertEquals(21, (int) properties.actualMaximumSize());
}
@Test
public void testSetCoreSizeLessThanMaximumSizeWithDivergenceDisallowed() {
HystrixThreadPoolProperties properties = new HystrixThreadPoolProperties(TestThreadPoolKey.TEST,
HystrixThreadPoolProperties.Setter()
.withCoreSize(2)
.withMaximumSize(8)
.withAllowMaximumSizeToDivergeFromCoreSize(false)) {
};
assertEquals(2, properties.coreSize().get().intValue());
assertEquals(8, properties.maximumSize().get().intValue());
assertEquals(2, (int) properties.actualMaximumSize());
}
@Test
public void testSetCoreSizeLessThanMaximumSizeWithDivergenceAllowed() {
HystrixThreadPoolProperties properties = new HystrixThreadPoolProperties(TestThreadPoolKey.TEST,
HystrixThreadPoolProperties.Setter()
.withCoreSize(2)
.withMaximumSize(8)
.withAllowMaximumSizeToDivergeFromCoreSize(true)) {
};
assertEquals(2, properties.coreSize().get().intValue());
assertEquals(8, properties.maximumSize().get().intValue());
assertEquals(8, (int) properties.actualMaximumSize());
}
@Test
public void testSetCoreSizeEqualToMaximumSizeDivergenceDisallowed() {
HystrixThreadPoolProperties properties = new HystrixThreadPoolProperties(TestThreadPoolKey.TEST,
HystrixThreadPoolProperties.Setter()
.withCoreSize(7)
.withMaximumSize(7)
.withAllowMaximumSizeToDivergeFromCoreSize(false)) {
};
assertEquals(7, properties.coreSize().get().intValue());
assertEquals(7, properties.maximumSize().get().intValue());
assertEquals(7, (int) properties.actualMaximumSize());
}
@Test
public void testSetCoreSizeEqualToMaximumSizeDivergenceAllowed() {
HystrixThreadPoolProperties properties = new HystrixThreadPoolProperties(TestThreadPoolKey.TEST,
HystrixThreadPoolProperties.Setter()
.withCoreSize(7)
.withMaximumSize(7)
.withAllowMaximumSizeToDivergeFromCoreSize(true)) {
};
assertEquals(7, properties.coreSize().get().intValue());
assertEquals(7, properties.maximumSize().get().intValue());
assertEquals(7, (int) properties.actualMaximumSize());
}
@Test
public void testSetCoreSizeGreaterThanMaximumSizeWithDivergenceDisallowed() {
HystrixThreadPoolProperties properties = new HystrixThreadPoolProperties(TestThreadPoolKey.TEST,
HystrixThreadPoolProperties.Setter()
.withCoreSize(12)
.withMaximumSize(8)
.withAllowMaximumSizeToDivergeFromCoreSize(false)) {
};
assertEquals(12, properties.coreSize().get().intValue());
assertEquals(8, properties.maximumSize().get().intValue());
assertEquals(12, (int) properties.actualMaximumSize());
}
@Test
public void testSetCoreSizeGreaterThanMaximumSizeWithDivergenceAllowed() {
HystrixThreadPoolProperties properties = new HystrixThreadPoolProperties(TestThreadPoolKey.TEST,
HystrixThreadPoolProperties.Setter()
.withCoreSize(12)
.withMaximumSize(8)
.withAllowMaximumSizeToDivergeFromCoreSize(true)) {
};
assertEquals(12, properties.coreSize().get().intValue());
assertEquals(8, properties.maximumSize().get().intValue());
assertEquals(12, (int) properties.actualMaximumSize());
}
}
| 4,574 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/NotWrappedByHystrixTestException.java | package com.netflix.hystrix;
import com.netflix.hystrix.exception.ExceptionNotWrappedByHystrix;
public class NotWrappedByHystrixTestException extends Exception implements ExceptionNotWrappedByHystrix {
private static final long serialVersionUID = 1L;
}
| 4,575 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/HystrixThreadPoolTest.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.hamcrest.core.Is.is;
import com.netflix.hystrix.HystrixThreadPool.Factory;
import com.netflix.hystrix.strategy.HystrixPlugins;
import com.netflix.hystrix.strategy.concurrency.*;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisher;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherFactory;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherThreadPool;
import org.junit.Before;
import org.junit.Test;
import rx.Scheduler;
import rx.functions.Action0;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
public class HystrixThreadPoolTest {
@Before
public void setup() {
Hystrix.reset();
}
@Test
public void testShutdown() {
// other unit tests will probably have run before this so get the count
int count = Factory.threadPools.size();
HystrixThreadPool pool = Factory.getInstance(HystrixThreadPoolKey.Factory.asKey("threadPoolFactoryTest"),
HystrixThreadPoolPropertiesTest.getUnitTestPropertiesBuilder());
assertEquals(count + 1, Factory.threadPools.size());
assertFalse(pool.getExecutor().isShutdown());
Factory.shutdown();
// ensure all pools were removed from the cache
assertEquals(0, Factory.threadPools.size());
assertTrue(pool.getExecutor().isShutdown());
}
@Test
public void testShutdownWithWait() {
// other unit tests will probably have run before this so get the count
int count = Factory.threadPools.size();
HystrixThreadPool pool = Factory.getInstance(HystrixThreadPoolKey.Factory.asKey("threadPoolFactoryTest"),
HystrixThreadPoolPropertiesTest.getUnitTestPropertiesBuilder());
assertEquals(count + 1, Factory.threadPools.size());
assertFalse(pool.getExecutor().isShutdown());
Factory.shutdown(1, TimeUnit.SECONDS);
// ensure all pools were removed from the cache
assertEquals(0, Factory.threadPools.size());
assertTrue(pool.getExecutor().isShutdown());
}
private static class HystrixMetricsPublisherThreadPoolContainer implements HystrixMetricsPublisherThreadPool {
private final HystrixThreadPoolMetrics hystrixThreadPoolMetrics;
private HystrixMetricsPublisherThreadPoolContainer(HystrixThreadPoolMetrics hystrixThreadPoolMetrics) {
this.hystrixThreadPoolMetrics = hystrixThreadPoolMetrics;
}
@Override
public void initialize() {
}
public HystrixThreadPoolMetrics getHystrixThreadPoolMetrics() {
return hystrixThreadPoolMetrics;
}
}
@Test
public void ensureThreadPoolInstanceIsTheOneRegisteredWithMetricsPublisherAndThreadPoolCache() throws IllegalAccessException, NoSuchFieldException {
HystrixPlugins.getInstance().registerMetricsPublisher(new HystrixMetricsPublisher() {
@Override
public HystrixMetricsPublisherThreadPool getMetricsPublisherForThreadPool(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolMetrics metrics, HystrixThreadPoolProperties properties) {
return new HystrixMetricsPublisherThreadPoolContainer(metrics);
}
});
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("threadPoolFactoryConcurrencyTest");
HystrixThreadPool poolOne = new HystrixThreadPool.HystrixThreadPoolDefault(
threadPoolKey, HystrixThreadPoolPropertiesTest.getUnitTestPropertiesBuilder());
HystrixThreadPool poolTwo = new HystrixThreadPool.HystrixThreadPoolDefault(
threadPoolKey, HystrixThreadPoolPropertiesTest.getUnitTestPropertiesBuilder());
assertThat(poolOne.getExecutor(), is(poolTwo.getExecutor())); //Now that we get the threadPool from the metrics object, this will always be equal
HystrixMetricsPublisherThreadPoolContainer hystrixMetricsPublisherThreadPool =
(HystrixMetricsPublisherThreadPoolContainer)HystrixMetricsPublisherFactory
.createOrRetrievePublisherForThreadPool(threadPoolKey, null, null);
ThreadPoolExecutor threadPoolExecutor = hystrixMetricsPublisherThreadPool.getHystrixThreadPoolMetrics().getThreadPool();
//assert that both HystrixThreadPools share the same ThreadPoolExecutor as the one in HystrixMetricsPublisherThreadPool
assertTrue(threadPoolExecutor.equals(poolOne.getExecutor()) && threadPoolExecutor.equals(poolTwo.getExecutor()));
assertFalse(threadPoolExecutor.isShutdown());
//Now the HystrixThreadPool ALWAYS has the same reference to the ThreadPoolExecutor so that it no longer matters which
//wins to be inserted into the HystrixThreadPool.Factory.threadPools cache.
}
@Test(timeout = 2500)
public void testUnsubscribeHystrixThreadPool() throws InterruptedException {
// methods are package-private so can't test it somewhere else
HystrixThreadPool pool = Factory.getInstance(HystrixThreadPoolKey.Factory.asKey("threadPoolFactoryTest"),
HystrixThreadPoolPropertiesTest.getUnitTestPropertiesBuilder());
final AtomicBoolean interrupted = new AtomicBoolean();
final CountDownLatch start = new CountDownLatch(1);
final CountDownLatch end = new CountDownLatch(1);
HystrixContextScheduler hcs = new HystrixContextScheduler(HystrixPlugins.getInstance().getConcurrencyStrategy(), pool);
Scheduler.Worker w = hcs.createWorker();
try {
w.schedule(new Action0() {
@Override
public void call() {
start.countDown();
try {
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
interrupted.set(true);
}
} finally {
end.countDown();
}
}
});
start.await();
w.unsubscribe();
end.await();
Factory.shutdown();
assertTrue(interrupted.get());
} finally {
w.unsubscribe();
}
}
}
| 4,576 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/UnsubscribedTasksRequestCacheTest.java | /**
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import com.netflix.hystrix.strategy.HystrixPlugins;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.*;
public class UnsubscribedTasksRequestCacheTest {
private AtomicBoolean encounteredCommandException = new AtomicBoolean(false);
private AtomicInteger numOfExecutions = new AtomicInteger(0);
public class CommandExecutionHook extends HystrixCommandExecutionHook {
@Override
public <T> Exception onError(HystrixInvokable<T> commandInstance, HystrixRuntimeException.FailureType failureType, Exception e) {
e.printStackTrace();
encounteredCommandException.set(true);
return e;
}
}
public class CommandUsingRequestCache extends HystrixCommand<Boolean> {
private final int value;
protected CommandUsingRequestCache(int value) {
super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
this.value = value;
}
@Override
protected Boolean run() {
numOfExecutions.getAndIncrement();
System.out.println(Thread.currentThread().getName() + " run()");
return value == 0 || value % 2 == 0;
}
@Override
protected String getCacheKey() {
return String.valueOf(value);
}
}
@Before
public void init() {
HystrixPlugins.reset();
}
@After
public void reset() {
HystrixPlugins.reset();
}
@Test
public void testOneCommandIsUnsubscribed() throws ExecutionException, InterruptedException {
HystrixPlugins.getInstance().registerCommandExecutionHook(new CommandExecutionHook());
final HystrixRequestContext context = HystrixRequestContext.initializeContext();
final AtomicInteger numCacheResponses = new AtomicInteger(0);
try {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future futureCommand2a = executorService.submit(createCommandRunnable(context, numCacheResponses));
Future futureCommand2b = executorService.submit(createCommandRunnable(context, numCacheResponses));
futureCommand2a.get();
futureCommand2b.get();
assertEquals(1, numCacheResponses.get());
assertEquals(1, numOfExecutions.get());
assertFalse(encounteredCommandException.get());
} finally {
context.shutdown();
}
}
private Runnable createCommandRunnable(final HystrixRequestContext context, final AtomicInteger numCacheResponses) {
return new Runnable() {
public void run() {
HystrixRequestContext.setContextOnCurrentThread(context);
CommandUsingRequestCache command2a = new CommandUsingRequestCache(2);
Future<Boolean> resultCommand2a = command2a.queue();
try {
assertTrue(resultCommand2a.get());
System.out.println(Thread.currentThread() + " " + command2a.isResponseFromCache());
if (command2a.isResponseFromCache()) {
numCacheResponses.getAndIncrement();
}
} catch (Exception e) {
fail("Exception: " + e.getMessage());
}
}
};
}
}
| 4,577 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/HystrixRequestCacheTest.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import org.junit.Test;
import rx.Observable;
import rx.Subscriber;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import rx.Subscription;
import rx.subjects.ReplaySubject;
public class HystrixRequestCacheTest {
@Test
public void testCache() {
HystrixConcurrencyStrategy strategy = HystrixConcurrencyStrategyDefault.getInstance();
HystrixRequestContext context = HystrixRequestContext.initializeContext();
try {
HystrixRequestCache cache1 = HystrixRequestCache.getInstance(HystrixCommandKey.Factory.asKey("command1"), strategy);
cache1.putIfAbsent("valueA", new TestObservable("a1"));
cache1.putIfAbsent("valueA", new TestObservable("a2"));
cache1.putIfAbsent("valueB", new TestObservable("b1"));
HystrixRequestCache cache2 = HystrixRequestCache.getInstance(HystrixCommandKey.Factory.asKey("command2"), strategy);
cache2.putIfAbsent("valueA", new TestObservable("a3"));
assertEquals("a1", cache1.get("valueA").toObservable().toBlocking().last());
assertEquals("b1", cache1.get("valueB").toObservable().toBlocking().last());
assertEquals("a3", cache2.get("valueA").toObservable().toBlocking().last());
assertNull(cache2.get("valueB"));
} catch (Exception e) {
fail("Exception: " + e.getMessage());
e.printStackTrace();
} finally {
context.shutdown();
}
context = HystrixRequestContext.initializeContext();
try {
// with a new context the instance should have nothing in it
HystrixRequestCache cache = HystrixRequestCache.getInstance(HystrixCommandKey.Factory.asKey("command1"), strategy);
assertNull(cache.get("valueA"));
assertNull(cache.get("valueB"));
} finally {
context.shutdown();
}
}
@Test(expected = IllegalStateException.class)
public void testCacheWithoutContext() {
HystrixRequestCache.getInstance(
HystrixCommandKey.Factory.asKey("command1"),
HystrixConcurrencyStrategyDefault.getInstance()
).get("any");
}
@Test
public void testClearCache() {
HystrixConcurrencyStrategy strategy = HystrixConcurrencyStrategyDefault.getInstance();
HystrixRequestContext context = HystrixRequestContext.initializeContext();
try {
HystrixRequestCache cache1 = HystrixRequestCache.getInstance(HystrixCommandKey.Factory.asKey("command1"), strategy);
cache1.putIfAbsent("valueA", new TestObservable("a1"));
assertEquals("a1", cache1.get("valueA").toObservable().toBlocking().last());
cache1.clear("valueA");
assertNull(cache1.get("valueA"));
} catch (Exception e) {
fail("Exception: " + e.getMessage());
e.printStackTrace();
} finally {
context.shutdown();
}
}
@Test
public void testCacheWithoutRequestContext() {
HystrixConcurrencyStrategy strategy = HystrixConcurrencyStrategyDefault.getInstance();
//HystrixRequestContext context = HystrixRequestContext.initializeContext();
try {
HystrixRequestCache cache1 = HystrixRequestCache.getInstance(HystrixCommandKey.Factory.asKey("command1"), strategy);
//this should fail, as there's no HystrixRequestContext instance to place the cache into
cache1.putIfAbsent("valueA", new TestObservable("a1"));
fail("should throw an exception on cache put");
} catch (Exception e) {
//expected
e.printStackTrace();
}
}
private static class TestObservable extends HystrixCachedObservable<String> {
public TestObservable(String arg) {
super(Observable.just(arg));
}
}
}
| 4,578 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/TestableExecutionHook.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import com.netflix.hystrix.exception.HystrixRuntimeException.FailureType;
import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook;
import rx.Notification;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
class TestableExecutionHook extends HystrixCommandExecutionHook {
private static void recordHookCall(StringBuilder sequenceRecorder, String methodName) {
sequenceRecorder.append(methodName).append(" - ");
}
StringBuilder executionSequence = new StringBuilder();
List<Notification<?>> commandEmissions = new ArrayList<Notification<?>>();
List<Notification<?>> executionEmissions = new ArrayList<Notification<?>>();
List<Notification<?>> fallbackEmissions = new ArrayList<Notification<?>>();
public boolean commandEmissionsMatch(int numOnNext, int numOnError, int numOnCompleted) {
return eventsMatch(commandEmissions, numOnNext, numOnError, numOnCompleted);
}
public boolean executionEventsMatch(int numOnNext, int numOnError, int numOnCompleted) {
return eventsMatch(executionEmissions, numOnNext, numOnError, numOnCompleted);
}
public boolean fallbackEventsMatch(int numOnNext, int numOnError, int numOnCompleted) {
return eventsMatch(fallbackEmissions, numOnNext, numOnError, numOnCompleted);
}
private boolean eventsMatch(List<Notification<?>> l, int numOnNext, int numOnError, int numOnCompleted) {
boolean matchFailed = false;
int actualOnNext = 0;
int actualOnError = 0;
int actualOnCompleted = 0;
if (l.size() != numOnNext + numOnError + numOnCompleted) {
System.out.println("Actual : " + l + ", Expected : " + numOnNext + " OnNexts, " + numOnError + " OnErrors, " + numOnCompleted + " OnCompleted");
return false;
}
for (int n = 0; n < numOnNext; n++) {
Notification<?> current = l.get(n);
if (!current.isOnNext()) {
matchFailed = true;
} else {
actualOnNext++;
}
}
for (int e = numOnNext; e < numOnNext + numOnError; e++) {
Notification<?> current = l.get(e);
if (!current.isOnError()) {
matchFailed = true;
} else {
actualOnError++;
}
}
for (int c = numOnNext + numOnError; c < numOnNext + numOnError + numOnCompleted; c++) {
Notification<?> current = l.get(c);
if (!current.isOnCompleted()) {
matchFailed = true;
} else {
actualOnCompleted++;
}
}
if (matchFailed) {
System.out.println("Expected : " + numOnNext + " OnNexts, " + numOnError + " OnErrors, and " + numOnCompleted);
System.out.println("Actual : " + actualOnNext + " OnNexts, " + actualOnError + " OnErrors, and " + actualOnCompleted);
}
return !matchFailed;
}
public Throwable getCommandException() {
return getException(commandEmissions);
}
public Throwable getExecutionException() {
return getException(executionEmissions);
}
public Throwable getFallbackException() {
return getException(fallbackEmissions);
}
private Throwable getException(List<Notification<?>> l) {
for (Notification<?> n: l) {
if (n.isOnError()) {
n.getThrowable().printStackTrace();
return n.getThrowable();
}
}
return null;
}
@Override
public <T> void onStart(HystrixInvokable<T> commandInstance) {
super.onStart(commandInstance);
recordHookCall(executionSequence, "onStart");
}
@Override
public <T> T onEmit(HystrixInvokable<T> commandInstance, T value) {
commandEmissions.add(Notification.createOnNext(value));
recordHookCall(executionSequence, "onEmit");
return super.onEmit(commandInstance, value);
}
@Override
public <T> Exception onError(HystrixInvokable<T> commandInstance, FailureType failureType, Exception e) {
commandEmissions.add(Notification.createOnError(e));
recordHookCall(executionSequence, "onError");
return super.onError(commandInstance, failureType, e);
}
@Override
public <T> void onSuccess(HystrixInvokable<T> commandInstance) {
commandEmissions.add(Notification.createOnCompleted());
recordHookCall(executionSequence, "onSuccess");
super.onSuccess(commandInstance);
}
@Override
public <T> void onThreadStart(HystrixInvokable<T> commandInstance) {
super.onThreadStart(commandInstance);
recordHookCall(executionSequence, "onThreadStart");
}
@Override
public <T> void onThreadComplete(HystrixInvokable<T> commandInstance) {
super.onThreadComplete(commandInstance);
recordHookCall(executionSequence, "onThreadComplete");
}
@Override
public <T> void onExecutionStart(HystrixInvokable<T> commandInstance) {
recordHookCall(executionSequence, "onExecutionStart");
super.onExecutionStart(commandInstance);
}
@Override
public <T> T onExecutionEmit(HystrixInvokable<T> commandInstance, T value) {
executionEmissions.add(Notification.createOnNext(value));
recordHookCall(executionSequence, "onExecutionEmit");
return super.onExecutionEmit(commandInstance, value);
}
@Override
public <T> Exception onExecutionError(HystrixInvokable<T> commandInstance, Exception e) {
executionEmissions.add(Notification.createOnError(e));
recordHookCall(executionSequence, "onExecutionError");
return super.onExecutionError(commandInstance, e);
}
@Override
public <T> void onExecutionSuccess(HystrixInvokable<T> commandInstance) {
executionEmissions.add(Notification.createOnCompleted());
recordHookCall(executionSequence, "onExecutionSuccess");
super.onExecutionSuccess(commandInstance);
}
@Override
public <T> void onFallbackStart(HystrixInvokable<T> commandInstance) {
super.onFallbackStart(commandInstance);
recordHookCall(executionSequence, "onFallbackStart");
}
@Override
public <T> T onFallbackEmit(HystrixInvokable<T> commandInstance, T value) {
fallbackEmissions.add(Notification.createOnNext(value));
recordHookCall(executionSequence, "onFallbackEmit");
return super.onFallbackEmit(commandInstance, value);
}
@Override
public <T> Exception onFallbackError(HystrixInvokable<T> commandInstance, Exception e) {
fallbackEmissions.add(Notification.createOnError(e));
recordHookCall(executionSequence, "onFallbackError");
return super.onFallbackError(commandInstance, e);
}
@Override
public <T> void onFallbackSuccess(HystrixInvokable<T> commandInstance) {
fallbackEmissions.add(Notification.createOnCompleted());
recordHookCall(executionSequence, "onFallbackSuccess");
super.onFallbackSuccess(commandInstance);
}
@Override
public <T> void onCacheHit(HystrixInvokable<T> commandInstance) {
super.onCacheHit(commandInstance);
recordHookCall(executionSequence, "onCacheHit");
}
@Override
public <T> void onUnsubscribe(HystrixInvokable<T> commandInstance) {
super.onUnsubscribe(commandInstance);
recordHookCall(executionSequence, "onUnsubscribe");
}
/**
* DEPRECATED METHODS FOLLOW. The string representation starts with `!` to distinguish
*/
AtomicInteger startExecute = new AtomicInteger();
Object endExecuteSuccessResponse = null;
Exception endExecuteFailureException = null;
HystrixRuntimeException.FailureType endExecuteFailureType = null;
AtomicInteger startRun = new AtomicInteger();
Object runSuccessResponse = null;
Exception runFailureException = null;
AtomicInteger startFallback = new AtomicInteger();
Object fallbackSuccessResponse = null;
Exception fallbackFailureException = null;
AtomicInteger threadStart = new AtomicInteger();
AtomicInteger threadComplete = new AtomicInteger();
AtomicInteger cacheHit = new AtomicInteger();
@Override
public <T> T onFallbackSuccess(HystrixInvokable<T> commandInstance, T response) {
recordHookCall(executionSequence, "!onFallbackSuccess");
return super.onFallbackSuccess(commandInstance, response);
}
@Override
public <T> T onComplete(HystrixInvokable<T> commandInstance, T response) {
recordHookCall(executionSequence, "!onComplete");
return super.onComplete(commandInstance, response);
}
@Override
public <T> void onRunStart(HystrixInvokable<T> commandInstance) {
super.onRunStart(commandInstance);
recordHookCall(executionSequence, "!onRunStart");
}
@Override
public <T> T onRunSuccess(HystrixInvokable<T> commandInstance, T response) {
recordHookCall(executionSequence, "!onRunSuccess");
return super.onRunSuccess(commandInstance, response);
}
@Override
public <T> Exception onRunError(HystrixInvokable<T> commandInstance, Exception e) {
recordHookCall(executionSequence, "!onRunError");
return super.onRunError(commandInstance, e);
}
}
| 4,579 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/HystrixCommandTimeoutConcurrencyTesting.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix;
import org.junit.Test;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import rx.Observable;
import java.util.ArrayList;
import java.util.List;
public class HystrixCommandTimeoutConcurrencyTesting {
private final static int NUM_CONCURRENT_COMMANDS = 30;
@Test
public void testTimeoutRace() throws InterruptedException {
final int NUM_TRIALS = 10;
for (int i = 0; i < NUM_TRIALS; i++) {
List<Observable<String>> observables = new ArrayList<Observable<String>>();
HystrixRequestContext context = null;
try {
context = HystrixRequestContext.initializeContext();
for (int j = 0; j < NUM_CONCURRENT_COMMANDS; j++) {
observables.add(new TestCommand().observe());
}
Observable<String> overall = Observable.merge(observables);
List<String> results = overall.toList().toBlocking().first(); //wait for all commands to complete
for (String s : results) {
if (s == null) {
System.err.println("Received NULL!");
throw new RuntimeException("Received NULL");
}
}
for (HystrixInvokableInfo<?> hi : HystrixRequestLog.getCurrentRequest().getAllExecutedCommands()) {
if (!hi.isResponseTimedOut()) {
System.err.println("Timeout not found in executed command");
throw new RuntimeException("Timeout not found in executed command");
}
if (hi.isResponseTimedOut() && hi.getExecutionEvents().size() == 1) {
System.err.println("Missing fallback status!");
throw new RuntimeException("Missing fallback status on timeout.");
}
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
throw new RuntimeException(e);
} finally {
System.out.println(HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
if (context != null) {
context.shutdown();
}
}
System.out.println("*************** TRIAL " + i + " ******************");
System.out.println();
Thread.sleep(50);
}
Hystrix.reset();
}
public static class TestCommand extends HystrixCommand<String> {
protected TestCommand() {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("testTimeoutConcurrency"))
.andCommandKey(HystrixCommandKey.Factory.asKey("testTimeoutConcurrencyCommand"))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withExecutionTimeoutInMilliseconds(3)
.withCircuitBreakerEnabled(false)
.withFallbackIsolationSemaphoreMaxConcurrentRequests(NUM_CONCURRENT_COMMANDS))
.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
.withCoreSize(NUM_CONCURRENT_COMMANDS)
.withMaxQueueSize(NUM_CONCURRENT_COMMANDS)
.withQueueSizeRejectionThreshold(NUM_CONCURRENT_COMMANDS)));
}
@Override
protected String run() throws Exception {
//System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " sleeping");
Thread.sleep(500);
//System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " awake and returning");
return "hello";
}
@Override
protected String getFallback() {
return "failed";
}
}
}
| 4,580 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/InspectableBuilder.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix;
public interface InspectableBuilder {
public TestCommandBuilder getBuilder();
public enum CommandKeyForUnitTest implements HystrixCommandKey {
KEY_ONE, KEY_TWO
}
public enum CommandGroupForUnitTest implements HystrixCommandGroupKey {
OWNER_ONE, OWNER_TWO
}
public enum ThreadPoolKeyForUnitTest implements HystrixThreadPoolKey {
THREAD_POOL_ONE, THREAD_POOL_TWO
}
public static class TestCommandBuilder {
HystrixCommandGroupKey owner = CommandGroupForUnitTest.OWNER_ONE;
HystrixCommandKey dependencyKey = null;
HystrixThreadPoolKey threadPoolKey = null;
HystrixCircuitBreaker circuitBreaker;
HystrixThreadPool threadPool = null;
HystrixCommandProperties.Setter commandPropertiesDefaults = HystrixCommandPropertiesTest.getUnitTestPropertiesSetter();
HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults = HystrixThreadPoolPropertiesTest.getUnitTestPropertiesBuilder();
HystrixCommandMetrics metrics;
AbstractCommand.TryableSemaphore fallbackSemaphore = null;
AbstractCommand.TryableSemaphore executionSemaphore = null;
TestableExecutionHook executionHook = new TestableExecutionHook();
TestCommandBuilder(HystrixCommandProperties.ExecutionIsolationStrategy isolationStrategy) {
this.commandPropertiesDefaults = HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(isolationStrategy);
}
TestCommandBuilder setOwner(HystrixCommandGroupKey owner) {
this.owner = owner;
return this;
}
TestCommandBuilder setCommandKey(HystrixCommandKey dependencyKey) {
this.dependencyKey = dependencyKey;
return this;
}
TestCommandBuilder setThreadPoolKey(HystrixThreadPoolKey threadPoolKey) {
this.threadPoolKey = threadPoolKey;
return this;
}
TestCommandBuilder setCircuitBreaker(HystrixCircuitBreakerTest.TestCircuitBreaker circuitBreaker) {
this.circuitBreaker = circuitBreaker;
if (circuitBreaker != null) {
this.metrics = circuitBreaker.metrics;
}
return this;
}
TestCommandBuilder setThreadPool(HystrixThreadPool threadPool) {
this.threadPool = threadPool;
return this;
}
TestCommandBuilder setCommandPropertiesDefaults(HystrixCommandProperties.Setter commandPropertiesDefaults) {
this.commandPropertiesDefaults = commandPropertiesDefaults;
return this;
}
TestCommandBuilder setThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults) {
this.threadPoolPropertiesDefaults = threadPoolPropertiesDefaults;
return this;
}
TestCommandBuilder setMetrics(HystrixCommandMetrics metrics) {
this.metrics = metrics;
return this;
}
TestCommandBuilder setFallbackSemaphore(AbstractCommand.TryableSemaphore fallbackSemaphore) {
this.fallbackSemaphore = fallbackSemaphore;
return this;
}
TestCommandBuilder setExecutionSemaphore(AbstractCommand.TryableSemaphore executionSemaphore) {
this.executionSemaphore = executionSemaphore;
return this;
}
TestCommandBuilder setExecutionHook(TestableExecutionHook executionHook) {
this.executionHook = executionHook;
return this;
}
}
}
| 4,581 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/HystrixRequestLogTest.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix;
import com.hystrix.junit.HystrixRequestContextRule;
import static org.junit.Assert.assertEquals;
import org.junit.Rule;
import org.junit.Test;
import rx.Observable;
public class HystrixRequestLogTest {
private static final String DIGITS_REGEX = "\\[\\d+";
@Rule
public HystrixRequestContextRule ctx = new HystrixRequestContextRule();
@Test
public void testSuccess() {
new TestCommand("A", false, true).execute();
String log = HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString();
// strip the actual count so we can compare reliably
log = log.replaceAll(DIGITS_REGEX, "[");
assertEquals("TestCommand[SUCCESS][ms]", log);
}
@Test
public void testSuccessFromCache() {
// 1 success
new TestCommand("A", false, true).execute();
// 4 success from cache
new TestCommand("A", false, true).execute();
new TestCommand("A", false, true).execute();
new TestCommand("A", false, true).execute();
new TestCommand("A", false, true).execute();
String log = HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString();
// strip the actual count so we can compare reliably
log = log.replaceAll(DIGITS_REGEX, "[");
assertEquals("TestCommand[SUCCESS][ms], TestCommand[SUCCESS, RESPONSE_FROM_CACHE][ms]x4", log);
}
@Test
public void testFailWithFallbackSuccess() {
// 1 failure
new TestCommand("A", true, false).execute();
// 4 failures from cache
new TestCommand("A", true, false).execute();
new TestCommand("A", true, false).execute();
new TestCommand("A", true, false).execute();
new TestCommand("A", true, false).execute();
String log = HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString();
// strip the actual count so we can compare reliably
log = log.replaceAll(DIGITS_REGEX, "[");
assertEquals("TestCommand[FAILURE, FALLBACK_SUCCESS][ms], TestCommand[FAILURE, FALLBACK_SUCCESS, RESPONSE_FROM_CACHE][ms]x4", log);
}
@Test
public void testFailWithFallbackFailure() {
// 1 failure
try {
new TestCommand("A", true, true).execute();
} catch (Exception e) {
}
// 1 failure from cache
try {
new TestCommand("A", true, true).execute();
} catch (Exception e) {
}
String log = HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString();
// strip the actual count so we can compare reliably
log = log.replaceAll(DIGITS_REGEX, "[");
assertEquals("TestCommand[FAILURE, FALLBACK_FAILURE][ms], TestCommand[FAILURE, FALLBACK_FAILURE, RESPONSE_FROM_CACHE][ms]", log);
}
@Test
public void testTimeout() {
Observable<String> result = null;
// 1 timeout
try {
for (int i = 0; i < 1; i++) {
result = new TestCommand("A", false, false, true).observe();
}
} catch (Exception e) {
}
try {
result.toBlocking().single();
} catch (Throwable ex) {
//ex.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis() + " -> done with awaiting all observables");
String log = HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString();
// strip the actual count so we can compare reliably
log = log.replaceAll(DIGITS_REGEX, "[");
assertEquals("TestCommand[TIMEOUT, FALLBACK_MISSING][ms]", log);
}
@Test
public void testManyTimeouts() {
for (int i = 0; i < 10; i++) {
testTimeout();
ctx.reset();
}
}
@Test
public void testMultipleCommands() {
// 1 success
new TestCommand("GetData", "A", false, false).execute();
// 1 success
new TestCommand("PutData", "B", false, false).execute();
// 1 success
new TestCommand("GetValues", "C", false, false).execute();
// 1 success from cache
new TestCommand("GetValues", "C", false, false).execute();
// 1 failure
try {
new TestCommand("A", true, true).execute();
} catch (Exception e) {
}
// 1 failure from cache
try {
new TestCommand("A", true, true).execute();
} catch (Exception e) {
}
String log = HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString();
// strip the actual count so we can compare reliably
log = log.replaceAll(DIGITS_REGEX, "[");
assertEquals("GetData[SUCCESS][ms], PutData[SUCCESS][ms], GetValues[SUCCESS][ms], GetValues[SUCCESS, RESPONSE_FROM_CACHE][ms], TestCommand[FAILURE, FALLBACK_FAILURE][ms], TestCommand[FAILURE, FALLBACK_FAILURE, RESPONSE_FROM_CACHE][ms]", log);
}
@Test
public void testMaxLimit() {
for (int i = 0; i < HystrixRequestLog.MAX_STORAGE; i++) {
new TestCommand("A", false, true).execute();
}
// then execute again some more
for (int i = 0; i < 10; i++) {
new TestCommand("A", false, true).execute();
}
assertEquals(HystrixRequestLog.MAX_STORAGE, HystrixRequestLog.getCurrentRequest().getAllExecutedCommands().size());
}
private static class TestCommand extends HystrixCommand<String> {
private final String value;
private final boolean fail;
private final boolean failOnFallback;
private final boolean timeout;
private final boolean useFallback;
private final boolean useCache;
public TestCommand(String commandName, String value, boolean fail, boolean failOnFallback) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RequestLogTestCommand")).andCommandKey(HystrixCommandKey.Factory.asKey(commandName)));
this.value = value;
this.fail = fail;
this.failOnFallback = failOnFallback;
this.timeout = false;
this.useFallback = true;
this.useCache = true;
}
public TestCommand(String value, boolean fail, boolean failOnFallback) {
super(HystrixCommandGroupKey.Factory.asKey("RequestLogTestCommand"));
this.value = value;
this.fail = fail;
this.failOnFallback = failOnFallback;
this.timeout = false;
this.useFallback = true;
this.useCache = true;
}
public TestCommand(String value, boolean fail, boolean failOnFallback, boolean timeout) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RequestLogTestCommand")).andCommandPropertiesDefaults(new HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(500)));
this.value = value;
this.fail = fail;
this.failOnFallback = failOnFallback;
this.timeout = timeout;
this.useFallback = false;
this.useCache = false;
}
@Override
protected String run() {
System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis());
if (fail) {
throw new RuntimeException("forced failure");
} else if (timeout) {
try {
Thread.sleep(10000);
System.out.println("Woke up from sleep!");
} catch (InterruptedException ex) {
System.out.println(Thread.currentThread().getName() + " Interrupted by timeout");
}
}
return value;
}
@Override
protected String getFallback() {
if (useFallback) {
if (failOnFallback) {
throw new RuntimeException("forced fallback failure");
} else {
return value + "-fallback";
}
} else {
throw new UnsupportedOperationException("no fallback implemented");
}
}
@Override
protected String getCacheKey() {
if (useCache) {
return value;
} else {
return null;
}
}
}
}
| 4,582 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/HystrixCommandPropertiesTest.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Test;
import com.netflix.config.ConfigurationManager;
import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy;
import com.netflix.hystrix.HystrixCommandProperties.Setter;
import com.netflix.hystrix.strategy.properties.HystrixProperty;
public class HystrixCommandPropertiesTest {
/**
* Utility method for creating baseline properties for unit tests.
*/
/* package */static HystrixCommandProperties.Setter getUnitTestPropertiesSetter() {
return new HystrixCommandProperties.Setter()
.withExecutionTimeoutInMilliseconds(1000)// when an execution will be timed out
.withExecutionTimeoutEnabled(true)
.withExecutionIsolationStrategy(ExecutionIsolationStrategy.THREAD) // we want thread execution by default in tests
.withExecutionIsolationThreadInterruptOnTimeout(true)
.withExecutionIsolationThreadInterruptOnFutureCancel(true)
.withCircuitBreakerForceOpen(false) // we don't want short-circuiting by default
.withCircuitBreakerErrorThresholdPercentage(40) // % of 'marks' that must be failed to trip the circuit
.withMetricsRollingStatisticalWindowInMilliseconds(5000)// milliseconds back that will be tracked
.withMetricsRollingStatisticalWindowBuckets(5) // buckets
.withCircuitBreakerRequestVolumeThreshold(0) // in testing we will not have a threshold unless we're specifically testing that feature
.withCircuitBreakerSleepWindowInMilliseconds(5000000) // milliseconds after tripping circuit before allowing retry (by default set VERY long as we want it to effectively never allow a singleTest for most unit tests)
.withCircuitBreakerEnabled(true)
.withRequestLogEnabled(true)
.withExecutionIsolationSemaphoreMaxConcurrentRequests(20)
.withFallbackIsolationSemaphoreMaxConcurrentRequests(10)
.withFallbackEnabled(true)
.withCircuitBreakerForceClosed(false)
.withMetricsRollingPercentileEnabled(true)
.withRequestCacheEnabled(true)
.withMetricsRollingPercentileWindowInMilliseconds(60000)
.withMetricsRollingPercentileWindowBuckets(12)
.withMetricsRollingPercentileBucketSize(1000)
.withMetricsHealthSnapshotIntervalInMilliseconds(100);
}
/**
* Return a static representation of the properties with values from the Builder so that UnitTests can create properties that are not affected by the actual implementations which pick up their
* values dynamically.
*
* @param builder command properties builder
* @return HystrixCommandProperties
*/
/* package */static HystrixCommandProperties asMock(final Setter builder) {
return new HystrixCommandProperties(TestKey.TEST) {
@Override
public HystrixProperty<Boolean> circuitBreakerEnabled() {
return HystrixProperty.Factory.asProperty(builder.getCircuitBreakerEnabled());
}
@Override
public HystrixProperty<Integer> circuitBreakerErrorThresholdPercentage() {
return HystrixProperty.Factory.asProperty(builder.getCircuitBreakerErrorThresholdPercentage());
}
@Override
public HystrixProperty<Boolean> circuitBreakerForceClosed() {
return HystrixProperty.Factory.asProperty(builder.getCircuitBreakerForceClosed());
}
@Override
public HystrixProperty<Boolean> circuitBreakerForceOpen() {
return HystrixProperty.Factory.asProperty(builder.getCircuitBreakerForceOpen());
}
@Override
public HystrixProperty<Integer> circuitBreakerRequestVolumeThreshold() {
return HystrixProperty.Factory.asProperty(builder.getCircuitBreakerRequestVolumeThreshold());
}
@Override
public HystrixProperty<Integer> circuitBreakerSleepWindowInMilliseconds() {
return HystrixProperty.Factory.asProperty(builder.getCircuitBreakerSleepWindowInMilliseconds());
}
@Override
public HystrixProperty<Integer> executionIsolationSemaphoreMaxConcurrentRequests() {
return HystrixProperty.Factory.asProperty(builder.getExecutionIsolationSemaphoreMaxConcurrentRequests());
}
@Override
public HystrixProperty<ExecutionIsolationStrategy> executionIsolationStrategy() {
return HystrixProperty.Factory.asProperty(builder.getExecutionIsolationStrategy());
}
@Override
public HystrixProperty<Boolean> executionIsolationThreadInterruptOnTimeout() {
return HystrixProperty.Factory.asProperty(builder.getExecutionIsolationThreadInterruptOnTimeout());
}
@Override
public HystrixProperty<Boolean> executionIsolationThreadInterruptOnFutureCancel() {
return HystrixProperty.Factory.asProperty(builder.getExecutionIsolationThreadInterruptOnFutureCancel());
}
@Override
public HystrixProperty<String> executionIsolationThreadPoolKeyOverride() {
return HystrixProperty.Factory.nullProperty();
}
@Override
public HystrixProperty<Integer> executionTimeoutInMilliseconds() {
return HystrixProperty.Factory.asProperty(builder.getExecutionTimeoutInMilliseconds());
}
@Override
public HystrixProperty<Boolean> executionTimeoutEnabled() {
return HystrixProperty.Factory.asProperty(builder.getExecutionTimeoutEnabled());
}
@Override
public HystrixProperty<Integer> fallbackIsolationSemaphoreMaxConcurrentRequests() {
return HystrixProperty.Factory.asProperty(builder.getFallbackIsolationSemaphoreMaxConcurrentRequests());
}
@Override
public HystrixProperty<Boolean> fallbackEnabled() {
return HystrixProperty.Factory.asProperty(builder.getFallbackEnabled());
}
@Override
public HystrixProperty<Integer> metricsHealthSnapshotIntervalInMilliseconds() {
return HystrixProperty.Factory.asProperty(builder.getMetricsHealthSnapshotIntervalInMilliseconds());
}
@Override
public HystrixProperty<Integer> metricsRollingPercentileBucketSize() {
return HystrixProperty.Factory.asProperty(builder.getMetricsRollingPercentileBucketSize());
}
@Override
public HystrixProperty<Boolean> metricsRollingPercentileEnabled() {
return HystrixProperty.Factory.asProperty(builder.getMetricsRollingPercentileEnabled());
}
@Override
public HystrixProperty<Integer> metricsRollingPercentileWindow() {
return HystrixProperty.Factory.asProperty(builder.getMetricsRollingPercentileWindowInMilliseconds());
}
@Override
public HystrixProperty<Integer> metricsRollingPercentileWindowBuckets() {
return HystrixProperty.Factory.asProperty(builder.getMetricsRollingPercentileWindowBuckets());
}
@Override
public HystrixProperty<Integer> metricsRollingStatisticalWindowInMilliseconds() {
return HystrixProperty.Factory.asProperty(builder.getMetricsRollingStatisticalWindowInMilliseconds());
}
@Override
public HystrixProperty<Integer> metricsRollingStatisticalWindowBuckets() {
return HystrixProperty.Factory.asProperty(builder.getMetricsRollingStatisticalWindowBuckets());
}
@Override
public HystrixProperty<Boolean> requestCacheEnabled() {
return HystrixProperty.Factory.asProperty(builder.getRequestCacheEnabled());
}
@Override
public HystrixProperty<Boolean> requestLogEnabled() {
return HystrixProperty.Factory.asProperty(builder.getRequestLogEnabled());
}
};
}
// NOTE: We use "unitTestPrefix" as a prefix so we can't end up pulling in external properties that change unit test behavior
public enum TestKey implements HystrixCommandKey {
TEST
}
private static class TestPropertiesCommand extends HystrixCommandProperties {
protected TestPropertiesCommand(HystrixCommandKey key, Setter builder, String propertyPrefix) {
super(key, builder, propertyPrefix);
}
}
@After
public void cleanup() {
ConfigurationManager.getConfigInstance().clear();
}
@Test
public void testBooleanBuilderOverride1() {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST,
new HystrixCommandProperties.Setter().withCircuitBreakerForceClosed(true), "unitTestPrefix");
// the builder override should take precedence over the default
assertEquals(true, properties.circuitBreakerForceClosed().get());
}
@Test
public void testBooleanBuilderOverride2() {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST,
new HystrixCommandProperties.Setter().withCircuitBreakerForceClosed(false), "unitTestPrefix");
// the builder override should take precedence over the default
assertEquals(false, properties.circuitBreakerForceClosed().get());
}
@Test
public void testBooleanCodeDefault() {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST, new HystrixCommandProperties.Setter(), "unitTestPrefix");
assertEquals(HystrixCommandProperties.default_circuitBreakerForceClosed, properties.circuitBreakerForceClosed().get());
}
@Test
public void testBooleanGlobalDynamicOverrideOfCodeDefault() throws Exception {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST, new HystrixCommandProperties.Setter(), "unitTestPrefix");
ConfigurationManager.getConfigInstance().setProperty("unitTestPrefix.command.default.circuitBreaker.forceClosed", true);
// the global dynamic property should take precedence over the default
assertEquals(true, properties.circuitBreakerForceClosed().get());
// cleanup
ConfigurationManager.getConfigInstance().clearProperty("unitTestPrefix.command.default.circuitBreaker.forceClosed");
}
@Test
public void testBooleanInstanceBuilderOverrideOfGlobalDynamicOverride1() throws Exception {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST,
new HystrixCommandProperties.Setter().withCircuitBreakerForceClosed(true), "unitTestPrefix");
ConfigurationManager.getConfigInstance().setProperty("unitTestPrefix.command.default.circuitBreaker.forceClosed", false);
// the builder injected should take precedence over the global dynamic property
assertEquals(true, properties.circuitBreakerForceClosed().get());
// cleanup
ConfigurationManager.getConfigInstance().clearProperty("unitTestPrefix.command.default.circuitBreaker.forceClosed");
}
@Test
public void testBooleanInstanceBuilderOverrideOfGlobalDynamicOverride2() throws Exception {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST,
new HystrixCommandProperties.Setter().withCircuitBreakerForceClosed(false), "unitTestPrefix");
ConfigurationManager.getConfigInstance().setProperty("unitTestPrefix.command.default.circuitBreaker.forceClosed", true);
// the builder injected should take precedence over the global dynamic property
assertEquals(false, properties.circuitBreakerForceClosed().get());
// cleanup
ConfigurationManager.getConfigInstance().clearProperty("unitTestPrefix.command.default.circuitBreaker.forceClosed");
}
@Test
public void testBooleanInstanceDynamicOverrideOfEverything() throws Exception {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST,
new HystrixCommandProperties.Setter().withCircuitBreakerForceClosed(false), "unitTestPrefix");
ConfigurationManager.getConfigInstance().setProperty("unitTestPrefix.command.default.circuitBreaker.forceClosed", false);
ConfigurationManager.getConfigInstance().setProperty("unitTestPrefix.command.TEST.circuitBreaker.forceClosed", true);
// the instance specific dynamic property should take precedence over everything
assertEquals(true, properties.circuitBreakerForceClosed().get());
// cleanup
ConfigurationManager.getConfigInstance().clearProperty("unitTestPrefix.command.default.circuitBreaker.forceClosed");
ConfigurationManager.getConfigInstance().clearProperty("unitTestPrefix.command.TEST.circuitBreaker.forceClosed");
}
@Test
public void testIntegerBuilderOverride() {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST,
new HystrixCommandProperties.Setter().withMetricsRollingStatisticalWindowInMilliseconds(5000), "unitTestPrefix");
// the builder override should take precedence over the default
assertEquals(5000, properties.metricsRollingStatisticalWindowInMilliseconds().get().intValue());
}
@Test
public void testIntegerCodeDefault() {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST, new HystrixCommandProperties.Setter(), "unitTestPrefix");
assertEquals(HystrixCommandProperties.default_metricsRollingStatisticalWindow, properties.metricsRollingStatisticalWindowInMilliseconds().get());
}
@Test
public void testIntegerGlobalDynamicOverrideOfCodeDefault() throws Exception {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST, new HystrixCommandProperties.Setter(), "unitTestPrefix");
ConfigurationManager.getConfigInstance().setProperty("unitTestPrefix.command.default.metrics.rollingStats.timeInMilliseconds", 1234);
// the global dynamic property should take precedence over the default
assertEquals(1234, properties.metricsRollingStatisticalWindowInMilliseconds().get().intValue());
// cleanup
ConfigurationManager.getConfigInstance().clearProperty("unitTestPrefix.command.default.metrics.rollingStats.timeInMilliseconds");
}
@Test
public void testIntegerInstanceBuilderOverrideOfGlobalDynamicOverride() throws Exception {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST,
new HystrixCommandProperties.Setter().withMetricsRollingStatisticalWindowInMilliseconds(5000), "unitTestPrefix");
ConfigurationManager.getConfigInstance().setProperty("unitTestPrefix.command.default.rollingStats.timeInMilliseconds", 3456);
// the builder injected should take precedence over the global dynamic property
assertEquals(5000, properties.metricsRollingStatisticalWindowInMilliseconds().get().intValue());
// cleanup
ConfigurationManager.getConfigInstance().clearProperty("unitTestPrefix.command.default.rollingStats.timeInMilliseconds");
}
@Test
public void testIntegerInstanceDynamicOverrideOfEverything() throws Exception {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST,
new HystrixCommandProperties.Setter().withMetricsRollingStatisticalWindowInMilliseconds(5000), "unitTestPrefix");
ConfigurationManager.getConfigInstance().setProperty("unitTestPrefix.command.default.metrics.rollingStats.timeInMilliseconds", 1234);
ConfigurationManager.getConfigInstance().setProperty("unitTestPrefix.command.TEST.metrics.rollingStats.timeInMilliseconds", 3456);
// the instance specific dynamic property should take precedence over everything
assertEquals(3456, properties.metricsRollingStatisticalWindowInMilliseconds().get().intValue());
// cleanup
ConfigurationManager.getConfigInstance().clearProperty("unitTestPrefix.command.default.metrics.rollingStats.timeInMilliseconds");
ConfigurationManager.getConfigInstance().clearProperty("unitTestPrefix.command.TEST.metrics.rollingStats.timeInMilliseconds");
}
@Test
public void testThreadPoolOnlyHasInstanceOverride() throws Exception {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST, new HystrixCommandProperties.Setter(), "unitTestPrefix");
ConfigurationManager.getConfigInstance().setProperty("unitTestPrefix.command.default.threadPoolKeyOverride", 1234);
// it should be null
assertEquals(null, properties.executionIsolationThreadPoolKeyOverride().get());
ConfigurationManager.getConfigInstance().setProperty("unitTestPrefix.command.TEST.threadPoolKeyOverride", "testPool");
// now it should have a value
assertEquals("testPool", properties.executionIsolationThreadPoolKeyOverride().get());
// cleanup
ConfigurationManager.getConfigInstance().clearProperty("unitTestPrefix.command.default.threadPoolKeyOverride");
ConfigurationManager.getConfigInstance().clearProperty("unitTestPrefix.command.TEST.threadPoolKeyOverride");
}
}
| 4,583 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/TestHystrixCommand.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix;
import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook;
abstract public class TestHystrixCommand<T> extends HystrixCommand<T> implements AbstractTestHystrixCommand<T> {
private final TestCommandBuilder builder;
public TestHystrixCommand(TestCommandBuilder builder) {
super(builder.owner, builder.dependencyKey, builder.threadPoolKey, builder.circuitBreaker, builder.threadPool,
builder.commandPropertiesDefaults, builder.threadPoolPropertiesDefaults, builder.metrics,
builder.fallbackSemaphore, builder.executionSemaphore, TEST_PROPERTIES_FACTORY, builder.executionHook);
this.builder = builder;
}
public TestHystrixCommand(TestCommandBuilder builder, HystrixCommandExecutionHook executionHook) {
super(builder.owner, builder.dependencyKey, builder.threadPoolKey, builder.circuitBreaker, builder.threadPool,
builder.commandPropertiesDefaults, builder.threadPoolPropertiesDefaults, builder.metrics,
builder.fallbackSemaphore, builder.executionSemaphore, TEST_PROPERTIES_FACTORY, executionHook);
this.builder = builder;
}
public TestCommandBuilder getBuilder() {
return builder;
}
static TestCommandBuilder testPropsBuilder() {
return new TestCommandBuilder(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD);
}
static TestCommandBuilder testPropsBuilder(HystrixCircuitBreakerTest.TestCircuitBreaker circuitBreaker) {
return new TestCommandBuilder(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD).setCircuitBreaker(circuitBreaker);
}
static TestCommandBuilder testPropsBuilder(HystrixCommandProperties.ExecutionIsolationStrategy isolationStrategy) {
return new TestCommandBuilder(isolationStrategy);
}
}
| 4,584 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/TestHystrixObservableCommand.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix;
abstract public class TestHystrixObservableCommand<T> extends HystrixObservableCommand<T> implements AbstractTestHystrixCommand<T> {
private final TestCommandBuilder builder;
public TestHystrixObservableCommand(TestCommandBuilder builder) {
super(builder.owner, builder.dependencyKey, builder.threadPoolKey, builder.circuitBreaker, builder.threadPool,
builder.commandPropertiesDefaults, builder.threadPoolPropertiesDefaults, builder.metrics,
builder.fallbackSemaphore, builder.executionSemaphore, TEST_PROPERTIES_FACTORY, builder.executionHook);
this.builder = builder;
}
public TestCommandBuilder getBuilder() {
return builder;
}
static TestCommandBuilder testPropsBuilder() {
return new TestCommandBuilder(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE);
}
static TestCommandBuilder testPropsBuilder(HystrixCircuitBreakerTest.TestCircuitBreaker circuitBreaker) {
return new TestCommandBuilder(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE).setCircuitBreaker(circuitBreaker);
}
static TestCommandBuilder testPropsBuilder(HystrixCommandProperties.ExecutionIsolationStrategy isolationStrategy, HystrixCircuitBreakerTest.TestCircuitBreaker circuitBreaker) {
return new TestCommandBuilder(isolationStrategy).setCircuitBreaker(circuitBreaker);
}
}
| 4,585 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/HystrixTest.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix;
import org.junit.Before;
import com.netflix.hystrix.HystrixCommand.Setter;
import org.junit.Test;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Func0;
import rx.schedulers.Schedulers;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.Assert.*;
public class HystrixTest {
@Before
public void reset() {
Hystrix.reset();
}
@Test
public void testNotInThread() {
assertNull(Hystrix.getCurrentThreadExecutingCommand());
}
@Test
public void testInsideHystrixThreadViaExecute() {
assertNull(Hystrix.getCurrentThreadExecutingCommand());
HystrixCommand<Boolean> command = new HystrixCommand<Boolean>(Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("TestUtil"))
.andCommandKey(HystrixCommandKey.Factory.asKey("CommandName"))) {
@Override
protected Boolean run() {
assertEquals("CommandName", Hystrix.getCurrentThreadExecutingCommand().name());
assertEquals(1, Hystrix.getCommandCount());
return Hystrix.getCurrentThreadExecutingCommand() != null;
}
};
assertTrue(command.execute());
assertNull(Hystrix.getCurrentThreadExecutingCommand());
assertEquals(0, Hystrix.getCommandCount());
}
@Test
public void testInsideHystrixThreadViaObserve() {
assertNull(Hystrix.getCurrentThreadExecutingCommand());
HystrixCommand<Boolean> command = new HystrixCommand<Boolean>(Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("TestUtil"))
.andCommandKey(HystrixCommandKey.Factory.asKey("CommandName"))) {
@Override
protected Boolean run() {
try {
//give the caller thread a chance to check that no thread locals are set on it
Thread.sleep(100);
} catch (InterruptedException ex) {
return false;
}
assertEquals("CommandName", Hystrix.getCurrentThreadExecutingCommand().name());
assertEquals(1, Hystrix.getCommandCount());
return Hystrix.getCurrentThreadExecutingCommand() != null;
}
};
final CountDownLatch latch = new CountDownLatch(1);
command.observe().subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
latch.countDown();
}
@Override
public void onError(Throwable e) {
fail(e.getMessage());
latch.countDown();
}
@Override
public void onNext(Boolean value) {
System.out.println("OnNext : " + value);
assertTrue(value);
assertEquals("CommandName", Hystrix.getCurrentThreadExecutingCommand().name());
assertEquals(1, Hystrix.getCommandCount());
}
});
try {
assertNull(Hystrix.getCurrentThreadExecutingCommand());
assertEquals(0, Hystrix.getCommandCount());
latch.await();
} catch (InterruptedException ex) {
fail(ex.getMessage());
}
assertNull(Hystrix.getCurrentThreadExecutingCommand());
assertEquals(0, Hystrix.getCommandCount());
}
@Test
public void testInsideNestedHystrixThread() {
HystrixCommand<Boolean> command = new HystrixCommand<Boolean>(Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("TestUtil"))
.andCommandKey(HystrixCommandKey.Factory.asKey("OuterCommand"))) {
@Override
protected Boolean run() {
assertEquals("OuterCommand", Hystrix.getCurrentThreadExecutingCommand().name());
System.out.println("Outer Thread : " + Thread.currentThread().getName());
//should be a single execution on this thread
assertEquals(1, Hystrix.getCommandCount());
if (Hystrix.getCurrentThreadExecutingCommand() == null) {
throw new RuntimeException("BEFORE expected it to run inside a thread");
}
HystrixCommand<Boolean> command2 = new HystrixCommand<Boolean>(Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("TestUtil"))
.andCommandKey(HystrixCommandKey.Factory.asKey("InnerCommand"))) {
@Override
protected Boolean run() {
assertEquals("InnerCommand", Hystrix.getCurrentThreadExecutingCommand().name());
System.out.println("Inner Thread : " + Thread.currentThread().getName());
//should be a single execution on this thread, since outer/inner are on different threads
assertEquals(1, Hystrix.getCommandCount());
return Hystrix.getCurrentThreadExecutingCommand() != null;
}
};
if (Hystrix.getCurrentThreadExecutingCommand() == null) {
throw new RuntimeException("AFTER expected it to run inside a thread");
}
return command2.execute();
}
};
assertTrue(command.execute());
assertNull(Hystrix.getCurrentThreadExecutingCommand());
}
@Test
public void testInsideHystrixSemaphoreExecute() {
HystrixCommand<Boolean> command = new HystrixCommand<Boolean>(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("TestUtil"))
.andCommandKey(HystrixCommandKey.Factory.asKey("SemaphoreIsolatedCommandName"))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE))) {
@Override
protected Boolean run() {
assertEquals("SemaphoreIsolatedCommandName", Hystrix.getCurrentThreadExecutingCommand().name());
System.out.println("Semaphore Thread : " + Thread.currentThread().getName());
//should be a single execution on the caller thread (since it's busy here)
assertEquals(1, Hystrix.getCommandCount());
return Hystrix.getCurrentThreadExecutingCommand() != null;
}
};
// it should be true for semaphore isolation as well
assertTrue(command.execute());
// and then be null again once done
assertNull(Hystrix.getCurrentThreadExecutingCommand());
}
@Test
public void testInsideHystrixSemaphoreQueue() throws Exception {
HystrixCommand<Boolean> command = new HystrixCommand<Boolean>(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("TestUtil"))
.andCommandKey(HystrixCommandKey.Factory.asKey("SemaphoreIsolatedCommandName"))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE))) {
@Override
protected Boolean run() {
assertEquals("SemaphoreIsolatedCommandName", Hystrix.getCurrentThreadExecutingCommand().name());
System.out.println("Semaphore Thread : " + Thread.currentThread().getName());
//should be a single execution on the caller thread (since it's busy here)
assertEquals(1, Hystrix.getCommandCount());
return Hystrix.getCurrentThreadExecutingCommand() != null;
}
};
// it should be true for semaphore isolation as well
assertTrue(command.queue().get());
// and then be null again once done
assertNull(Hystrix.getCurrentThreadExecutingCommand());
}
@Test
public void testInsideHystrixSemaphoreObserve() throws Exception {
HystrixCommand<Boolean> command = new HystrixCommand<Boolean>(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("TestUtil"))
.andCommandKey(HystrixCommandKey.Factory.asKey("SemaphoreIsolatedCommandName"))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE))) {
@Override
protected Boolean run() {
assertEquals("SemaphoreIsolatedCommandName", Hystrix.getCurrentThreadExecutingCommand().name());
System.out.println("Semaphore Thread : " + Thread.currentThread().getName());
//should be a single execution on the caller thread (since it's busy here)
assertEquals(1, Hystrix.getCommandCount());
return Hystrix.getCurrentThreadExecutingCommand() != null;
}
};
// it should be true for semaphore isolation as well
assertTrue(command.toObservable().toBlocking().single());
// and then be null again once done
assertNull(Hystrix.getCurrentThreadExecutingCommand());
}
@Test
public void testThreadNestedInsideHystrixSemaphore() {
HystrixCommand<Boolean> command = new HystrixCommand<Boolean>(Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("TestUtil"))
.andCommandKey(HystrixCommandKey.Factory.asKey("OuterSemaphoreCommand"))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE))) {
@Override
protected Boolean run() {
assertEquals("OuterSemaphoreCommand", Hystrix.getCurrentThreadExecutingCommand().name());
System.out.println("Outer Semaphore Thread : " + Thread.currentThread().getName());
//should be a single execution on the caller thread
assertEquals(1, Hystrix.getCommandCount());
if (Hystrix.getCurrentThreadExecutingCommand() == null) {
throw new RuntimeException("BEFORE expected it to run inside a semaphore");
}
HystrixCommand<Boolean> command2 = new HystrixCommand<Boolean>(Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("TestUtil"))
.andCommandKey(HystrixCommandKey.Factory.asKey("InnerCommand"))) {
@Override
protected Boolean run() {
assertEquals("InnerCommand", Hystrix.getCurrentThreadExecutingCommand().name());
System.out.println("Inner Thread : " + Thread.currentThread().getName());
//should be a single execution on the thread isolating the second command
assertEquals(1, Hystrix.getCommandCount());
return Hystrix.getCurrentThreadExecutingCommand() != null;
}
};
if (Hystrix.getCurrentThreadExecutingCommand() == null) {
throw new RuntimeException("AFTER expected it to run inside a semaphore");
}
return command2.execute();
}
};
assertTrue(command.execute());
assertNull(Hystrix.getCurrentThreadExecutingCommand());
}
@Test
public void testSemaphoreIsolatedSynchronousHystrixObservableCommand() {
HystrixObservableCommand<Integer> observableCmd = new SynchronousObservableCommand();
assertNull(Hystrix.getCurrentThreadExecutingCommand());
final CountDownLatch latch = new CountDownLatch(1);
observableCmd.observe().subscribe(new Subscriber<Integer>() {
@Override
public void onCompleted() {
latch.countDown();
}
@Override
public void onError(Throwable e) {
fail(e.getMessage());
latch.countDown();
}
@Override
public void onNext(Integer value) {
System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis() + " SyncObservable latched Subscriber OnNext : " + value);
}
});
try {
assertNull(Hystrix.getCurrentThreadExecutingCommand());
assertEquals(0, Hystrix.getCommandCount());
latch.await();
} catch (InterruptedException ex) {
fail(ex.getMessage());
}
assertNull(Hystrix.getCurrentThreadExecutingCommand());
assertEquals(0, Hystrix.getCommandCount());
}
// @Test
// public void testSemaphoreIsolatedAsynchronousHystrixObservableCommand() {
// HystrixObservableCommand<Integer> observableCmd = new AsynchronousObservableCommand();
//
// assertNull(Hystrix.getCurrentThreadExecutingCommand());
//
// final CountDownLatch latch = new CountDownLatch(1);
//
// observableCmd.observe().subscribe(new Subscriber<Integer>() {
// @Override
// public void onCompleted() {
// latch.countDown();
// }
//
// @Override
// public void onError(Throwable e) {
// fail(e.getMessage());
// latch.countDown();
// }
//
// @Override
// public void onNext(Integer value) {
// System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis() + " AsyncObservable latched Subscriber OnNext : " + value);
// }
// });
//
// try {
// assertNull(Hystrix.getCurrentThreadExecutingCommand());
// assertEquals(0, Hystrix.getCommandCount());
// latch.await();
// } catch (InterruptedException ex) {
// fail(ex.getMessage());
// }
//
// assertNull(Hystrix.getCurrentThreadExecutingCommand());
// assertEquals(0, Hystrix.getCommandCount());
// }
@Test
public void testMultipleSemaphoreObservableCommandsInFlight() throws InterruptedException {
int NUM_COMMANDS = 50;
List<Observable<Integer>> commands = new ArrayList<Observable<Integer>>();
for (int i = 0; i < NUM_COMMANDS; i++) {
commands.add(Observable.defer(new Func0<Observable<Integer>>() {
@Override
public Observable<Integer> call() {
return new AsynchronousObservableCommand().observe();
}
}));
}
final AtomicBoolean exceptionFound = new AtomicBoolean(false);
final CountDownLatch latch = new CountDownLatch(1);
Observable.merge(commands).subscribe(new Subscriber<Integer>() {
@Override
public void onCompleted() {
System.out.println("OnCompleted");
latch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println("OnError : " + e);
e.printStackTrace();
exceptionFound.set(true);
latch.countDown();
}
@Override
public void onNext(Integer n) {
System.out.println("OnNext : " + n + " : " + Thread.currentThread().getName() + " : " + Hystrix.getCommandCount());// + " : " + Hystrix.getCurrentThreadExecutingCommand().name() + " : " + Hystrix.getCommandCount());
}
});
latch.await();
assertFalse(exceptionFound.get());
}
//see https://github.com/Netflix/Hystrix/issues/280
@Test
public void testResetCommandProperties() {
HystrixCommand<Boolean> cmd1 = new ResettableCommand(100, 1, 10);
assertEquals(100L, (long) cmd1.getProperties().executionTimeoutInMilliseconds().get());
assertEquals(1L, (long) cmd1.getProperties().executionIsolationSemaphoreMaxConcurrentRequests().get());
//assertEquals(10L, (long) cmd1.threadPool.getExecutor()..getCorePoolSize());
Hystrix.reset();
HystrixCommand<Boolean> cmd2 = new ResettableCommand(700, 2, 40);
assertEquals(700L, (long) cmd2.getProperties().executionTimeoutInMilliseconds().get());
assertEquals(2L, (long) cmd2.getProperties().executionIsolationSemaphoreMaxConcurrentRequests().get());
//assertEquals(40L, (long) cmd2.threadPool.getExecutor().getCorePoolSize());
}
private static class SynchronousObservableCommand extends HystrixObservableCommand<Integer> {
protected SynchronousObservableCommand() {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("GROUP"))
.andCommandKey(HystrixCommandKey.Factory.asKey("SyncObservable"))
.andCommandPropertiesDefaults(new HystrixCommandProperties.Setter().withExecutionIsolationSemaphoreMaxConcurrentRequests(1000))
);
}
@Override
protected Observable<Integer> construct() {
return Observable.create(new Observable.OnSubscribe<Integer>() {
@Override
public void call(Subscriber<? super Integer> subscriber) {
try {
System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis() + " SyncCommand construct()");
assertEquals("SyncObservable", Hystrix.getCurrentThreadExecutingCommand().name());
assertEquals(1, Hystrix.getCommandCount());
Thread.sleep(10);
System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis() + " SyncCommand construct() -> OnNext(1)");
subscriber.onNext(1);
Thread.sleep(10);
System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis() + " SyncCommand construct() -> OnNext(2)");
subscriber.onNext(2);
System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis() + " SyncCommand construct() -> OnCompleted");
subscriber.onCompleted();
} catch (Throwable ex) {
subscriber.onError(ex);
}
}
});
}
}
private static class AsynchronousObservableCommand extends HystrixObservableCommand<Integer> {
protected AsynchronousObservableCommand() {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("GROUP"))
.andCommandKey(HystrixCommandKey.Factory.asKey("AsyncObservable"))
.andCommandPropertiesDefaults(new HystrixCommandProperties.Setter().withExecutionIsolationSemaphoreMaxConcurrentRequests(1000))
);
}
@Override
protected Observable<Integer> construct() {
return Observable.create(new Observable.OnSubscribe<Integer>() {
@Override
public void call(Subscriber<? super Integer> subscriber) {
try {
System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis() + " AsyncCommand construct()");
Thread.sleep(10);
System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis() + " AsyncCommand construct() -> OnNext(1)");
subscriber.onNext(1);
Thread.sleep(10);
System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis() + " AsyncCommand construct() -> OnNext(2)");
subscriber.onNext(2);
System.out.println(Thread.currentThread().getName() + " : " + System.currentTimeMillis() + " AsyncCommand construct() -> OnCompleted");
subscriber.onCompleted();
} catch (Throwable ex) {
subscriber.onError(ex);
}
}
}).subscribeOn(Schedulers.computation());
}
}
private static class ResettableCommand extends HystrixCommand<Boolean> {
ResettableCommand(int timeout, int semaphoreCount, int poolCoreSize) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("GROUP"))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withExecutionTimeoutInMilliseconds(timeout)
.withExecutionIsolationSemaphoreMaxConcurrentRequests(semaphoreCount))
.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter().withCoreSize(poolCoreSize)));
}
@Override
protected Boolean run() throws Exception {
return true;
}
}
}
| 4,586 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/NotWrappedByHystrixTestRuntimeException.java | package com.netflix.hystrix;
import com.netflix.hystrix.exception.ExceptionNotWrappedByHystrix;
public class NotWrappedByHystrixTestRuntimeException extends RuntimeException implements ExceptionNotWrappedByHystrix {
private static final long serialVersionUID = 1L;
public NotWrappedByHystrixTestRuntimeException() {
super("Raw exception for TestHystrixCommand");
}
}
| 4,587 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/util/HystrixRollingNumberTest.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import com.netflix.hystrix.util.HystrixRollingNumber.Time;
public class HystrixRollingNumberTest {
@Test
public void testCreatesBuckets() {
MockedTime time = new MockedTime();
try {
HystrixRollingNumber counter = new HystrixRollingNumber(time, 200, 10);
// confirm the initial settings
assertEquals(200, counter.timeInMilliseconds);
assertEquals(10, counter.numberOfBuckets);
assertEquals(20, counter.bucketSizeInMillseconds);
// we start out with 0 buckets in the queue
assertEquals(0, counter.buckets.size());
// add a success in each interval which should result in all 10 buckets being created with 1 success in each
for (int i = 0; i < counter.numberOfBuckets; i++) {
counter.increment(HystrixRollingNumberEvent.SUCCESS);
time.increment(counter.bucketSizeInMillseconds);
}
// confirm we have all 10 buckets
assertEquals(10, counter.buckets.size());
// add 1 more and we should still only have 10 buckets since that's the max
counter.increment(HystrixRollingNumberEvent.SUCCESS);
assertEquals(10, counter.buckets.size());
} catch (Exception e) {
e.printStackTrace();
fail("Exception: " + e.getMessage());
}
}
@Test
public void testResetBuckets() {
MockedTime time = new MockedTime();
try {
HystrixRollingNumber counter = new HystrixRollingNumber(time, 200, 10);
// we start out with 0 buckets in the queue
assertEquals(0, counter.buckets.size());
// add 1
counter.increment(HystrixRollingNumberEvent.SUCCESS);
// confirm we have 1 bucket
assertEquals(1, counter.buckets.size());
// confirm we still have 1 bucket
assertEquals(1, counter.buckets.size());
// add 1
counter.increment(HystrixRollingNumberEvent.SUCCESS);
// we should now have a single bucket with no values in it instead of 2 or more buckets
assertEquals(1, counter.buckets.size());
} catch (Exception e) {
e.printStackTrace();
fail("Exception: " + e.getMessage());
}
}
@Test
public void testEmptyBucketsFillIn() {
MockedTime time = new MockedTime();
try {
HystrixRollingNumber counter = new HystrixRollingNumber(time, 200, 10);
// add 1
counter.increment(HystrixRollingNumberEvent.SUCCESS);
// we should have 1 bucket
assertEquals(1, counter.buckets.size());
// wait past 3 bucket time periods (the 1st bucket then 2 empty ones)
time.increment(counter.bucketSizeInMillseconds * 3);
// add another
counter.increment(HystrixRollingNumberEvent.SUCCESS);
// we should have 4 (1 + 2 empty + 1 new one) buckets
assertEquals(4, counter.buckets.size());
} catch (Exception e) {
e.printStackTrace();
fail("Exception: " + e.getMessage());
}
}
@Test
public void testIncrementInSingleBucket() {
MockedTime time = new MockedTime();
try {
HystrixRollingNumber counter = new HystrixRollingNumber(time, 200, 10);
// increment
counter.increment(HystrixRollingNumberEvent.SUCCESS);
counter.increment(HystrixRollingNumberEvent.SUCCESS);
counter.increment(HystrixRollingNumberEvent.SUCCESS);
counter.increment(HystrixRollingNumberEvent.SUCCESS);
counter.increment(HystrixRollingNumberEvent.FAILURE);
counter.increment(HystrixRollingNumberEvent.FAILURE);
counter.increment(HystrixRollingNumberEvent.TIMEOUT);
// we should have 1 bucket
assertEquals(1, counter.buckets.size());
// the count should be 4
assertEquals(4, counter.buckets.getLast().getAdder(HystrixRollingNumberEvent.SUCCESS).sum());
assertEquals(2, counter.buckets.getLast().getAdder(HystrixRollingNumberEvent.FAILURE).sum());
assertEquals(1, counter.buckets.getLast().getAdder(HystrixRollingNumberEvent.TIMEOUT).sum());
} catch (Exception e) {
e.printStackTrace();
fail("Exception: " + e.getMessage());
}
}
@Test
public void testTimeout() {
MockedTime time = new MockedTime();
try {
HystrixRollingNumber counter = new HystrixRollingNumber(time, 200, 10);
// increment
counter.increment(HystrixRollingNumberEvent.TIMEOUT);
// we should have 1 bucket
assertEquals(1, counter.buckets.size());
// the count should be 1
assertEquals(1, counter.buckets.getLast().getAdder(HystrixRollingNumberEvent.TIMEOUT).sum());
assertEquals(1, counter.getRollingSum(HystrixRollingNumberEvent.TIMEOUT));
// sleep to get to a new bucket
time.increment(counter.bucketSizeInMillseconds * 3);
// incremenet again in latest bucket
counter.increment(HystrixRollingNumberEvent.TIMEOUT);
// we should have 4 buckets
assertEquals(4, counter.buckets.size());
// the counts of the last bucket
assertEquals(1, counter.buckets.getLast().getAdder(HystrixRollingNumberEvent.TIMEOUT).sum());
// the total counts
assertEquals(2, counter.getRollingSum(HystrixRollingNumberEvent.TIMEOUT));
} catch (Exception e) {
e.printStackTrace();
fail("Exception: " + e.getMessage());
}
}
@Test
public void testShortCircuited() {
MockedTime time = new MockedTime();
try {
HystrixRollingNumber counter = new HystrixRollingNumber(time, 200, 10);
// increment
counter.increment(HystrixRollingNumberEvent.SHORT_CIRCUITED);
// we should have 1 bucket
assertEquals(1, counter.buckets.size());
// the count should be 1
assertEquals(1, counter.buckets.getLast().getAdder(HystrixRollingNumberEvent.SHORT_CIRCUITED).sum());
assertEquals(1, counter.getRollingSum(HystrixRollingNumberEvent.SHORT_CIRCUITED));
// sleep to get to a new bucket
time.increment(counter.bucketSizeInMillseconds * 3);
// incremenet again in latest bucket
counter.increment(HystrixRollingNumberEvent.SHORT_CIRCUITED);
// we should have 4 buckets
assertEquals(4, counter.buckets.size());
// the counts of the last bucket
assertEquals(1, counter.buckets.getLast().getAdder(HystrixRollingNumberEvent.SHORT_CIRCUITED).sum());
// the total counts
assertEquals(2, counter.getRollingSum(HystrixRollingNumberEvent.SHORT_CIRCUITED));
} catch (Exception e) {
e.printStackTrace();
fail("Exception: " + e.getMessage());
}
}
@Test
public void testThreadPoolRejection() {
testCounterType(HystrixRollingNumberEvent.THREAD_POOL_REJECTED);
}
@Test
public void testFallbackSuccess() {
testCounterType(HystrixRollingNumberEvent.FALLBACK_SUCCESS);
}
@Test
public void testFallbackFailure() {
testCounterType(HystrixRollingNumberEvent.FALLBACK_FAILURE);
}
@Test
public void testExceptionThrow() {
testCounterType(HystrixRollingNumberEvent.EXCEPTION_THROWN);
}
private void testCounterType(HystrixRollingNumberEvent type) {
MockedTime time = new MockedTime();
try {
HystrixRollingNumber counter = new HystrixRollingNumber(time, 200, 10);
// increment
counter.increment(type);
// we should have 1 bucket
assertEquals(1, counter.buckets.size());
// the count should be 1
assertEquals(1, counter.buckets.getLast().getAdder(type).sum());
assertEquals(1, counter.getRollingSum(type));
// sleep to get to a new bucket
time.increment(counter.bucketSizeInMillseconds * 3);
// increment again in latest bucket
counter.increment(type);
// we should have 4 buckets
assertEquals(4, counter.buckets.size());
// the counts of the last bucket
assertEquals(1, counter.buckets.getLast().getAdder(type).sum());
// the total counts
assertEquals(2, counter.getRollingSum(type));
} catch (Exception e) {
e.printStackTrace();
fail("Exception: " + e.getMessage());
}
}
@Test
public void testIncrementInMultipleBuckets() {
MockedTime time = new MockedTime();
try {
HystrixRollingNumber counter = new HystrixRollingNumber(time, 200, 10);
// increment
counter.increment(HystrixRollingNumberEvent.SUCCESS);
counter.increment(HystrixRollingNumberEvent.SUCCESS);
counter.increment(HystrixRollingNumberEvent.SUCCESS);
counter.increment(HystrixRollingNumberEvent.SUCCESS);
counter.increment(HystrixRollingNumberEvent.FAILURE);
counter.increment(HystrixRollingNumberEvent.FAILURE);
counter.increment(HystrixRollingNumberEvent.TIMEOUT);
counter.increment(HystrixRollingNumberEvent.TIMEOUT);
counter.increment(HystrixRollingNumberEvent.SHORT_CIRCUITED);
// sleep to get to a new bucket
time.increment(counter.bucketSizeInMillseconds * 3);
// increment
counter.increment(HystrixRollingNumberEvent.SUCCESS);
counter.increment(HystrixRollingNumberEvent.SUCCESS);
counter.increment(HystrixRollingNumberEvent.FAILURE);
counter.increment(HystrixRollingNumberEvent.FAILURE);
counter.increment(HystrixRollingNumberEvent.FAILURE);
counter.increment(HystrixRollingNumberEvent.TIMEOUT);
counter.increment(HystrixRollingNumberEvent.SHORT_CIRCUITED);
// we should have 4 buckets
assertEquals(4, counter.buckets.size());
// the counts of the last bucket
assertEquals(2, counter.buckets.getLast().getAdder(HystrixRollingNumberEvent.SUCCESS).sum());
assertEquals(3, counter.buckets.getLast().getAdder(HystrixRollingNumberEvent.FAILURE).sum());
assertEquals(1, counter.buckets.getLast().getAdder(HystrixRollingNumberEvent.TIMEOUT).sum());
assertEquals(1, counter.buckets.getLast().getAdder(HystrixRollingNumberEvent.SHORT_CIRCUITED).sum());
// the total counts
assertEquals(6, counter.getRollingSum(HystrixRollingNumberEvent.SUCCESS));
assertEquals(5, counter.getRollingSum(HystrixRollingNumberEvent.FAILURE));
assertEquals(3, counter.getRollingSum(HystrixRollingNumberEvent.TIMEOUT));
assertEquals(2, counter.getRollingSum(HystrixRollingNumberEvent.SHORT_CIRCUITED));
// wait until window passes
time.increment(counter.timeInMilliseconds);
// increment
counter.increment(HystrixRollingNumberEvent.SUCCESS);
// the total counts should now include only the last bucket after a reset since the window passed
assertEquals(1, counter.getRollingSum(HystrixRollingNumberEvent.SUCCESS));
assertEquals(0, counter.getRollingSum(HystrixRollingNumberEvent.FAILURE));
assertEquals(0, counter.getRollingSum(HystrixRollingNumberEvent.TIMEOUT));
} catch (Exception e) {
e.printStackTrace();
fail("Exception: " + e.getMessage());
}
}
@Test
public void testCounterRetrievalRefreshesBuckets() {
MockedTime time = new MockedTime();
try {
HystrixRollingNumber counter = new HystrixRollingNumber(time, 200, 10);
// increment
counter.increment(HystrixRollingNumberEvent.SUCCESS);
counter.increment(HystrixRollingNumberEvent.SUCCESS);
counter.increment(HystrixRollingNumberEvent.SUCCESS);
counter.increment(HystrixRollingNumberEvent.SUCCESS);
counter.increment(HystrixRollingNumberEvent.FAILURE);
counter.increment(HystrixRollingNumberEvent.FAILURE);
// sleep to get to a new bucket
time.increment(counter.bucketSizeInMillseconds * 3);
// we should have 1 bucket since nothing has triggered the update of buckets in the elapsed time
assertEquals(1, counter.buckets.size());
// the total counts
assertEquals(4, counter.getRollingSum(HystrixRollingNumberEvent.SUCCESS));
assertEquals(2, counter.getRollingSum(HystrixRollingNumberEvent.FAILURE));
// we should have 4 buckets as the counter 'gets' should have triggered the buckets being created to fill in time
assertEquals(4, counter.buckets.size());
// wait until window passes
time.increment(counter.timeInMilliseconds);
// the total counts should all be 0 (and the buckets cleared by the get, not only increment)
assertEquals(0, counter.getRollingSum(HystrixRollingNumberEvent.SUCCESS));
assertEquals(0, counter.getRollingSum(HystrixRollingNumberEvent.FAILURE));
// increment
counter.increment(HystrixRollingNumberEvent.SUCCESS);
// the total counts should now include only the last bucket after a reset since the window passed
assertEquals(1, counter.getRollingSum(HystrixRollingNumberEvent.SUCCESS));
assertEquals(0, counter.getRollingSum(HystrixRollingNumberEvent.FAILURE));
} catch (Exception e) {
e.printStackTrace();
fail("Exception: " + e.getMessage());
}
}
@Test
public void testUpdateMax1() {
MockedTime time = new MockedTime();
try {
HystrixRollingNumber counter = new HystrixRollingNumber(time, 200, 10);
// increment
counter.updateRollingMax(HystrixRollingNumberEvent.THREAD_MAX_ACTIVE, 10);
// we should have 1 bucket
assertEquals(1, counter.buckets.size());
// the count should be 10
assertEquals(10, counter.buckets.getLast().getMaxUpdater(HystrixRollingNumberEvent.THREAD_MAX_ACTIVE).max());
assertEquals(10, counter.getRollingMaxValue(HystrixRollingNumberEvent.THREAD_MAX_ACTIVE));
// sleep to get to a new bucket
time.increment(counter.bucketSizeInMillseconds * 3);
// increment again in latest bucket
counter.updateRollingMax(HystrixRollingNumberEvent.THREAD_MAX_ACTIVE, 20);
// we should have 4 buckets
assertEquals(4, counter.buckets.size());
// the max
assertEquals(20, counter.buckets.getLast().getMaxUpdater(HystrixRollingNumberEvent.THREAD_MAX_ACTIVE).max());
// counts per bucket
long values[] = counter.getValues(HystrixRollingNumberEvent.THREAD_MAX_ACTIVE);
assertEquals(10, values[0]); // oldest bucket
assertEquals(0, values[1]);
assertEquals(0, values[2]);
assertEquals(20, values[3]); // latest bucket
} catch (Exception e) {
e.printStackTrace();
fail("Exception: " + e.getMessage());
}
}
@Test
public void testUpdateMax2() {
MockedTime time = new MockedTime();
try {
HystrixRollingNumber counter = new HystrixRollingNumber(time, 200, 10);
// increment
counter.updateRollingMax(HystrixRollingNumberEvent.THREAD_MAX_ACTIVE, 10);
counter.updateRollingMax(HystrixRollingNumberEvent.THREAD_MAX_ACTIVE, 30);
counter.updateRollingMax(HystrixRollingNumberEvent.THREAD_MAX_ACTIVE, 20);
// we should have 1 bucket
assertEquals(1, counter.buckets.size());
// the count should be 30
assertEquals(30, counter.buckets.getLast().getMaxUpdater(HystrixRollingNumberEvent.THREAD_MAX_ACTIVE).max());
assertEquals(30, counter.getRollingMaxValue(HystrixRollingNumberEvent.THREAD_MAX_ACTIVE));
// sleep to get to a new bucket
time.increment(counter.bucketSizeInMillseconds * 3);
counter.updateRollingMax(HystrixRollingNumberEvent.THREAD_MAX_ACTIVE, 30);
counter.updateRollingMax(HystrixRollingNumberEvent.THREAD_MAX_ACTIVE, 30);
counter.updateRollingMax(HystrixRollingNumberEvent.THREAD_MAX_ACTIVE, 50);
// we should have 4 buckets
assertEquals(4, counter.buckets.size());
// the count
assertEquals(50, counter.buckets.getLast().getMaxUpdater(HystrixRollingNumberEvent.THREAD_MAX_ACTIVE).max());
assertEquals(50, counter.getValueOfLatestBucket(HystrixRollingNumberEvent.THREAD_MAX_ACTIVE));
// values per bucket
long values[] = counter.getValues(HystrixRollingNumberEvent.THREAD_MAX_ACTIVE);
assertEquals(30, values[0]); // oldest bucket
assertEquals(0, values[1]);
assertEquals(0, values[2]);
assertEquals(50, values[3]); // latest bucket
} catch (Exception e) {
e.printStackTrace();
fail("Exception: " + e.getMessage());
}
}
@Test
public void testMaxValue() {
MockedTime time = new MockedTime();
try {
HystrixRollingNumberEvent type = HystrixRollingNumberEvent.THREAD_MAX_ACTIVE;
HystrixRollingNumber counter = new HystrixRollingNumber(time, 200, 10);
counter.updateRollingMax(type, 10);
// sleep to get to a new bucket
time.increment(counter.bucketSizeInMillseconds);
counter.updateRollingMax(type, 30);
// sleep to get to a new bucket
time.increment(counter.bucketSizeInMillseconds);
counter.updateRollingMax(type, 40);
// sleep to get to a new bucket
time.increment(counter.bucketSizeInMillseconds);
counter.updateRollingMax(type, 15);
assertEquals(40, counter.getRollingMaxValue(type));
} catch (Exception e) {
e.printStackTrace();
fail("Exception: " + e.getMessage());
}
}
@Test
public void testEmptySum() {
MockedTime time = new MockedTime();
HystrixRollingNumberEvent type = HystrixRollingNumberEvent.COLLAPSED;
HystrixRollingNumber counter = new HystrixRollingNumber(time, 200, 10);
assertEquals(0, counter.getRollingSum(type));
}
@Test
public void testEmptyMax() {
MockedTime time = new MockedTime();
HystrixRollingNumberEvent type = HystrixRollingNumberEvent.THREAD_MAX_ACTIVE;
HystrixRollingNumber counter = new HystrixRollingNumber(time, 200, 10);
assertEquals(0, counter.getRollingMaxValue(type));
}
@Test
public void testEmptyLatestValue() {
MockedTime time = new MockedTime();
HystrixRollingNumberEvent type = HystrixRollingNumberEvent.THREAD_MAX_ACTIVE;
HystrixRollingNumber counter = new HystrixRollingNumber(time, 200, 10);
assertEquals(0, counter.getValueOfLatestBucket(type));
}
@Test
public void testRolling() {
MockedTime time = new MockedTime();
HystrixRollingNumberEvent type = HystrixRollingNumberEvent.THREAD_MAX_ACTIVE;
HystrixRollingNumber counter = new HystrixRollingNumber(time, 20, 2);
// iterate over 20 buckets on a queue sized for 2
for (int i = 0; i < 20; i++) {
// first bucket
counter.getCurrentBucket();
try {
time.increment(counter.bucketSizeInMillseconds);
} catch (Exception e) {
// ignore
}
assertEquals(2, counter.getValues(type).length);
counter.getValueOfLatestBucket(type);
// System.out.println("Head: " + counter.buckets.state.get().head);
// System.out.println("Tail: " + counter.buckets.state.get().tail);
}
}
@Test
public void testCumulativeCounterAfterRolling() {
MockedTime time = new MockedTime();
HystrixRollingNumberEvent type = HystrixRollingNumberEvent.SUCCESS;
HystrixRollingNumber counter = new HystrixRollingNumber(time, 20, 2);
assertEquals(0, counter.getCumulativeSum(type));
// iterate over 20 buckets on a queue sized for 2
for (int i = 0; i < 20; i++) {
// first bucket
counter.increment(type);
try {
time.increment(counter.bucketSizeInMillseconds);
} catch (Exception e) {
// ignore
}
assertEquals(2, counter.getValues(type).length);
counter.getValueOfLatestBucket(type);
}
// cumulative count should be 20 (for the number of loops above) regardless of buckets rolling
assertEquals(20, counter.getCumulativeSum(type));
}
@Test
public void testCumulativeCounterAfterRollingAndReset() {
MockedTime time = new MockedTime();
HystrixRollingNumberEvent type = HystrixRollingNumberEvent.SUCCESS;
HystrixRollingNumber counter = new HystrixRollingNumber(time, 20, 2);
assertEquals(0, counter.getCumulativeSum(type));
// iterate over 20 buckets on a queue sized for 2
for (int i = 0; i < 20; i++) {
// first bucket
counter.increment(type);
try {
time.increment(counter.bucketSizeInMillseconds);
} catch (Exception e) {
// ignore
}
assertEquals(2, counter.getValues(type).length);
counter.getValueOfLatestBucket(type);
if (i == 5 || i == 15) {
// simulate a reset occurring every once in a while
// so we ensure the absolute sum is handling it okay
counter.reset();
}
}
// cumulative count should be 20 (for the number of loops above) regardless of buckets rolling
assertEquals(20, counter.getCumulativeSum(type));
}
@Test
public void testCumulativeCounterAfterRollingAndReset2() {
MockedTime time = new MockedTime();
HystrixRollingNumberEvent type = HystrixRollingNumberEvent.SUCCESS;
HystrixRollingNumber counter = new HystrixRollingNumber(time, 20, 2);
assertEquals(0, counter.getCumulativeSum(type));
counter.increment(type);
counter.increment(type);
counter.increment(type);
// iterate over 20 buckets on a queue sized for 2
for (int i = 0; i < 20; i++) {
try {
time.increment(counter.bucketSizeInMillseconds);
} catch (Exception e) {
// ignore
}
if (i == 5 || i == 15) {
// simulate a reset occurring every once in a while
// so we ensure the absolute sum is handling it okay
counter.reset();
}
}
// no increments during the loop, just some before and after
counter.increment(type);
counter.increment(type);
// cumulative count should be 5 regardless of buckets rolling
assertEquals(5, counter.getCumulativeSum(type));
}
@Test
public void testCumulativeCounterAfterRollingAndReset3() {
MockedTime time = new MockedTime();
HystrixRollingNumberEvent type = HystrixRollingNumberEvent.SUCCESS;
HystrixRollingNumber counter = new HystrixRollingNumber(time, 20, 2);
assertEquals(0, counter.getCumulativeSum(type));
counter.increment(type);
counter.increment(type);
counter.increment(type);
// iterate over 20 buckets on a queue sized for 2
for (int i = 0; i < 20; i++) {
try {
time.increment(counter.bucketSizeInMillseconds);
} catch (Exception e) {
// ignore
}
}
// since we are rolling over the buckets it should reset naturally
// no increments during the loop, just some before and after
counter.increment(type);
counter.increment(type);
// cumulative count should be 5 regardless of buckets rolling
assertEquals(5, counter.getCumulativeSum(type));
}
private static class MockedTime implements Time {
private AtomicInteger time = new AtomicInteger(0);
@Override
public long getCurrentTimeInMillis() {
return time.get();
}
public void increment(int millis) {
time.addAndGet(millis);
}
}
}
| 4,588 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/util/HystrixRollingPercentileTest.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import com.netflix.hystrix.strategy.properties.HystrixProperty;
import com.netflix.hystrix.util.HystrixRollingPercentile.PercentileSnapshot;
import com.netflix.hystrix.util.HystrixRollingPercentile.Time;
public class HystrixRollingPercentileTest {
private static final int timeInMilliseconds = 60000;
private static final int numberOfBuckets = 12; // 12 buckets at 5000ms each
private static final int bucketDataLength = 1000;
private static final HystrixProperty<Boolean> enabled = HystrixProperty.Factory.asProperty(true);
private static ExecutorService threadPool;
@BeforeClass
public static void setUp() {
threadPool = Executors.newFixedThreadPool(10);
}
@AfterClass
public static void tearDown() {
threadPool.shutdown();
try {
threadPool.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException ie) {
System.out.println("Thread pool never terminated in HystrixRollingPercentileTest");
}
}
@Test
public void testRolling() {
MockedTime time = new MockedTime();
HystrixRollingPercentile p = new HystrixRollingPercentile(time, timeInMilliseconds, numberOfBuckets, bucketDataLength, enabled);
p.addValue(1000);
p.addValue(1000);
p.addValue(1000);
p.addValue(2000);
assertEquals(1, p.buckets.size());
// no bucket turnover yet so percentile not yet generated
assertEquals(0, p.getPercentile(50));
time.increment(6000);
// still only 1 bucket until we touch it again
assertEquals(1, p.buckets.size());
// a bucket has been created so we have a new percentile
assertEquals(1000, p.getPercentile(50));
// now 2 buckets since getting a percentile causes bucket retrieval
assertEquals(2, p.buckets.size());
p.addValue(1000);
p.addValue(500);
// should still be 2 buckets
assertEquals(2, p.buckets.size());
p.addValue(200);
p.addValue(200);
p.addValue(1600);
p.addValue(200);
p.addValue(1600);
p.addValue(1600);
// we haven't progressed to a new bucket so the percentile should be the same and ignore the most recent bucket
assertEquals(1000, p.getPercentile(50));
// increment to another bucket so we include all of the above in the PercentileSnapshot
time.increment(6000);
// the rolling version should have the same data as creating a snapshot like this
PercentileSnapshot ps = new PercentileSnapshot(1000, 1000, 1000, 2000, 1000, 500, 200, 200, 1600, 200, 1600, 1600);
assertEquals(ps.getPercentile(0.15), p.getPercentile(0.15));
assertEquals(ps.getPercentile(0.50), p.getPercentile(0.50));
assertEquals(ps.getPercentile(0.90), p.getPercentile(0.90));
assertEquals(ps.getPercentile(0.995), p.getPercentile(0.995));
System.out.println("100th: " + ps.getPercentile(100) + " " + p.getPercentile(100));
System.out.println("99.5th: " + ps.getPercentile(99.5) + " " + p.getPercentile(99.5));
System.out.println("99th: " + ps.getPercentile(99) + " " + p.getPercentile(99));
System.out.println("90th: " + ps.getPercentile(90) + " " + p.getPercentile(90));
System.out.println("50th: " + ps.getPercentile(50) + " " + p.getPercentile(50));
System.out.println("10th: " + ps.getPercentile(10) + " " + p.getPercentile(10));
// mean = 1000+1000+1000+2000+1000+500+200+200+1600+200+1600+1600/12
assertEquals(991, ps.getMean());
}
@Test
public void testValueIsZeroAfterRollingWindowPassesAndNoTraffic() {
MockedTime time = new MockedTime();
HystrixRollingPercentile p = new HystrixRollingPercentile(time, timeInMilliseconds, numberOfBuckets, bucketDataLength, enabled);
p.addValue(1000);
p.addValue(1000);
p.addValue(1000);
p.addValue(2000);
p.addValue(4000);
assertEquals(1, p.buckets.size());
// no bucket turnover yet so percentile not yet generated
assertEquals(0, p.getPercentile(50));
time.increment(6000);
// still only 1 bucket until we touch it again
assertEquals(1, p.buckets.size());
// a bucket has been created so we have a new percentile
assertEquals(1500, p.getPercentile(50));
// let 1 minute pass
time.increment(60000);
// no data in a minute should mean all buckets are empty (or reset) so we should not have any percentiles
assertEquals(0, p.getPercentile(50));
}
@Test
public void testSampleDataOverTime1() {
System.out.println("\n\n***************************** testSampleDataOverTime1 \n");
MockedTime time = new MockedTime();
HystrixRollingPercentile p = new HystrixRollingPercentile(time, timeInMilliseconds, numberOfBuckets, bucketDataLength, enabled);
int previousTime = 0;
for (int i = 0; i < SampleDataHolder1.data.length; i++) {
int timeInMillisecondsSinceStart = SampleDataHolder1.data[i][0];
int latency = SampleDataHolder1.data[i][1];
time.increment(timeInMillisecondsSinceStart - previousTime);
previousTime = timeInMillisecondsSinceStart;
p.addValue(latency);
}
System.out.println("0.01: " + p.getPercentile(0.01));
System.out.println("Median: " + p.getPercentile(50));
System.out.println("90th: " + p.getPercentile(90));
System.out.println("99th: " + p.getPercentile(99));
System.out.println("99.5th: " + p.getPercentile(99.5));
System.out.println("99.99: " + p.getPercentile(99.99));
System.out.println("Median: " + p.getPercentile(50));
System.out.println("Median: " + p.getPercentile(50));
System.out.println("Median: " + p.getPercentile(50));
/*
* In a loop as a use case was found where very different values were calculated in subsequent requests.
*/
for (int i = 0; i < 10; i++) {
if (p.getPercentile(50) > 5) {
fail("We expect around 2 but got: " + p.getPercentile(50));
}
if (p.getPercentile(99.5) < 20) {
fail("We expect to see some high values over 20 but got: " + p.getPercentile(99.5));
}
}
}
@Test
public void testSampleDataOverTime2() {
System.out.println("\n\n***************************** testSampleDataOverTime2 \n");
MockedTime time = new MockedTime();
int previousTime = 0;
HystrixRollingPercentile p = new HystrixRollingPercentile(time, timeInMilliseconds, numberOfBuckets, bucketDataLength, enabled);
for (int i = 0; i < SampleDataHolder2.data.length; i++) {
int timeInMillisecondsSinceStart = SampleDataHolder2.data[i][0];
int latency = SampleDataHolder2.data[i][1];
time.increment(timeInMillisecondsSinceStart - previousTime);
previousTime = timeInMillisecondsSinceStart;
p.addValue(latency);
}
System.out.println("0.01: " + p.getPercentile(0.01));
System.out.println("Median: " + p.getPercentile(50));
System.out.println("90th: " + p.getPercentile(90));
System.out.println("99th: " + p.getPercentile(99));
System.out.println("99.5th: " + p.getPercentile(99.5));
System.out.println("99.99: " + p.getPercentile(99.99));
if (p.getPercentile(50) > 90 || p.getPercentile(50) < 50) {
fail("We expect around 60-70 but got: " + p.getPercentile(50));
}
if (p.getPercentile(99) < 400) {
fail("We expect to see some high values over 400 but got: " + p.getPercentile(99));
}
}
public PercentileSnapshot getPercentileForValues(int... values) {
return new PercentileSnapshot(values);
}
@Test
public void testPercentileAlgorithm_Median1() {
PercentileSnapshot list = new PercentileSnapshot(100, 100, 100, 100, 200, 200, 200, 300, 300, 300, 300);
Assert.assertEquals(200, list.getPercentile(50));
}
@Test
public void testPercentileAlgorithm_Median2() {
PercentileSnapshot list = new PercentileSnapshot(100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 500);
Assert.assertEquals(100, list.getPercentile(50));
}
@Test
public void testPercentileAlgorithm_Median3() {
PercentileSnapshot list = new PercentileSnapshot(50, 75, 100, 125, 160, 170, 180, 200, 210, 300, 500);
// list.addValue(50); // 1
// list.addValue(75); // 2
// list.addValue(100); // 3
// list.addValue(125); // 4
// list.addValue(160); // 5
// list.addValue(170); // 6
// list.addValue(180); // 7
// list.addValue(200); // 8
// list.addValue(210); // 9
// list.addValue(300); // 10
// list.addValue(500); // 11
Assert.assertEquals(175, list.getPercentile(50));
}
@Test
public void testPercentileAlgorithm_Median4() {
PercentileSnapshot list = new PercentileSnapshot(300, 75, 125, 500, 100, 160, 180, 200, 210, 50, 170);
// unsorted so it is expected to sort it for us
// list.addValue(300); // 10
// list.addValue(75); // 2
// list.addValue(125); // 4
// list.addValue(500); // 11
// list.addValue(100); // 3
// list.addValue(160); // 5
// list.addValue(180); // 7
// list.addValue(200); // 8
// list.addValue(210); // 9
// list.addValue(50); // 1
// list.addValue(170); // 6
Assert.assertEquals(175, list.getPercentile(50));
}
@Test
public void testPercentileAlgorithm_Extremes() {
PercentileSnapshot p = new PercentileSnapshot(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 800, 768, 657, 700, 867);
System.out.println("0.01: " + p.getPercentile(0.01));
System.out.println("10th: " + p.getPercentile(10));
System.out.println("Median: " + p.getPercentile(50));
System.out.println("75th: " + p.getPercentile(75));
System.out.println("90th: " + p.getPercentile(90));
System.out.println("99th: " + p.getPercentile(99));
System.out.println("99.5th: " + p.getPercentile(99.5));
System.out.println("99.99: " + p.getPercentile(99.99));
Assert.assertEquals(2, p.getPercentile(50));
Assert.assertEquals(2, p.getPercentile(10));
Assert.assertEquals(2, p.getPercentile(75));
if (p.getPercentile(95) < 600) {
fail("We expect the 90th to be over 600 to show the extremes but got: " + p.getPercentile(90));
}
if (p.getPercentile(99) < 600) {
fail("We expect the 99th to be over 600 to show the extremes but got: " + p.getPercentile(99));
}
}
@Test
public void testPercentileAlgorithm_HighPercentile() {
PercentileSnapshot p = getPercentileForValues(1, 2, 3);
Assert.assertEquals(2, p.getPercentile(50));
Assert.assertEquals(3, p.getPercentile(75));
}
@Test
public void testPercentileAlgorithm_LowPercentile() {
PercentileSnapshot p = getPercentileForValues(1, 2);
Assert.assertEquals(1, p.getPercentile(25));
Assert.assertEquals(2, p.getPercentile(75));
}
@Test
public void testPercentileAlgorithm_Percentiles() {
PercentileSnapshot p = getPercentileForValues(10, 30, 20, 40);
Assert.assertEquals(22, p.getPercentile(30), 1.0e-5);
Assert.assertEquals(20, p.getPercentile(25), 1.0e-5);
Assert.assertEquals(40, p.getPercentile(75), 1.0e-5);
Assert.assertEquals(30, p.getPercentile(50), 1.0e-5);
// invalid percentiles
Assert.assertEquals(10, p.getPercentile(-1));
Assert.assertEquals(40, p.getPercentile(101));
}
@Test
public void testPercentileAlgorithm_NISTExample() {
PercentileSnapshot p = getPercentileForValues(951772, 951567, 951937, 951959, 951442, 950610, 951591, 951195, 951772, 950925, 951990, 951682);
Assert.assertEquals(951983, p.getPercentile(90));
Assert.assertEquals(951990, p.getPercentile(100));
}
/**
* This code should work without throwing exceptions but the data returned will all be -1 since the rolling percentile is disabled.
*/
@Test
public void testDoesNothingWhenDisabled() {
MockedTime time = new MockedTime();
int previousTime = 0;
HystrixRollingPercentile p = new HystrixRollingPercentile(time, timeInMilliseconds, numberOfBuckets, bucketDataLength, HystrixProperty.Factory.asProperty(false));
for (int i = 0; i < SampleDataHolder2.data.length; i++) {
int timeInMillisecondsSinceStart = SampleDataHolder2.data[i][0];
int latency = SampleDataHolder2.data[i][1];
time.increment(timeInMillisecondsSinceStart - previousTime);
previousTime = timeInMillisecondsSinceStart;
p.addValue(latency);
}
assertEquals(-1, p.getPercentile(50));
assertEquals(-1, p.getPercentile(75));
assertEquals(-1, p.getMean());
}
@Test
public void testThreadSafety() {
final MockedTime time = new MockedTime();
final HystrixRollingPercentile p = new HystrixRollingPercentile(time, 100, 25, 1000, HystrixProperty.Factory.asProperty(true));
final int NUM_THREADS = 1000;
final int NUM_ITERATIONS = 1000000;
final CountDownLatch latch = new CountDownLatch(NUM_THREADS);
final AtomicInteger aggregateMetrics = new AtomicInteger(); //same as a blackhole
final Random r = new Random();
Future<?> metricsPoller = threadPool.submit(new Runnable() {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
aggregateMetrics.addAndGet(p.getMean() + p.getPercentile(10) + p.getPercentile(50) + p.getPercentile(90));
//System.out.println("AGGREGATE : " + p.getPercentile(10) + " : " + p.getPercentile(50) + " : " + p.getPercentile(90));
}
}
});
for (int i = 0; i < NUM_THREADS; i++) {
final int threadId = i;
threadPool.submit(new Runnable() {
@Override
public void run() {
for (int j = 1; j < NUM_ITERATIONS / NUM_THREADS + 1; j++) {
int nextInt = r.nextInt(100);
p.addValue(nextInt);
if (threadId == 0) {
time.increment(1);
}
}
latch.countDown();
}
});
}
try {
latch.await(100, TimeUnit.SECONDS);
metricsPoller.cancel(true);
} catch (InterruptedException ex) {
fail("Timeout on all threads writing percentiles");
}
aggregateMetrics.addAndGet(p.getMean() + p.getPercentile(10) + p.getPercentile(50) + p.getPercentile(90));
System.out.println(p.getMean() + " : " + p.getPercentile(50) + " : " + p.getPercentile(75) + " : " + p.getPercentile(90) + " : " + p.getPercentile(95) + " : " + p.getPercentile(99));
}
@Test
public void testWriteThreadSafety() {
final MockedTime time = new MockedTime();
final HystrixRollingPercentile p = new HystrixRollingPercentile(time, 100, 25, 1000, HystrixProperty.Factory.asProperty(true));
final int NUM_THREADS = 10;
final int NUM_ITERATIONS = 1000;
final CountDownLatch latch = new CountDownLatch(NUM_THREADS);
final Random r = new Random();
final AtomicInteger added = new AtomicInteger(0);
for (int i = 0; i < NUM_THREADS; i++) {
threadPool.submit(new Runnable() {
@Override
public void run() {
for (int j = 1; j < NUM_ITERATIONS / NUM_THREADS + 1; j++) {
int nextInt = r.nextInt(100);
p.addValue(nextInt);
added.getAndIncrement();
}
latch.countDown();
}
});
}
try {
latch.await(100, TimeUnit.SECONDS);
assertEquals(added.get(), p.buckets.peekLast().data.length());
} catch (InterruptedException ex) {
fail("Timeout on all threads writing percentiles");
}
}
@Test
public void testThreadSafetyMulti() {
for (int i = 0; i < 100; i++) {
testThreadSafety();
}
}
private static class MockedTime implements Time {
private AtomicInteger time = new AtomicInteger(0);
@Override
public long getCurrentTimeInMillis() {
return time.get();
}
public void increment(int millis) {
time.addAndGet(millis);
}
}
/* sub-class to avoid 65k limit of a single class */
private static class SampleDataHolder1 {
/*
* Array of [milliseconds, latency]
*/
private static int[][] data = new int[][] {
{ 0, 3 }, { 43, 33 }, { 45, 11 }, { 45, 1 }, { 68, 13 }, { 88, 10 }, { 158, 2 }, { 158, 4 }, { 169, 12 }, { 267, 2 }, { 342, 2 }, { 438, 2 }, { 464, 7 }, { 504, 2 }, { 541, 6 }, { 541, 2 }, { 562, 2 }, { 581, 3 }, { 636, 2 }, { 778, 2 }, { 825, 1 }, { 859, 2 }, { 948, 1 }, { 1043, 2 }, { 1145, 2 }, { 1152, 1 }, { 1218, 5 },
{ 1229, 2 }, { 1259, 2 }, { 1333, 2 }, { 1349, 2 }, { 1392, 2 }, { 1468, 1 }, { 1551, 2 }, { 1586, 2 }, { 1685, 2 }, { 1696, 1 }, { 1807, 2 }, { 1817, 3 }, { 1817, 6 }, { 1847, 2 }, { 1870, 2 }, { 1939, 2 }, { 2050, 2 }, { 2129, 3 }, { 2141, 2 }, { 2265, 2 }, { 2414, 1 }, { 2693, 2 }, { 2703, 2 }, { 2791, 2 }, { 2838, 2 },
{ 2906, 2 }, { 2981, 2 }, { 3008, 2 }, { 3026, 4 }, { 3077, 2 }, { 3273, 2 }, { 3282, 2 }, { 3286, 2 }, { 3318, 3 }, { 3335, 5 }, { 3710, 2 }, { 3711, 1 }, { 3745, 2 }, { 3748, 4 }, { 3767, 3 }, { 3809, 3 }, { 3835, 35 }, { 4083, 1 }, { 4116, 2 }, { 4117, 1 }, { 4157, 1 }, { 4279, 2 }, { 4344, 2 }, { 4452, 2 }, { 4530, 2 },
{ 4583, 2 }, { 4647, 3 }, { 4758, 2 }, { 4776, 2 }, { 4793, 2 }, { 4901, 2 }, { 4909, 2 }, { 4962, 2 }, { 4984, 2 }, { 5022, 2 }, { 5139, 2 }, { 5166, 1 }, { 5174, 2 }, { 5187, 2 }, { 5225, 2 }, { 5234, 2 }, { 5263, 1 }, { 5325, 2 }, { 5355, 4 }, { 5407, 1 }, { 5414, 2 }, { 5589, 2 }, { 5595, 2 }, { 5747, 2 }, { 5780, 2 },
{ 5788, 2 }, { 5796, 2 }, { 5818, 2 }, { 5975, 1 }, { 6018, 1 }, { 6270, 2 }, { 6272, 2 }, { 6348, 2 }, { 6372, 2 }, { 6379, 2 }, { 6439, 2 }, { 6442, 2 }, { 6460, 2 }, { 6460, 2 }, { 6509, 2 }, { 6511, 1 }, { 6514, 4 }, { 6530, 8 }, { 6719, 2 }, { 6760, 2 }, { 6784, 2 }, { 6838, 1 }, { 6861, 2 }, { 6947, 2 }, { 7013, 2 },
{ 7075, 2 }, { 7122, 5 }, { 7130, 2 }, { 7209, 3 }, { 7259, 2 }, { 7309, 1 }, { 7315, 3 }, { 7322, 2 }, { 7348, 2 }, { 7420, 2 }, { 7461, 2 }, { 7545, 2 }, { 7554, 3 }, { 7630, 2 }, { 7666, 2 }, { 7815, 1 }, { 7972, 1 }, { 7972, 2 }, { 7988, 2 }, { 8049, 8 }, { 8254, 2 }, { 8269, 2 }, { 8352, 1 }, { 8378, 2 }, { 8526, 2 },
{ 8531, 2 }, { 8583, 2 }, { 8615, 2 }, { 8619, 3 }, { 8623, 2 }, { 8692, 1 }, { 8698, 2 }, { 8773, 2 }, { 8777, 3 }, { 8822, 2 }, { 8929, 2 }, { 8935, 2 }, { 9025, 2 }, { 9054, 2 }, { 9056, 1 }, { 9086, 2 }, { 9147, 3 }, { 9219, 2 }, { 9230, 3 }, { 9248, 2 }, { 9283, 2 }, { 9314, 2 }, { 9418, 1 }, { 9426, 2 }, { 9456, 1 },
{ 9594, 2 }, { 9628, 2 }, { 9642, 2 }, { 9646, 2 }, { 9686, 1 }, { 9709, 2 }, { 9771, 3 }, { 9782, 2 }, { 9884, 2 }, { 9914, 5 }, { 10004, 4 }, { 10033, 6 }, { 10052, 2 }, { 10086, 2 }, { 10168, 2 }, { 10176, 1 }, { 10228, 2 }, { 10312, 2 }, { 10372, 2 }, { 10622, 2 }, { 10685, 2 }, { 10687, 1 }, { 10787, 2 }, { 11010, 2 },
{ 11024, 2 }, { 11044, 2 }, { 11086, 2 }, { 11149, 1 }, { 11198, 2 }, { 11265, 2 }, { 11302, 2 }, { 11326, 2 }, { 11354, 2 }, { 11404, 1 }, { 11473, 2 }, { 11506, 2 }, { 11548, 4 }, { 11575, 2 }, { 11621, 4 }, { 11625, 3 }, { 11625, 1 }, { 11642, 4 }, { 11859, 5 }, { 11870, 2 }, { 11872, 3 }, { 11880, 7 }, { 11886, 3 },
{ 11905, 6 }, { 11880, 3 }, { 11912, 6 }, { 11916, 4 }, { 11916, 3 }, { 11965, 4 }, { 12068, 13 }, { 12106, 2 }, { 12120, 2 }, { 12221, 2 }, { 12257, 2 }, { 12361, 2 }, { 12411, 2 }, { 12473, 3 }, { 12554, 2 }, { 12583, 2 }, { 12654, 2 }, { 12665, 2 }, { 12744, 1 }, { 12775, 2 }, { 12858, 2 }, { 12993, 2 }, { 13007, 3 },
{ 13025, 4 }, { 13038, 2 }, { 13092, 4 }, { 13094, 5 }, { 13095, 1 }, { 13110, 2 }, { 13116, 1 }, { 13140, 2 }, { 13169, 1 }, { 13186, 2 }, { 13202, 2 }, { 13202, 1 }, { 13256, 2 }, { 13344, 2 }, { 13373, 2 }, { 13396, 3 }, { 13446, 2 }, { 13451, 3 }, { 13475, 2 }, { 13521, 1 }, { 13587, 2 }, { 13592, 2 }, { 13708, 3 },
{ 13711, 1 }, { 13741, 1 }, { 13757, 1 }, { 13847, 2 }, { 13881, 3 }, { 13915, 1 }, { 14005, 2 }, { 14028, 2 }, { 14037, 2 }, { 14074, 2 }, { 14135, 2 }, { 14176, 2 }, { 14227, 2 }, { 14228, 2 }, { 14271, 3 }, { 14279, 3 }, { 14493, 2 }, { 14535, 3 }, { 14535, 1 }, { 14680, 2 }, { 14717, 2 }, { 14725, 1 }, { 14790, 2 },
{ 14801, 1 }, { 14959, 2 }, { 15052, 2 }, { 15055, 1 }, { 15055, 1 }, { 15075, 2 }, { 15103, 8 }, { 15153, 16 }, { 15191, 2 }, { 15240, 2 }, { 15313, 2 }, { 15323, 2 }, { 15341, 1 }, { 15383, 2 }, { 15387, 2 }, { 15491, 2 }, { 15534, 2 }, { 15539, 2 }, { 15549, 2 }, { 15554, 1 }, { 15664, 1 }, { 15726, 2 }, { 15807, 2 },
{ 15842, 2 }, { 15897, 2 }, { 15913, 3 }, { 15925, 2 }, { 15935, 2 }, { 16131, 1 }, { 16211, 3 }, { 16249, 2 }, { 16268, 2 }, { 16307, 2 }, { 16398, 2 }, { 16498, 2 }, { 16518, 1 }, { 16552, 1 }, { 16571, 2 }, { 16592, 2 }, { 16601, 3 }, { 16638, 2 }, { 16698, 2 }, { 16712, 1 }, { 16767, 2 }, { 16789, 2 }, { 16992, 2 },
{ 17015, 2 }, { 17035, 2 }, { 17074, 3 }, { 17086, 3 }, { 17086, 1 }, { 17092, 1 }, { 17110, 4 }, { 17116, 3 }, { 17236, 2 }, { 17291, 2 }, { 17291, 2 }, { 17340, 2 }, { 17342, 1 }, { 17360, 3 }, { 17436, 3 }, { 17457, 2 }, { 17508, 1 }, { 17556, 2 }, { 17601, 2 }, { 17639, 2 }, { 17671, 2 }, { 17743, 2 }, { 17857, 2 },
{ 17915, 2 }, { 17992, 2 }, { 18077, 1 }, { 18088, 2 }, { 18158, 1 }, { 18239, 16 }, { 18242, 2 }, { 18252, 3 }, { 18299, 1 }, { 18405, 2 }, { 18433, 2 }, { 18444, 2 }, { 18490, 2 }, { 18497, 2 }, { 18516, 2 }, { 18540, 2 }, { 18598, 2 }, { 18649, 2 }, { 18658, 2 }, { 18683, 2 }, { 18728, 2 }, { 18767, 1 }, { 18821, 2 },
{ 18868, 2 }, { 18876, 2 }, { 18914, 14 }, { 19212, 1 }, { 19215, 1 }, { 19293, 2 }, { 19303, 2 }, { 19336, 2 }, { 19376, 2 }, { 19419, 2 }, { 19558, 2 }, { 19559, 1 }, { 19609, 2 }, { 19688, 2 }, { 19724, 2 }, { 19820, 1 }, { 19851, 2 }, { 19881, 2 }, { 19966, 2 }, { 19983, 3 }, { 19988, 4 }, { 20047, 1 }, { 20062, 2 },
{ 20091, 1 }, { 20152, 1 }, { 20183, 1 }, { 20208, 2 }, { 20346, 2 }, { 20386, 1 }, { 20459, 2 }, { 20505, 2 }, { 20520, 1 }, { 20560, 3 }, { 20566, 3 }, { 20566, 1 }, { 20610, 2 }, { 20652, 2 }, { 20694, 2 }, { 20740, 2 }, { 20756, 2 }, { 20825, 3 }, { 20895, 2 }, { 20959, 1 }, { 20995, 2 }, { 21017, 3 }, { 21039, 2 },
{ 21086, 1 }, { 21109, 3 }, { 21139, 3 }, { 21206, 2 }, { 21230, 2 }, { 21251, 3 }, { 21352, 2 }, { 21353, 2 }, { 21370, 3 }, { 21389, 1 }, { 21445, 3 }, { 21475, 2 }, { 21528, 2 }, { 21559, 3 }, { 21604, 2 }, { 21606, 1 }, { 21815, 2 }, { 21858, 3 }, { 21860, 3 }, { 22015, 2 }, { 22065, 2 }, { 22098, 5 }, { 22105, 2 },
{ 22158, 3 }, { 22197, 2 }, { 22254, 1 }, { 22353, 2 }, { 22404, 4 }, { 22422, 2 }, { 22569, 2 }, { 22634, 2 }, { 22639, 2 }, { 22861, 2 }, { 22868, 2 }, { 22876, 1 }, { 22902, 2 }, { 22925, 2 }, { 23080, 2 }, { 23085, 3 }, { 23089, 5 }, { 23329, 1 }, { 23349, 2 }, { 23559, 5 }, { 23567, 3 }, { 23574, 2 }, { 23584, 3 },
{ 23615, 3 }, { 23633, 2 }, { 23674, 2 }, { 23678, 1 }, { 23853, 2 }, { 23875, 2 }, { 24010, 4 }, { 24076, 2 }, { 24128, 6 }, { 24248, 2 }, { 24253, 2 }, { 24259, 1 }, { 24319, 2 }, { 24319, 1 }, { 24502, 3 }, { 24666, 2 }, { 24781, 3 }, { 24792, 2 }, { 24909, 2 }, { 24993, 2 }, { 25039, 1 }, { 25090, 3 }, { 25137, 1 },
{ 25138, 3 }, { 25140, 3 }, { 25155, 5 }, { 25411, 2 }, { 25460, 2 }, { 25564, 3 }, { 25586, 3 }, { 25630, 2 }, { 25765, 2 }, { 25789, 3 }, { 25803, 2 }, { 25851, 2 }, { 25872, 2 }, { 25887, 2 }, { 25981, 1 }, { 26016, 2 }, { 26019, 1 }, { 26029, 1 }, { 26104, 7 }, { 26144, 2 }, { 26275, 1 }, { 26295, 2 }, { 26298, 1 },
{ 26322, 2 }, { 26380, 2 }, { 26408, 4 }, { 26446, 1 }, { 26553, 1 }, { 26576, 1 }, { 26635, 1 }, { 26668, 2 }, { 26675, 2 }, { 26698, 4 }, { 26748, 9 }, { 26788, 2 }, { 26932, 2 }, { 26962, 2 }, { 27042, 2 }, { 27060, 2 }, { 27163, 3 }, { 27202, 2 }, { 27290, 2 }, { 27337, 3 }, { 27376, 2 }, { 27439, 2 }, { 27458, 4 },
{ 27515, 2 }, { 27518, 1 }, { 27541, 2 }, { 27585, 3 }, { 27633, 2 }, { 27695, 2 }, { 27702, 2 }, { 27861, 2 }, { 27924, 1 }, { 28025, 14 }, { 28058, 2 }, { 28143, 2 }, { 28215, 2 }, { 28240, 2 }, { 28241, 2 }, { 28285, 2 }, { 28324, 3 }, { 28378, 2 }, { 28514, 2 }, { 28529, 2 }, { 28538, 2 }, { 28565, 3 }, { 28697, 2 },
{ 28735, 2 }, { 28769, 2 }, { 28770, 4 }, { 28788, 4 }, { 28807, 3 }, { 28807, 4 }, { 28829, 1 }, { 28853, 2 }, { 28856, 7 }, { 28864, 2 }, { 28865, 3 }, { 28915, 2 }, { 28928, 2 }, { 28964, 2 }, { 28988, 1 }, { 29031, 2 }, { 29095, 2 }, { 29189, 2 }, { 29205, 1 }, { 29230, 1 }, { 29332, 2 }, { 29339, 2 }, { 29349, 5 },
{ 29449, 2 }, { 29471, 2 }, { 29578, 2 }, { 29859, 2 }, { 29878, 2 }, { 29947, 10 }, { 30083, 2 }, { 30121, 2 }, { 30128, 2 }, { 30155, 4 }, { 30157, 1 }, { 30272, 2 }, { 30281, 2 }, { 30286, 2 }, { 30305, 2 }, { 30408, 2 }, { 30444, 22 }, { 30612, 2 }, { 30628, 2 }, { 30747, 2 }, { 30783, 2 }, { 30808, 5 }, { 30868, 3 },
{ 30875, 2 }, { 30997, 2 }, { 31000, 2 }, { 31022, 3 }, { 31111, 1 }, { 31144, 2 }, { 31146, 3 }, { 31187, 2 }, { 31324, 2 }, { 31343, 2 }, { 31416, 2 }, { 31485, 2 }, { 31539, 2 }, { 31638, 2 }, { 31648, 2 }, { 31750, 2 }, { 31754, 2 }, { 31785, 10 }, { 31786, 5 }, { 31800, 2 }, { 31801, 4 }, { 31807, 7 }, { 31807, 3 },
{ 31807, 10 }, { 31808, 3 }, { 31808, 4 }, { 31818, 6 }, { 31825, 7 }, { 31838, 2 }, { 31911, 1 }, { 31974, 2 }, { 32010, 3 }, { 32031, 2 }, { 32040, 2 }, { 32063, 1 }, { 32078, 2 }, { 32156, 2 }, { 32198, 31 }, { 32257, 2 }, { 32257, 2 }, { 32265, 2 }, { 32330, 2 }, { 32369, 8 }, { 32404, 3 }, { 32425, 2 }, { 32432, 2 },
{ 32505, 2 }, { 32531, 2 }, { 32536, 2 }, { 32549, 2 }, { 32582, 3 }, { 32590, 4 }, { 32624, 2 }, { 32644, 2 }, { 32692, 2 }, { 32695, 4 }, { 32699, 3 }, { 32726, 4 }, { 32784, 2 }, { 32832, 2 }, { 32883, 6 }, { 32965, 4 }, { 33044, 2 }, { 33104, 2 }, { 33184, 2 }, { 33264, 1 }, { 33292, 2 }, { 33312, 1 }, { 33468, 2 },
{ 33471, 1 }, { 33565, 2 }, { 33627, 2 }, { 33659, 2 }, { 33709, 2 }, { 33766, 5 }, { 33836, 2 }, { 33875, 2 }, { 33954, 2 }, { 33959, 2 }, { 34050, 2 }, { 34090, 2 }, { 34168, 2 }, { 34233, 2 }, { 34461, 2 }, { 34462, 1 }, { 34463, 2 }, { 34472, 4 }, { 34500, 2 }, { 34520, 2 }, { 34544, 2 }, { 34614, 2 }, { 34662, 1 },
{ 34676, 2 }, { 34729, 4 }, { 34803, 2 }, { 34845, 2 }, { 34913, 2 }, { 34963, 6 }, { 35019, 2 }, { 35022, 2 }, { 35070, 2 }, { 35120, 2 }, { 35132, 2 }, { 35144, 2 }, { 35205, 2 }, { 35230, 3 }, { 35244, 2 }, { 35271, 4 }, { 35276, 2 }, { 35282, 2 }, { 35324, 3 }, { 35366, 3 }, { 35659, 2 }, { 35680, 2 }, { 35744, 2 },
{ 35758, 3 }, { 35796, 2 }, { 35830, 2 }, { 35841, 7 }, { 35843, 2 }, { 35856, 2 }, { 35914, 4 }, { 35929, 13 }, { 35993, 2 }, { 35997, 1 }, { 36046, 4 }, { 36046, 1 }, { 36051, 1 }, { 36111, 2 }, { 36208, 1 }, { 36208, 1 }, { 36306, 2 }, { 36325, 2 }, { 36386, 2 }, { 36405, 2 }, { 36443, 1 }, { 36455, 1 }, { 36538, 2 },
{ 36562, 2 }, { 36566, 2 }, { 36628, 2 }, { 36693, 2 }, { 36713, 2 }, { 36730, 2 }, { 36747, 2 }, { 36786, 2 }, { 36810, 1 }, { 36848, 2 }, { 36914, 1 }, { 36920, 2 }, { 36952, 2 }, { 37071, 2 }, { 37086, 1 }, { 37094, 3 }, { 37158, 3 }, { 37231, 2 }, { 37241, 2 }, { 37285, 2 }, { 37349, 2 }, { 37404, 2 }, { 37410, 1 },
{ 37433, 4 }, { 37615, 2 }, { 37659, 2 }, { 37742, 2 }, { 37773, 2 }, { 37867, 1 }, { 37890, 2 }, { 37960, 2 }, { 38042, 3 }, { 38241, 2 }, { 38400, 2 }, { 38461, 1 }, { 38551, 2 }, { 38611, 1 }, { 38657, 2 }, { 38729, 2 }, { 38748, 2 }, { 38815, 2 }, { 38852, 2 }, { 38890, 1 }, { 38954, 2 }, { 39119, 2 }, { 39162, 2 },
{ 39175, 3 }, { 39176, 2 }, { 39231, 2 }, { 39261, 2 }, { 39467, 2 }, { 39500, 2 }, { 39507, 2 }, { 39566, 2 }, { 39608, 2 }, { 39686, 6 }, { 39730, 2 }, { 39842, 1 }, { 39853, 1 }, { 39905, 2 }, { 39931, 2 }, { 39989, 2 }, { 40030, 2 }, { 40227, 2 }, { 40268, 2 }, { 40372, 2 }, { 40415, 1 }, { 40488, 3 }, { 40536, 2 },
{ 40676, 3 }, { 40677, 2 }, { 40755, 2 }, { 40842, 2 }, { 40849, 1 }, { 40870, 3 }, { 40873, 3 }, { 40972, 2 }, { 41033, 2 }, { 41190, 2 }, { 41273, 5 }, { 41273, 1 }, { 41293, 2 }, { 41367, 32 }, { 41376, 2 }, { 41420, 2 }, { 41473, 2 }, { 41473, 2 }, { 41493, 4 }, { 41521, 2 }, { 41533, 2 }, { 41554, 2 }, { 41568, 2 },
{ 41583, 3 }, { 41728, 2 }, { 41786, 2 }, { 41836, 1 }, { 41875, 2 }, { 41933, 2 }, { 42044, 2 }, { 42075, 2 }, { 42076, 2 }, { 42133, 2 }, { 42259, 29 }, { 42269, 3 }, { 42294, 2 }, { 42420, 2 }, { 42524, 2 }, { 42524, 1 }, { 42546, 1 }, { 42631, 2 }, { 42693, 2 }, { 42740, 2 }, { 42744, 4 }, { 42755, 1 }, { 42870, 2 },
{ 42894, 2 }, { 42939, 2 }, { 42973, 2 }, { 43016, 2 }, { 43070, 2 }, { 43105, 2 }, { 43115, 2 }, { 43375, 3 }, { 43387, 1 }, { 43424, 3 }, { 43448, 2 }, { 43480, 2 }, { 43498, 2 }, { 43651, 2 }, { 43727, 2 }, { 43879, 2 }, { 43910, 1 }, { 43977, 2 }, { 44003, 2 }, { 44080, 2 }, { 44082, 1 }, { 44136, 2 }, { 44169, 29 },
{ 44186, 2 }, { 44339, 2 }, { 44350, 1 }, { 44356, 1 }, { 44430, 2 }, { 44440, 1 }, { 44530, 1 }, { 44538, 2 }, { 44572, 2 }, { 44585, 2 }, { 44709, 2 }, { 44748, 2 }, { 44748, 2 }, { 44769, 2 }, { 44813, 2 }, { 44890, 2 }, { 45015, 2 }, { 45046, 4 }, { 45052, 2 }, { 45062, 2 }, { 45094, 6 }, { 45184, 2 }, { 45191, 2 },
{ 45201, 3 }, { 45216, 3 }, { 45227, 2 }, { 45269, 1 }, { 45294, 2 }, { 45314, 2 }, { 45345, 8 }, { 45352, 2 }, { 45365, 3 }, { 45378, 1 }, { 45392, 4 }, { 45405, 3 }, { 45410, 2 }, { 45448, 14 }, { 45450, 2 }, { 45457, 2 }, { 45466, 3 }, { 45481, 4 }, { 45486, 7 }, { 45533, 5 }, { 45576, 2 }, { 45649, 2 }, { 45917, 2 },
{ 45919, 6 }, { 45919, 1 }, { 45930, 15 }, { 45930, 2 }, { 46001, 5 }, { 46036, 2 }, { 46054, 2 }, { 46075, 2 }, { 46153, 2 }, { 46155, 2 }, { 46228, 2 }, { 46234, 2 }, { 46273, 2 }, { 46387, 2 }, { 46398, 2 }, { 46517, 2 }, { 46559, 2 }, { 46565, 1 }, { 46598, 2 }, { 46686, 2 }, { 46744, 2 }, { 46816, 3 }, { 46835, 2 },
{ 46921, 2 }, { 46938, 2 }, { 46991, 2 }, { 47038, 2 }, { 47098, 3 }, { 47107, 2 }, { 47201, 3 }, { 47327, 1 }, { 47327, 1 }, { 47338, 2 }, { 47395, 1 }, { 47499, 2 }, { 47504, 2 }, { 47515, 1 }, { 47516, 1 }, { 47600, 1 }, { 47604, 1 }, { 47707, 1 }, { 47728, 1 }, { 47748, 2 }, { 47763, 2 }, { 47807, 4 }, { 47814, 2 },
{ 47822, 2 }, { 47834, 2 }, { 47843, 3 }, { 47886, 2 }, { 47893, 2 }, { 48066, 2 }, { 48126, 2 }, { 48133, 1 }, { 48166, 2 }, { 48299, 1 }, { 48455, 2 }, { 48468, 2 }, { 48568, 2 }, { 48606, 2 }, { 48642, 2 }, { 48698, 2 }, { 48714, 2 }, { 48754, 2 }, { 48765, 3 }, { 48773, 5 }, { 48819, 2 }, { 48833, 2 }, { 48904, 2 },
{ 49000, 1 }, { 49113, 12 }, { 49140, 2 }, { 49276, 2 }, { 49353, 2 }, { 49411, 3 }, { 49418, 2 }, { 49540, 2 }, { 49544, 2 }, { 49584, 2 }, { 49602, 2 }, { 49784, 5 }, { 49822, 4 }, { 49822, 5 }, { 49828, 2 }, { 49866, 2 }, { 49922, 3 }, { 49959, 2 }, { 50045, 2 }, { 50134, 3 }, { 50140, 2 }, { 50237, 2 }, { 50247, 2 },
{ 50266, 13 }, { 50290, 2 }, { 50312, 4 }, { 50314, 1 }, { 50527, 2 }, { 50605, 1 }, { 50730, 2 }, { 50751, 2 }, { 50770, 2 }, { 50858, 2 }, { 50859, 2 }, { 50909, 2 }, { 50948, 3 }, { 51043, 2 }, { 51048, 2 }, { 51089, 2 }, { 51090, 2 }, { 51141, 2 }, { 51163, 2 }, { 51250, 2 }, { 51347, 2 }, { 51475, 2 }, { 51536, 2 },
{ 51544, 2 }, { 51595, 2 }, { 51602, 19 }, { 51643, 5 }, { 51702, 2 }, { 51702, 10 }, { 51764, 2 }, { 51793, 5 }, { 51812, 2 }, { 51839, 1 }, { 51938, 3 }, { 51941, 1 }, { 51967, 4 }, { 52049, 3 }, { 52074, 3 }, { 52098, 2 }, { 52118, 2 }, { 52119, 3 }, { 52227, 11 }, { 52246, 3 }, { 52282, 2 }, { 52451, 2 }, { 52583, 2 },
{ 52601, 1 }, { 52605, 2 }, { 52615, 2 }, { 52668, 2 }, { 52824, 2 }, { 53076, 1 }, { 53120, 1 }, { 53179, 2 }, { 53189, 2 }, { 53193, 1 }, { 53195, 2 }, { 53246, 2 }, { 53249, 2 }, { 53268, 1 }, { 53295, 2 }, { 53312, 2 }, { 53410, 2 }, { 53451, 2 }, { 53570, 2 }, { 53593, 2 }, { 53635, 2 }, { 53657, 2 }, { 53682, 3 },
{ 53728, 5 }, { 53733, 2 }, { 53753, 2 }, { 53787, 4 }, { 53807, 1 }, { 54008, 2 }, { 54059, 2 }, { 54060, 1 }, { 54080, 2 }, { 54090, 1 }, { 54138, 2 }, { 54149, 2 }, { 54168, 1 }, { 54171, 2 }, { 54216, 22 }, { 54233, 6 }, { 54434, 2 }, { 54534, 2 }, { 54562, 2 }, { 54763, 2 }, { 54791, 2 }, { 54816, 2 }, { 54909, 2 },
{ 54916, 3 }, { 54963, 2 }, { 54985, 2 }, { 54991, 3 }, { 55016, 3 }, { 55025, 3 }, { 55032, 2 }, { 55099, 2 }, { 55260, 2 }, { 55261, 2 }, { 55270, 3 }, { 55384, 2 }, { 55455, 2 }, { 55456, 2 }, { 55504, 3 }, { 55510, 2 }, { 55558, 2 }, { 55568, 2 }, { 55585, 2 }, { 55677, 2 }, { 55703, 2 }, { 55749, 2 }, { 55779, 2 },
{ 55789, 3 }, { 55792, 2 }, { 55830, 4 }, { 55835, 2 }, { 55879, 2 }, { 56076, 2 }, { 56118, 2 }, { 56314, 2 }, { 56392, 1 }, { 56411, 2 }, { 56459, 2 }, { 56553, 34 }, { 56575, 2 }, { 56733, 2 }, { 56762, 2 }, { 56793, 3 }, { 56877, 3 }, { 56927, 2 }, { 56981, 2 }, { 57014, 1 }, { 57149, 2 }, { 57162, 2 }, { 57186, 2 },
{ 57254, 2 }, { 57267, 1 }, { 57324, 2 }, { 57327, 2 }, { 57365, 4 }, { 57371, 2 }, { 57445, 2 }, { 57477, 2 }, { 57497, 2 }, { 57536, 2 }, { 57609, 2 }, { 57626, 2 }, { 57666, 2 }, { 57694, 2 }, { 57694, 2 }, { 57749, 2 }, { 57781, 7 }, { 57878, 2 }, { 57953, 2 }, { 58051, 2 }, { 58088, 2 }, { 58097, 2 }, { 58142, 3 },
{ 58142, 1 }, { 58197, 1 }, { 58221, 2 }, { 58222, 2 }, { 58244, 2 }, { 58290, 1 }, { 58296, 1 }, { 58325, 2 }, { 58378, 1 }, { 58389, 3 }, { 58430, 2 }, { 58454, 2 }, { 58551, 29 }, { 58563, 6 }, { 58681, 2 }, { 58751, 8 }, { 58752, 43 }, { 58790, 5 }, { 58846, 2 }, { 58879, 6 }, { 58953, 2 }, { 58998, 2 }, { 59010, 1 },
{ 59038, 5 }, { 59135, 2 }, { 59166, 2 }, { 59180, 2 }, { 59222, 2 }, { 59227, 2 }, { 59307, 2 }, { 59398, 3 }, { 59411, 2 }, { 59436, 3 }, { 59464, 2 }, { 59569, 2 }, { 59587, 2 }, { 59624, 3 }, { 59786, 2 }, { 59834, 2 }, { 59841, 2 }, { 59841, 1 }, { 59984, 2 }, { 59985, 2 }, { 60003, 3 }, { 60045, 2 }, { 60097, 2 },
{ 60148, 2 }, { 60172, 2 }, { 60203, 5 }, { 60565, 2 }, { 60625, 2 }, { 60743, 2 }, { 60781, 2 }, { 60892, 2 }, { 60977, 2 }, { 60979, 2 }, { 61021, 5 }, { 61021, 4 }, { 61026, 2 }, { 61139, 2 }, { 61165, 3 }, { 61204, 2 }, { 61207, 1 }, { 61248, 3 }, { 61257, 2 }, { 61264, 6 }, { 61272, 3 }, { 61410, 2 }, { 61410, 3 },
{ 61416, 2 }, { 61423, 1 }, { 61503, 2 }, { 61503, 2 }, { 61533, 2 }, { 61567, 2 }, { 61575, 2 }, { 61835, 1 }, { 61842, 1 }, { 61924, 2 }, { 61951, 6 }, { 61975, 2 }, { 61986, 3 }, { 62024, 1 }, { 62110, 2 }, { 62135, 2 }, { 62192, 2 }, { 62208, 2 }, { 62399, 2 }, { 62400, 1 }, { 62414, 2 }, { 62423, 3 }, { 62456, 3 },
{ 62459, 3 }, { 62478, 3 }, { 62484, 2 }, { 62510, 6 }, { 62511, 3 }, { 62565, 3 }, { 62610, 2 }, { 62875, 4 }, { 62896, 5 }, { 62898, 2 }, { 62904, 2 }, { 62938, 3 }, { 62943, 2 }, { 62977, 2 }, { 62989, 3 }, { 62998, 5 }, { 63069, 1 }, { 63093, 5 }, { 63107, 2 }, { 63113, 1 }, { 63231, 4 }, { 63253, 2 }, { 63286, 4 },
{ 63289, 2 }, { 63334, 1 }, { 63334, 4 }, { 63413, 2 }, { 63425, 2 }, { 63512, 10 }, { 63537, 1 }, { 63694, 1 }, { 63721, 4 }, { 63749, 2 }, { 63783, 17 }, { 63791, 3 }, { 63792, 2 }, { 63882, 25 }, { 63896, 1 }, { 63936, 2 }, { 63969, 3 }, { 63986, 2 }, { 63988, 2 }, { 64009, 10 }, { 64018, 2 }, { 64032, 6 }, { 64125, 2 },
{ 64195, 1 }, { 64221, 7 }, { 64390, 2 }, { 64459, 2 }, { 64568, 2 }, { 64784, 1 }, { 64789, 2 }, { 64829, 2 }, { 64848, 1 }, { 64914, 2 }, { 64928, 1 }, { 64939, 2 }, { 65026, 2 }, { 65057, 2 }, { 65070, 2 }, { 65193, 4 }, { 65235, 3 }, { 65242, 2 }, { 65281, 2 }, { 65320, 2 }, { 65365, 1 }, { 65414, 2 }, { 65445, 2 },
{ 65581, 2 }, { 65624, 1 }, { 65719, 2 }, { 65766, 2 }, { 65927, 2 }, { 66004, 1 }, { 66031, 2 }, { 66085, 1 }, { 66085, 2 }, { 66133, 2 }, { 66134, 2 }, { 66188, 1 }, { 66240, 2 }, { 66249, 2 }, { 66250, 2 }, { 66295, 2 }, { 66342, 1 }, { 66352, 3 }, { 66388, 3 }, { 66432, 2 }, { 66437, 47 }, { 66497, 2 }, { 66517, 2 },
{ 66526, 2 }, { 66546, 9 }, { 66605, 2 }, { 66753, 2 }, { 66792, 2 }, { 66796, 2 }, { 66828, 2 }, { 66899, 3 }, { 66970, 6 }, { 66981, 2 }, { 66983, 1 }, { 67009, 2 }, { 67017, 4 }, { 67115, 2 }, { 67117, 1 }, { 67130, 6 }, { 67132, 7 }, { 67162, 2 }, { 67179, 6 }, { 67236, 2 }, { 67263, 3 }, { 67274, 2 }, { 67274, 2 },
{ 67349, 3 }, { 67486, 2 }, { 67503, 3 }, { 67517, 1 }, { 67559, 1 }, { 67660, 2 }, { 67727, 2 }, { 67901, 2 }, { 67943, 4 }, { 67950, 2 }, { 67965, 3 }, { 68029, 2 }, { 68048, 2 }, { 68169, 2 }, { 68172, 1 }, { 68258, 2 }, { 68288, 1 }, { 68359, 2 }, { 68441, 2 }, { 68484, 2 }, { 68488, 2 }, { 68525, 2 }, { 68535, 2 },
{ 68575, 7 }, { 68575, 5 }, { 68583, 2 }, { 68588, 4 }, { 68593, 1 }, { 68597, 2 }, { 68636, 2 }, { 68636, 2 }, { 68667, 2 }, { 68785, 1 }, { 68914, 4 }, { 68915, 5 }, { 68940, 3 }, { 69010, 2 }, { 69063, 2 }, { 69076, 2 }, { 69235, 2 }, { 69270, 2 }, { 69298, 1 }, { 69350, 5 }, { 69432, 2 }, { 69514, 2 }, { 69562, 3 },
{ 69562, 4 }, { 69638, 1 }, { 69656, 2 }, { 69709, 2 }, { 69775, 2 }, { 69788, 2 }, { 70193, 2 }, { 70233, 2 }, { 70252, 2 }, { 70259, 2 }, { 70293, 3 }, { 70405, 3 }, { 70462, 2 }, { 70515, 3 }, { 70518, 2 }, { 70535, 6 }, { 70547, 6 }, { 70577, 6 }, { 70631, 17 }, { 70667, 2 }, { 70680, 1 }, { 70694, 1 }, { 70898, 2 },
{ 70916, 1 }, { 70936, 3 }, { 71033, 2 }, { 71126, 2 }, { 71158, 2 }, { 71162, 2 }, { 71421, 1 }, { 71441, 2 }, { 71557, 2 }, { 71789, 1 }, { 71816, 2 }, { 71850, 1 }, { 71869, 1 }, { 71961, 2 }, { 71973, 4 }, { 72064, 2 }, { 72110, 2 }, { 72117, 3 }, { 72164, 2 }, { 72266, 2 }, { 72325, 2 }, { 72326, 1 }, { 72420, 2 },
{ 72693, 2 }, { 72705, 1 }, { 72730, 2 }, { 72793, 2 }, { 72795, 1 }, { 72939, 1 }, { 72945, 3 }, { 72945, 2 }, { 73120, 1 }, { 73121, 5 }, { 73122, 4 }, { 73126, 1 }, { 73126, 1 }, { 73196, 3 }, { 73219, 2 }, { 73241, 6 }, { 73272, 3 }, { 73354, 1 }, { 73368, 2 }, { 73467, 1 }, { 73517, 2 }, { 73554, 2 }, { 73678, 2 },
{ 73838, 1 }, { 73881, 2 }, { 73958, 2 }, { 73985, 15 }, { 74092, 2 }, { 74205, 2 }, { 74245, 2 }, { 74277, 2 }, { 74286, 2 }, { 74353, 2 }, { 74403, 2 }, { 74428, 1 }, { 74468, 2 }, { 74481, 3 }, { 74511, 2 }, { 74537, 2 }, { 74596, 2 }, { 74750, 2 }, { 74754, 2 }, { 74861, 2 }, { 74933, 4 }, { 74970, 1 }, { 75003, 3 },
{ 75077, 1 }, { 75159, 2 }, { 75170, 2 }, { 75234, 2 }, { 75300, 3 }, { 75337, 2 }, { 75345, 2 }, { 75419, 1 }, { 75429, 2 }, { 75477, 1 }, { 75513, 2 }, { 75536, 2 }, { 75536, 2 }, { 75539, 1 }, { 75551, 2 }, { 75561, 2 }, { 75565, 2 }, { 75590, 2 }, { 75623, 5 }, { 75773, 6 }, { 75777, 6 }, { 75785, 2 }, { 75791, 2 },
{ 75804, 2 }, { 75862, 2 }, { 75924, 3 }, { 75927, 2 }, { 75996, 11 }, { 76000, 1 }, { 76006, 2 }, { 76020, 3 }, { 76110, 2 }, { 76126, 3 }, { 76131, 2 }, { 76136, 2 }, { 76144, 2 }, { 76203, 2 }, { 76229, 3 }, { 76244, 15 }, { 76246, 2 }, { 76300, 1 }, { 76403, 3 }, { 76545, 2 }, { 76569, 2 }, { 76813, 2 }, { 76821, 2 },
{ 76837, 2 }, { 76863, 2 }, { 77027, 2 }, { 77037, 2 }, { 77074, 3 }, { 77170, 2 }, { 77191, 2 }, { 77220, 2 }, { 77230, 2 }, { 77261, 2 }, { 77277, 2 }, { 77309, 2 }, { 77314, 2 }, { 77412, 2 }, { 77419, 2 }, { 77457, 2 }, { 77633, 3 }, { 77714, 2 }, { 77855, 2 }, { 77857, 1 }, { 77876, 2 }, { 77895, 2 }, { 77916, 5 },
{ 77947, 2 }, { 77948, 1 }, { 77966, 1 }, { 77996, 2 }, { 78025, 1 }, { 78064, 2 }, { 78100, 2 }, { 78113, 1 }, { 78114, 3 }, { 78167, 2 }, { 78175, 2 }, { 78260, 2 }, { 78261, 1 }, { 78265, 2 }, { 78286, 1 }, { 78300, 2 }, { 78327, 3 }, { 78363, 1 }, { 78384, 2 }, { 78459, 2 }, { 78516, 2 }, { 78612, 2 }, { 78643, 2 },
{ 78655, 2 }, { 78698, 1 }, { 78720, 3 }, { 78789, 3 }, { 78838, 5 }, { 78893, 1 }, { 78954, 7 }, { 79007, 2 }, { 79132, 3 }, { 79193, 2 }, { 79193, 2 }, { 79226, 2 }, { 79411, 2 }, { 79422, 1 }, { 79502, 2 }, { 79593, 2 }, { 79622, 2 }, { 79657, 3 }, { 79771, 2 }, { 79866, 2 }, { 79909, 2 }, { 80005, 2 }, { 80032, 2 },
{ 80060, 1 }, { 80132, 2 }, { 80149, 3 }, { 80251, 2 }, { 80363, 2 }, { 80379, 1 }, { 80464, 2 }, { 80498, 2 }, { 80553, 2 }, { 80556, 3 }, { 80559, 1 }, { 80571, 2 }, { 80652, 1 }, { 80703, 2 }, { 80754, 2 }, { 80754, 2 }, { 80860, 2 }, { 81055, 2 }, { 81087, 4 }, { 81210, 2 }, { 81211, 1 }, { 81216, 1 }, { 81223, 1 },
{ 81231, 1 }, { 81288, 2 }, { 81317, 2 }, { 81327, 3 }, { 81332, 2 }, { 81376, 2 }, { 81469, 2 }, { 81579, 2 }, { 81617, 1 }, { 81630, 2 }, { 81666, 2 }, { 81800, 2 }, { 81832, 2 }, { 81848, 2 }, { 81869, 2 }, { 81941, 3 }, { 82177, 3 }, { 82179, 2 }, { 82180, 2 }, { 82182, 4 }, { 82185, 2 }, { 82195, 2 }, { 82238, 4 },
{ 82265, 3 }, { 82295, 10 }, { 82299, 9 }, { 82367, 3 }, { 82379, 3 }, { 82380, 1 }, { 82505, 2 }, { 82568, 2 }, { 82620, 1 }, { 82637, 5 }, { 82821, 2 }, { 82841, 2 }, { 82945, 1 }, { 83020, 12 }, { 83072, 2 }, { 83181, 2 }, { 83240, 2 }, { 83253, 3 }, { 83261, 2 }, { 83288, 2 }, { 83291, 4 }, { 83295, 3 }, { 83365, 2 },
{ 83368, 2 }, { 83408, 2 }, { 83458, 2 }, { 83470, 2 }, { 83471, 1 }, { 83637, 3 }, { 83693, 2 }, { 83703, 2 }, { 83732, 2 }, { 83745, 1 }, { 83800, 4 }, { 83801, 3 }, { 83856, 3 }, { 83863, 5 }, { 83867, 2 }, { 83868, 3 }, { 83898, 7 }, { 83900, 4 }, { 83901, 5 }, { 83989, 2 }, { 84049, 35 }, { 84086, 2 }, { 84089, 2 },
{ 84115, 3 }, { 84130, 3 }, { 84132, 2 }, { 84143, 3 }, { 84173, 2 }, { 84185, 5 }, { 84297, 2 }, { 84390, 2 }, { 84497, 4 }, { 84657, 2 }, { 84657, 2 }, { 84724, 2 }, { 84775, 2 }, { 84870, 2 }, { 84892, 2 }, { 84910, 3 }, { 84935, 3 }, { 85002, 2 }, { 85051, 2 }, { 85052, 2 }, { 85135, 25 }, { 85135, 2 }, { 85144, 2 },
{ 85165, 3 }, { 85205, 2 }, { 85232, 2 }, { 85281, 5 }, { 85423, 6 }, { 85539, 2 }, { 85582, 4 }, { 85609, 2 }, { 85701, 36 }, { 85705, 2 }, { 85824, 2 }, { 85824, 2 }, { 85858, 30 }, { 85858, 28 }, { 85904, 35 }, { 85910, 2 }, { 85913, 2 }, { 85926, 3 }, { 85942, 4 }, { 85969, 4 }, { 85996, 1 }, { 86013, 3 }, { 86034, 13 },
{ 86068, 8 }, { 86069, 8 }, { 86089, 8 }, { 86193, 13 }, { 86217, 7 }, { 86219, 2 }, { 86250, 2 }, { 86304, 16 }, { 86317, 2 }, { 86322, 4 }, { 86325, 2 }, { 86333, 2 }, { 86394, 2 }, { 86433, 2 }, { 86469, 3 }, { 86512, 4 }, { 86537, 2 }, { 86627, 2 }, { 86658, 2 }, { 86810, 2 }, { 86813, 2 }, { 86884, 2 }, { 86947, 2 },
{ 87003, 2 }, { 87010, 5 }, { 87019, 2 }, { 87027, 2 }, { 87105, 2 }, { 87107, 2 }, { 87183, 2 }, { 87273, 2 }, { 87358, 3 }, { 87388, 3 }, { 87503, 4 }, { 87639, 2 }, { 87649, 4 }, { 87722, 2 }, { 87829, 2 }, { 87829, 1 }, { 87863, 2 }, { 87894, 2 }, { 87988, 32 }, { 88035, 27 }, { 88059, 3 }, { 88094, 5 }, { 88111, 21 },
{ 88129, 2 }, { 88175, 5 }, { 88256, 2 }, { 88329, 2 }, { 88415, 3 }, { 88482, 2 }, { 88502, 1 }, { 88529, 2 }, { 88551, 3 }, { 88552, 1 }, { 88713, 2 }, { 88797, 2 }, { 88844, 27 }, { 88925, 5 }, { 88935, 2 }, { 88944, 1 }, { 89073, 2 }, { 89095, 3 }, { 89283, 2 }, { 89294, 3 }, { 89299, 2 }, { 89324, 2 }, { 89368, 2 },
{ 89387, 2 }, { 89464, 2 }, { 89607, 2 }, { 89737, 2 }, { 89791, 2 }, { 89794, 3 }, { 89840, 2 }, { 89849, 3 }, { 89859, 2 }, { 89905, 2 }, { 89952, 38 }, { 90030, 7 }, { 90030, 6 }, { 90031, 1 }, { 90072, 2 }, { 90090, 2 }, { 90146, 3 }, { 90202, 23 }, { 90302, 3 }, { 90328, 14 }, { 90335, 14 }, { 90338, 8 }, { 90380, 2 },
{ 90434, 1 }, { 90482, 2 }, { 90527, 9 }, { 90537, 3 }, { 90545, 2 }, { 90639, 5 }, { 90642, 2 }, { 90709, 2 }, { 90775, 1 }, { 90806, 2 }, { 90845, 19 }, { 90872, 4 }, { 90884, 2 }, { 90910, 2 }, { 90994, 5 }, { 91046, 8 }, { 91059, 8 }, { 91096, 39 }, { 91147, 2 }, { 91168, 1 }, { 91493, 2 }, { 91513, 3 }, { 91618, 3 },
{ 91653, 2 }, { 91817, 2 }, { 91831, 3 }, { 91833, 3 }, { 91885, 2 }, { 91919, 2 }, { 91934, 2 }, { 92245, 1 }, { 92284, 2 }, { 92292, 4 }, { 92369, 3 }, { 92388, 2 }, { 92426, 7 }, { 92720, 14 }, { 92720, 6 }, { 92729, 9 }, { 92733, 13 }, { 92735, 6 }, { 92786, 2 }, { 92853, 31 }, { 92906, 2 }, { 93031, 7 }, { 93077, 2 },
{ 93102, 2 }, { 93109, 2 }, { 93122, 3 }, { 93214, 2 }, { 93330, 2 }, { 93395, 2 }, { 93506, 2 }, { 93564, 9 }, { 93713, 9 }, { 93722, 4 }, { 93840, 2 }, { 93877, 4 }, { 93891, 3 }, { 93948, 2 }, { 93981, 2 }, { 94012, 3 }, { 94033, 2 }, { 94121, 2 }, { 94165, 32 }, { 94181, 3 }, { 94210, 2 }, { 94216, 2 }, { 94230, 2 },
{ 94333, 31 }, { 94433, 3 }, { 94497, 3 }, { 94609, 2 }, { 94623, 2 }, { 94763, 2 }, { 94780, 2 }, { 95287, 2 }, { 95348, 2 }, { 95433, 5 }, { 95446, 2 }, { 95493, 7 }, { 95517, 3 }, { 95580, 2 }, { 95610, 5 }, { 95620, 2 }, { 95678, 3 }, { 95683, 2 }, { 95689, 2 }, { 95760, 2 }, { 95792, 2 }, { 95850, 2 }, { 95908, 2 },
{ 95908, 2 }, { 95967, 2 }, { 96022, 3 }, { 96088, 2 }, { 96460, 2 }, { 96554, 2 }, { 96597, 2 }, { 96763, 2 }, { 96808, 2 }, { 96854, 1 }, { 96963, 1 }, { 97007, 3 }, { 97125, 1 }, { 97128, 2 }, { 97133, 3 }, { 97142, 3 }, { 97156, 2 }, { 97223, 2 }, { 97244, 2 }, { 97303, 2 }, { 97355, 2 }, { 97356, 3 }, { 97393, 3 },
{ 97409, 1 }, { 97451, 2 }, { 97539, 2 }, { 97546, 2 }, { 97553, 2 }, { 97627, 2 }, { 97640, 2 }, { 97650, 6 }, { 97675, 2 }, { 97685, 3 }, { 97773, 2 }, { 97802, 4 }, { 97826, 19 }, { 97860, 2 }, { 97956, 2 }, { 97958, 2 }, { 97973, 3 }, { 97982, 2 }, { 98039, 2 }, { 98051, 2 }, { 98059, 2 }, { 98088, 2 }, { 98092, 4 },
{ 98147, 2 }, { 98147, 2 }, { 98169, 2 }, { 98207, 2 }, { 98277, 1 }, { 98277, 22 }, { 98285, 2 }, { 98324, 3 }, { 98324, 3 }, { 98381, 31 }, { 98390, 2 }, { 98404, 2 }, { 98415, 4 }, { 98460, 2 }, { 98462, 1 }, { 98475, 3 }, { 98485, 2 }, { 98640, 1 }, { 98798, 2 }, { 98800, 4 }, { 98821, 2 }, { 98895, 2 }, { 98936, 2 },
{ 98950, 2 }, { 98980, 2 }, { 99033, 2 }, { 99045, 2 }, { 99135, 2 }, { 99315, 30 }, { 99324, 2 }, { 99346, 2 }, { 99418, 2 }, { 99505, 2 }, { 99557, 2 }, { 99559, 2 }, { 99586, 2 }, { 99622, 2 }, { 99770, 1 }, { 99790, 2 }, { 99810, 2 }, { 99871, 1 }, { 99926, 2 }, { 99927, 2 }, { 99978, 2 }, { 99980, 2 }, { 100022, 3 },
{ 100024, 1 }, { 100069, 2 }, { 100150, 2 }, { 100225, 2 }, { 100246, 1 }, { 100310, 2 }, { 100361, 2 }, { 100428, 1 }, { 100434, 2 }, { 100450, 4 }, { 100546, 2 }, { 100551, 2 }, { 100551, 2 }, { 100554, 1 }, { 100597, 2 }, { 100676, 2 }, { 100693, 2 }, { 100827, 2 }, { 100928, 2 }, { 100928, 1 }, { 100935, 2 }, { 100937, 3 },
{ 101034, 2 }, { 101041, 2 }, { 101154, 2 }, { 101200, 4 }, { 101250, 2 }, { 101352, 2 }, { 101403, 2 }, { 101430, 1 }, { 101508, 3 }, { 101509, 3 }, { 101523, 10 }, { 101604, 2 }, { 101637, 2 }, { 101681, 4 }, { 101759, 1 }, { 101773, 1 }, { 101836, 1 }, { 101882, 4 }, { 101895, 2 }, { 101897, 2 }, { 101939, 2 }, { 101951, 6 },
{ 101956, 5 }, { 102055, 1 }, { 102085, 2 }, { 102093, 2 }, { 102209, 2 }, { 102258, 6 }, { 102271, 2 }, { 102284, 2 }, { 102332, 2 }, { 102354, 2 }, { 102366, 2 }, { 102424, 3 }, { 102456, 2 }, { 102496, 1 }, { 102497, 3 }, { 102519, 3 }, { 102554, 1 }, { 102610, 5 }, { 102657, 2 }, { 102661, 4 }, { 102695, 4 }, { 102707, 12 },
{ 102910, 2 }, { 102930, 5 }, { 102937, 9 }, { 102938, 7 }, { 102965, 6 }, { 102969, 7 }, { 103031, 2 }, { 103062, 2 }, { 103096, 2 }, { 103146, 2 }, { 103159, 2 }, { 103223, 2 }, { 103267, 2 }, { 103296, 2 }, { 103303, 2 }, { 103487, 2 }, { 103491, 2 }, { 103599, 2 }, { 103677, 2 }, { 103903, 1 }, { 104040, 2 }, { 104047, 1 },
{ 104052, 2 }, { 104057, 4 }, { 104057, 2 }, { 104062, 4 }, { 104091, 2 }, { 104189, 3 }, { 104283, 8 }, { 104288, 4 }, { 104305, 3 }, { 104445, 2 }, { 104472, 2 }, { 104475, 1 }, { 104497, 4 }, { 104548, 2 }, { 104582, 2 }, { 104626, 1 }, { 104716, 2 }, { 104826, 2 }, { 104849, 2 }, { 104872, 1 }, { 104945, 1 }, { 104948, 2 },
{ 105066, 2 }, { 105071, 1 }, { 105198, 4 }, { 105198, 4 }, { 105203, 2 }, { 105256, 6 }, { 105263, 2 }, { 105329, 2 }, { 105515, 2 }, { 105566, 2 }, { 105566, 2 }, { 105585, 2 }, { 105678, 2 }, { 105852, 2 }, { 105877, 2 }, { 105911, 2 }, { 106022, 1 }, { 106033, 2 }, { 106080, 2 }, { 106192, 2 }, { 106220, 3 }, { 106243, 2 },
{ 106323, 11 }, { 106371, 2 }, { 106608, 2 }, { 106624, 2 }, { 106680, 3 }, { 106688, 1 }, { 106800, 1 }, { 106800, 1 }, { 106821, 4 }, { 106853, 1 }, { 106930, 3 }, { 106937, 2 }, { 106955, 2 }, { 106996, 2 }, { 106996, 1 }, { 107148, 4 }, { 107213, 16 }, { 107213, 2 }, { 107243, 2 }, { 107360, 2 }, { 107408, 2 }, { 107509, 4 },
{ 107572, 2 }, { 107592, 2 }, { 107644, 5 }, { 107679, 2 }, { 107705, 3 }, { 107761, 4 }, { 107780, 2 }, { 107825, 2 }, { 108007, 2 }, { 108041, 4 }, { 108058, 2 }, { 108071, 1 }, { 108132, 2 }, { 108164, 2 }, { 108189, 2 }, { 108210, 2 }, { 108330, 2 }, { 108430, 2 }, { 108450, 2 }, { 108469, 2 }, { 108484, 2 }, { 108533, 2 },
{ 108588, 2 }, { 108594, 2 }, { 108690, 2 }, { 108785, 1 }, { 108814, 2 }, { 108818, 1 }, { 108820, 2 }, { 108889, 2 }, { 108951, 2 }, { 108959, 2 }, { 108963, 2 }, { 109034, 2 }, { 109172, 1 }, { 109176, 2 }, { 109195, 3 }, { 109229, 2 }, { 109256, 2 }, { 109290, 2 }, { 109304, 2 }, { 109333, 2 }, { 109343, 4 }, { 109347, 7 },
{ 109387, 2 }, { 109421, 1 }, { 109497, 2 }, { 109501, 3 }, { 109513, 2 }, { 109525, 3 }, { 109625, 4 }, { 109710, 2 }, { 109740, 2 }, { 109751, 2 }, { 109761, 2 }, { 109890, 8 }, { 109891, 4 }, { 109909, 2 }, { 109923, 1 }, { 110017, 2 }, { 110046, 2 }, { 110111, 2 }, { 110258, 2 }, { 110340, 2 }, { 110352, 2 }, { 110398, 2 },
{ 110583, 2 }, { 110600, 13 }, { 110626, 3 }, { 110709, 2 }, { 110772, 4 }, { 110773, 2 }, { 110813, 1 }, { 110890, 2 }, { 110898, 2 }, { 110954, 2 }, { 111120, 2 }, { 111132, 3 }, { 111163, 8 }, { 111224, 2 }, { 111340, 2 }, { 111398, 2 }, { 111555, 2 }, { 111597, 3 }, { 111607, 2 }, { 111655, 2 }, { 111691, 3 }, { 111835, 2 },
{ 111854, 2 }, { 111876, 16 }, { 111884, 1 }, { 111884, 2 }, { 111929, 2 }, { 111941, 2 }, { 111969, 2 }, { 112003, 2 }, { 112165, 2 }, { 112365, 2 }, { 112450, 1 }, { 112521, 2 }, { 112649, 4 }, { 112665, 2 }, { 112881, 1 }, { 112882, 2 }, { 112906, 2 }, { 112951, 2 }, { 112994, 2 }, { 112997, 2 }, { 113002, 2 }, { 113056, 1 },
{ 113077, 2 }, { 113208, 1 }, { 113320, 2 }, { 113326, 3 }, { 113375, 2 }, { 113530, 30 }, { 113530, 30 }, { 113537, 1 }, { 113563, 14 }, { 113592, 2 }, { 113637, 2 }, { 113768, 2 }, { 113850, 5 }, { 113892, 2 }, { 113916, 2 }, { 113965, 2 }, { 113976, 2 }, { 114037, 2 }, { 114149, 1 }, { 114158, 9 }, { 114201, 2 }, { 114262, 2 },
{ 114268, 4 }, { 114353, 2 }, { 114388, 2 }, { 114404, 2 }, { 114428, 5 }, { 114438, 2 }, { 114541, 2 }, { 114550, 2 }, { 114561, 2 }, { 114625, 3 }, { 114730, 2 }, { 114770, 1 }, { 114815, 4 }, { 114998, 2 }, { 115077, 2 }, { 115093, 2 }, { 115120, 2 }, { 115194, 2 }, { 115216, 3 }, { 115299, 2 }, { 115391, 3 }, { 115410, 2 },
{ 115542, 33 }, { 115581, 2 }, { 115618, 2 }, { 115645, 5 }, { 115647, 2 }, { 115697, 2 }, { 115725, 2 }, { 115740, 2 }, { 115757, 2 }, { 115763, 2 }, { 115770, 2 }, { 115787, 2 }, { 115916, 2 }, { 115928, 2 }, { 115962, 2 }, { 116020, 2 }, { 116022, 1 }, { 116089, 2 }, { 116159, 1 }, { 116196, 2 }, { 116247, 2 }, { 116254, 7 },
{ 116336, 2 }, { 116409, 2 }, { 116459, 2 }, { 116569, 2 }, { 116619, 2 }, { 116688, 2 }, { 116733, 2 }, { 116807, 3 }, { 116843, 2 }, { 116886, 1 }, { 116902, 2 }, { 116931, 2 }, { 116952, 2 }, { 116952, 2 }, { 117177, 2 }, { 117189, 2 }, { 117206, 2 }, { 117260, 29 }, { 117271, 6 }, { 117276, 3 }, { 117276, 5 }, { 117278, 3 },
{ 117278, 2 }, { 117359, 4 }, { 117380, 2 }, { 117414, 1 }, { 117503, 2 }, { 117517, 2 }, { 117530, 2 }, { 117574, 4 }, { 117575, 5 }, { 117577, 2 }, { 117606, 2 }, { 117645, 2 }, { 117655, 2 }, { 117692, 2 }, { 117705, 1 }, { 117731, 1 }, { 117762, 4 }, { 117780, 2 }, { 117974, 1 }, { 118057, 1 }, { 118099, 2 }, { 118107, 2 },
{ 118113, 2 }, { 118175, 2 }, { 118198, 2 }, { 118232, 2 }, { 118326, 1 }, { 118438, 31 }, { 118469, 2 }, { 118521, 31 }, { 118565, 2 }, { 118593, 2 }, { 118602, 2 }, { 118652, 2 }, { 118668, 2 }, { 118689, 3 }, { 118703, 14 }, { 118705, 2 }, { 118813, 2 }, { 118825, 2 }, { 118894, 3 }, { 118915, 2 }, { 118962, 2 }, { 118986, 2 },
{ 119045, 2 }, { 119054, 1 }, { 119054, 1 }, { 119119, 2 }, { 119149, 2 }, { 119206, 1 }, { 119316, 2 }, { 119387, 2 }, { 119404, 3 }, { 119516, 2 }, { 119520, 2 }, { 119571, 3 }, { 119573, 2 }, { 119610, 5 }, { 119621, 2 }, { 119623, 4 }, { 119672, 2 }, { 119692, 3 }, { 119734, 2 }, { 119742, 1 }, { 119754, 1 }, { 119785, 2 },
{ 120001, 2 }, { 120115, 4 }, { 120260, 2 }, { 120314, 2 }, { 120416, 2 }, { 120435, 1 }, { 120450, 3 }, { 120530, 2 }, { 120550, 5 }, { 120730, 2 }, { 120731, 2 }, { 120751, 3 }, { 120755, 2 }, { 120869, 2 }, { 120988, 2 }, { 121061, 2 }, { 121177, 2 }, { 121212, 2 }, { 121214, 1 }, { 121286, 2 }, { 121331, 1 }, { 121344, 2 },
{ 121407, 2 }, { 121424, 1 }, { 121491, 2 }, { 121568, 1 }, { 121588, 6 }, { 121651, 2 }, { 121676, 2 }, { 121785, 4 }, { 121830, 3 }, { 121919, 1 }, { 121951, 2 }, { 121991, 1 }, { 122056, 2 }, { 122062, 2 }, { 122144, 2 }, { 122183, 1 }, { 122331, 2 }, { 122466, 2 }, { 122558, 2 }, { 122570, 2 }, { 122676, 2 }, { 122733, 2 },
{ 122774, 6 }, { 122783, 2 }, { 122825, 2 }, { 122865, 2 }, { 122884, 2 }, { 122892, 2 }, { 122911, 2 }, { 122929, 2 }, { 122936, 2 }, { 123190, 2 }, { 123271, 2 }, { 123271, 2 }, { 123302, 7 }, { 123391, 2 }, { 123394, 2 }, { 123416, 1 }, { 123708, 2 }, { 123752, 2 }, { 123761, 2 }, { 123783, 2 }, { 123794, 2 }, { 123817, 2 },
{ 123820, 1 }, { 123823, 1 }, { 123857, 3 }, { 123886, 2 }, { 124023, 1 }, { 124029, 2 }, { 124042, 2 }, { 124056, 3 }, { 124071, 6 }, { 124105, 5 }, { 124143, 2 }, { 124191, 2 }, { 124207, 1 }, { 124257, 2 }, { 124306, 3 }, { 124338, 2 }, { 124388, 8 }, { 124400, 2 }, { 124418, 2 }, { 124502, 2 }, { 124521, 1 }, { 124533, 2 },
{ 124645, 2 }, { 124685, 1 }, { 124694, 2 }, { 124700, 1 }, { 124736, 2 }, { 124891, 7 }, { 124920, 2 }, { 124983, 2 }, { 125014, 2 }, { 125038, 2 }, { 125084, 2 }, { 125162, 2 }, { 125193, 2 }, { 125285, 2 }, { 125368, 2 }, { 125409, 2 }, { 125570, 2 }, { 125601, 2 }, { 125641, 1 }, { 125721, 2 }, { 125731, 2 }, { 125803, 2 },
{ 125904, 2 }, { 125973, 2 }, { 126018, 1 }, { 126034, 5 }, { 126094, 1 }, { 126144, 1 }, { 126195, 2 }, { 126297, 2 }, { 126389, 2 }, { 126429, 2 }, { 126439, 2 }, { 126499, 2 }, { 126501, 1 }, { 126587, 2 }, { 126663, 2 }, { 126681, 2 }, { 126687, 1 }, { 126781, 2 }, { 126783, 2 }, { 126840, 8 }, { 126843, 2 }, { 126959, 2 },
{ 127015, 2 }, { 127101, 2 }, { 127149, 2 }, { 127197, 3 }, { 127268, 2 }, { 127372, 2 }, { 127385, 2 }, { 127473, 4 }, { 127539, 2 }, { 127598, 2 }, { 127613, 14 }, { 127683, 3 }, { 127684, 2 }, { 127697, 2 }, { 127698, 3 }, { 127773, 2 }, { 127781, 1 }, { 127839, 2 }, { 127905, 2 }, { 127949, 2 }, { 128035, 2 }, { 128046, 1 },
{ 128167, 2 }, { 128271, 2 }, { 128307, 1 }, { 128320, 2 }, { 128330, 2 }, { 128375, 2 }, { 128381, 4 }, { 128447, 2 }, { 128462, 2 }, { 128466, 3 }, { 128466, 2 }, { 128496, 2 }, { 128589, 2 }, { 128616, 3 }, { 128679, 1 }, { 128770, 1 }, { 128793, 2 }, { 128802, 2 }, { 128813, 2 }, { 128900, 2 }, { 128949, 2 }, { 129269, 2 },
{ 129271, 3 }, { 129278, 2 }, { 129343, 1 }, { 129408, 2 }, { 129408, 1 }, { 129421, 6 }, { 129461, 2 }, { 129469, 3 }, { 129482, 2 }, { 129502, 2 }, { 129512, 2 }, { 129551, 2 }, { 129629, 2 }, { 129632, 2 }, { 129679, 1 }, { 129725, 2 }, { 130007, 2 }, { 130018, 16 }, { 130057, 2 }, { 130071, 2 }, { 130087, 2 }, { 130188, 1 },
{ 130202, 2 }, { 130316, 2 }, { 130328, 1 }, { 130466, 2 }, { 130549, 2 }, { 130649, 2 }, { 130705, 3 }, { 130800, 2 }, { 130907, 2 }, { 130989, 2 }, { 131103, 2 }, { 131127, 2 }, { 131200, 5 }, { 131241, 6 }, { 131351, 2 }, { 131413, 2 }, { 131448, 2 }, { 131599, 2 }, { 131634, 1 }, { 131687, 2 }, { 131739, 2 }, { 131758, 2 },
{ 131765, 2 }, { 131787, 3 }, { 131819, 3 }, { 131868, 2 }, { 131886, 2 }, { 131901, 4 }, { 131977, 2 }, { 131990, 2 }, { 132035, 2 }, { 132035, 2 }, { 132043, 2 }, { 132173, 2 }, { 132181, 4 }, { 132181, 6 }, { 132194, 5 }, { 132252, 2 }, { 132262, 6 }, { 132271, 1 }, { 132285, 2 }, { 132328, 2 }, { 132335, 1 }, { 132337, 1 },
{ 132389, 5 }, { 132430, 2 }, { 132451, 2 }, { 132499, 4 }, { 132503, 1 }, { 132520, 4 }, { 132541, 4 }, { 132860, 2 }, { 132862, 4 }, { 132874, 12 }, { 132874, 13 }, { 132875, 12 }, { 132911, 2 }, { 132973, 2 }, { 133051, 2 }, { 133062, 2 }, { 133067, 2 }, { 133138, 2 }, { 133184, 2 }, { 133231, 2 }, { 133297, 3 }, { 133344, 2 },
{ 133385, 4 }, { 133408, 2 }, { 133464, 2 }, { 133522, 2 }, { 133631, 2 }, { 133631, 2 }, { 133702, 2 }, { 133705, 1 }, { 133721, 2 }, { 133746, 2 }, { 133773, 3 }, { 133819, 2 }, { 133843, 2 }, { 133929, 2 }, { 133946, 2 }, { 134113, 4 }, { 134151, 2 }, { 134289, 1 }, { 134385, 2 }, { 134429, 2 }, { 134506, 2 }, { 134511, 2 },
{ 134521, 2 }, { 134558, 1 }, { 134710, 2 }, { 134738, 2 }, { 134751, 3 }, { 134818, 2 }, { 134820, 4 }, { 134879, 2 }, { 134919, 2 }, { 134947, 2 }, { 134948, 3 }, { 135040, 3 }, { 135125, 10 }, { 135155, 2 }, { 135228, 2 }, { 135255, 2 }, { 135296, 3 }, { 135322, 2 }, { 135349, 2 }, { 135428, 3 }, { 135476, 1 }, { 135503, 2 },
{ 135524, 2 }, { 135550, 4 }, { 135594, 2 }, { 135597, 2 }, { 135624, 3 }, { 135741, 2 }, { 135753, 2 }, { 135842, 2 }, { 135853, 2 }, { 135896, 3 }, { 136004, 1 }, { 136061, 1 }, { 136068, 1 }, { 136106, 2 }, { 136145, 2 }, { 136145, 2 }, { 136173, 2 }, { 136186, 2 }, { 136196, 2 }, { 136201, 2 }, { 136211, 2 }, { 136268, 2 },
{ 136298, 2 }, { 136377, 2 }, { 136420, 2 }, { 136475, 2 }, { 136486, 1 }, { 136554, 2 }, { 136641, 2 }, { 136770, 1 }, { 136873, 2 }, { 136877, 1 }, { 136906, 2 }, { 137092, 2 }, { 137143, 2 }, { 137200, 3 }, { 137232, 2 }, { 137239, 2 }, { 137248, 2 }, { 137281, 1 }, { 137301, 2 }, { 137314, 3 }, { 137352, 1 }, { 137365, 2 },
{ 137375, 2 }, { 137411, 2 }, { 137424, 2 }, { 137516, 2 }, { 137532, 2 }, { 137593, 2 }, { 137600, 2 }, { 137658, 2 }, { 137703, 2 }, { 137766, 2 }, { 137791, 2 }, { 137801, 2 }, { 137864, 2 }, { 137870, 3 }, { 137931, 2 }, { 138009, 3 }, { 138013, 1 }, { 138013, 1 }, { 138066, 2 }, { 138073, 2 }, { 138114, 2 }, { 138150, 2 },
{ 138236, 2 }, { 138276, 2 }, { 138286, 2 }, { 138298, 3 }, { 138309, 1 }, { 138373, 3 }, { 138524, 2 }, { 138535, 1 }, { 138593, 4 }, { 138611, 1 }, { 138725, 2 }, { 138807, 2 }, { 138819, 3 }, { 138849, 5 }, { 138867, 2 }, { 138907, 2 }, { 138930, 3 }, { 139026, 2 }, { 139102, 2 }, { 139108, 3 }, { 139184, 1 }, { 139209, 3 },
{ 139282, 2 }, { 139289, 4 }, { 139382, 1 }, { 139421, 1 }, { 139436, 2 }, { 139450, 1 }, { 139523, 3 }, { 139533, 2 }, { 139590, 2 }, { 139590, 2 }, { 139722, 2 }, { 139785, 2 }, { 139785, 1 }, { 139798, 2 }, { 139813, 2 }, { 139868, 2 }, { 139935, 3 }, { 139990, 3 }, { 140050, 2 }, { 140177, 2 }, { 140177, 4 }, { 140408, 2 },
{ 140420, 3 }, { 140461, 2 }, { 140578, 15 }, { 140605, 1 }, { 140662, 1 }, { 140755, 2 }, { 140786, 2 }, { 140846, 2 }, { 140874, 2 }, { 140959, 1 }, { 140973, 2 }, { 141128, 2 }, { 141132, 2 }, { 141257, 2 }, { 141290, 1 }, { 141360, 2 }, { 141472, 2 }, { 141545, 2 }, { 141545, 2 }, { 141575, 1 }, { 141606, 5 }, { 141655, 2 },
{ 141735, 2 }, { 141767, 5 }, { 141796, 2 }, { 141841, 2 }, { 141915, 2 }, { 141923, 1 }, { 141932, 2 }, { 141994, 2 }, { 142018, 2 }, { 142029, 3 }, { 142072, 2 }, { 142128, 2 }, { 142133, 1 }, { 142261, 2 }, { 142304, 1 }, { 142400, 2 }, { 142401, 2 }, { 142409, 2 }, { 142479, 2 }, { 142522, 1 }, { 142552, 1 }, { 142589, 2 },
{ 142596, 2 }, { 142753, 1 }, { 142766, 2 }, { 142796, 2 }, { 142836, 2 }, { 142871, 2 }, { 143058, 3 }, { 143059, 6 }, { 143063, 3 }, { 143065, 2 }, { 143141, 4 }, { 143173, 2 }, { 143374, 2 }, { 143399, 2 }, { 143406, 2 }, { 143429, 3 }, { 143430, 2 }, { 143462, 1 }, { 143579, 2 }, { 143663, 2 }, { 143844, 3 }, { 143851, 2 },
{ 143926, 2 }, { 143931, 2 }, { 144051, 6 }, { 144085, 10 }, { 144147, 2 }, { 144188, 4 }, { 144238, 4 }, { 144353, 2 }, { 144465, 2 }, { 144474, 2 }, { 144637, 2 }, { 144638, 1 }, { 144648, 1 }, { 144661, 3 }, { 144812, 2 }, { 144847, 2 }, { 144901, 8 }, { 145058, 2 }, { 145122, 8 }, { 145134, 2 }, { 145150, 2 }, { 145299, 1 },
{ 145313, 2 }, { 145314, 3 }, { 145374, 2 }, { 145412, 2 }, { 145432, 2 }, { 145446, 2 }, { 145534, 3 }, { 145592, 2 }, { 145614, 2 }, { 145648, 2 }, { 145721, 2 }, { 145858, 1 }, { 145970, 3 }, { 145984, 3 }, { 146004, 2 }, { 146016, 3 }, { 146048, 2 }, { 146097, 3 }, { 146103, 2 }, { 146136, 2 }, { 146194, 3 }, { 146230, 1 },
{ 146254, 2 }, { 146261, 4 }, { 146269, 4 }, { 146393, 2 }, { 146411, 3 }, { 146501, 2 }, { 146547, 2 }, { 146547, 2 }, { 146573, 2 }, { 146616, 2 }, { 146622, 3 }, { 146728, 3 }, { 146781, 5 }, { 146805, 4 }, { 146921, 2 }, { 147002, 3 }, { 147072, 2 }, { 147159, 2 }, { 147170, 2 }, { 147203, 1 }, { 147245, 2 }, { 147278, 2 },
{ 147422, 2 }, { 147471, 2 }, { 147491, 2 }, { 147607, 4 }, { 147693, 2 }, { 147763, 2 }, { 147775, 6 }, { 147776, 4 }, { 147824, 2 }, { 147922, 2 }, { 147922, 2 }, { 147937, 2 }, { 147957, 2 }, { 147980, 2 }, { 148008, 2 }, { 148018, 2 }, { 148046, 3 }, { 148071, 4 }, { 148106, 3 }, { 148122, 2 }, { 148139, 2 }, { 148175, 2 },
{ 148318, 2 }, { 148514, 2 }, { 148528, 2 }, { 148539, 2 }, { 148545, 2 }, { 148564, 2 }, { 148569, 2 }, { 148607, 3 }, { 148712, 2 }, { 148751, 2 }, { 148792, 4 }, { 148807, 2 }, { 148818, 2 }, { 148846, 9 }, { 148848, 2 }, { 148851, 2 }, { 148861, 3 }, { 148924, 32 }, { 148934, 2 }, { 149037, 1 }, { 149127, 3 }, { 149132, 2 },
{ 149181, 1 }, { 149181, 2 }, { 149206, 2 }, { 149216, 7 }, { 149240, 4 }, { 149240, 1 }, { 149279, 1 }, { 149280, 3 }, { 149292, 2 }, { 149314, 2 }, { 149344, 2 }, { 149364, 4 }, { 149388, 2 }, { 149438, 2 }, { 149520, 2 }, { 149566, 2 }, { 149630, 2 }, { 149682, 2 }, { 149691, 1 }, { 149703, 2 }, { 149775, 2 }, { 149796, 1 },
{ 149863, 1 }, { 149884, 2 }, { 149888, 1 }, { 149983, 2 }, { 150078, 3 }, { 150083, 6 }, { 150175, 1 }, { 150235, 2 }, { 150238, 2 }, { 150298, 3 }, { 150321, 2 }, { 150382, 2 }, { 150510, 4 }, { 150574, 2 }, { 150619, 5 }, { 150645, 2 }, { 150694, 2 }, { 150732, 8 }, { 150764, 2 }, { 150813, 2 }, { 150871, 2 }, { 150879, 2 },
{ 150888, 1 }, { 150920, 2 }, { 151009, 2 }, { 151013, 2 }, { 151019, 2 }, { 151063, 2 }, { 151067, 2 }, { 151125, 1 }, { 151151, 5 }, { 151172, 2 }, { 151197, 4 }, { 151228, 70 }, { 151292, 2 }, { 151354, 2 }, { 151392, 2 }, { 151396, 1 }, { 151412, 2 }, { 151514, 2 }, { 151529, 2 }, { 151567, 2 }, { 151589, 2 }, { 151641, 2 },
{ 151672, 2 }, { 151730, 2 }, { 151748, 2 }, { 151770, 1 }, { 151788, 2 }, { 151795, 2 }, { 151805, 2 }, { 152046, 5 }, { 152048, 3 }, { 152054, 2 }, { 152057, 3 }, { 152058, 2 }, { 152075, 2 }, { 152090, 9 }, { 152205, 2 }, { 152440, 2 }, { 152480, 2 }, { 152484, 2 }, { 152601, 2 }, { 152714, 2 }, { 152801, 2 }, { 152819, 10 },
{ 152825, 2 }, { 152896, 10 }, { 152937, 2 }, { 152938, 2 }, { 152939, 3 }, { 153042, 2 }, { 153069, 2 }, { 153099, 2 }, { 153164, 2 }, { 153234, 2 }, { 153266, 2 }, { 153345, 2 }, { 153420, 2 }, { 153479, 2 }, { 153488, 4 }, { 153502, 2 }, { 153663, 3 }, { 153740, 1 }, { 153780, 2 }, { 153824, 6 }, { 153938, 2 }, { 153985, 2 },
{ 154022, 2 }, { 154022, 1 }, { 154072, 4 }, { 154109, 2 }, { 154189, 2 }, { 154222, 2 }, { 154228, 2 }, { 154265, 15 }, { 154324, 2 }, { 154350, 2 }, { 154375, 2 }, { 154396, 2 }, { 154431, 2 }, { 154463, 2 }, { 154475, 3 }, { 154510, 1 }, { 154518, 1 }, { 154529, 2 }, { 154710, 2 }, { 154742, 2 }, { 154792, 2 }, { 154871, 4 },
{ 154960, 2 }, { 154961, 2 }, { 154964, 2 }, { 154989, 3 }, { 155002, 3 }, { 155079, 2 }, { 155105, 2 }, { 155107, 2 }, { 155258, 1 }, { 155328, 2 }, { 155328, 2 }, { 155347, 2 }, { 155369, 2 }, { 155447, 2 }, { 155482, 2 }, { 155508, 2 }, { 155531, 2 }, { 155553, 1 }, { 155647, 3 }, { 155659, 9 }, { 155859, 2 }, { 155960, 2 },
{ 156009, 2 }, { 156062, 2 }, { 156143, 3 }, { 156217, 3 }, { 156252, 7 }, { 156260, 2 }, { 156274, 2 }, { 156339, 2 }, { 156354, 3 }, { 156406, 2 }, { 156550, 2 }, { 156694, 2 }, { 156730, 12 }, { 156795, 4 }, { 156806, 3 }, { 156818, 5 }, { 156835, 3 }, { 156850, 3 }, { 156861, 4 }, { 156877, 2 }, { 156915, 6 }, { 156967, 2 },
{ 157046, 2 }, { 157208, 3 }, { 157260, 2 }, { 157364, 2 }, { 157365, 1 }, { 157371, 2 }, { 157440, 2 }, { 157453, 2 }, { 157482, 1 }, { 157505, 2 }, { 157511, 4 }, { 157522, 2 }, { 157562, 2 }, { 157562, 2 }, { 157702, 2 }, { 157734, 3 }, { 157807, 2 }, { 157851, 2 }, { 157882, 2 }, { 157957, 2 }, { 158227, 2 }, { 158284, 2 },
{ 158292, 2 }, { 158310, 3 }, { 158310, 3 }, { 158330, 2 }, { 158358, 1 }, { 158493, 2 }, { 158596, 2 }, { 158736, 2 }, { 158812, 1 }, { 158830, 2 }, { 158846, 1 }, { 158884, 1 }, { 158918, 2 }, { 159003, 2 }, { 159056, 2 }, { 159189, 2 }, { 159372, 2 }, { 159373, 2 }, { 159410, 3 }, { 159421, 4 }, { 159429, 2 }, { 159505, 2 },
{ 159559, 1 }, { 159574, 2 }, { 159587, 4 }, { 159683, 2 }, { 159745, 1 }, { 159748, 3 }, { 159858, 2 }, { 159945, 1 }, { 159971, 4 }, { 159982, 2 }, { 160079, 13 }, { 160084, 2 }, { 160085, 4 }, { 160104, 9 }, { 160197, 2 }, { 160295, 2 }, { 160365, 2 }, { 160372, 1 }, { 160392, 3 }, { 160408, 1 }, { 160446, 1 }, { 160540, 2 },
{ 160599, 1 }, { 160604, 2 }, { 160745, 3 }, { 160752, 2 }, { 160794, 2 }, { 160826, 2 }, { 160846, 2 }, { 160871, 2 }, { 160957, 2 }, { 160986, 2 }, { 161053, 2 }, { 161133, 3 }, { 161133, 1 }, { 161162, 3 }, { 161247, 2 }, { 161270, 2 }, { 161292, 6 }, { 161370, 2 }, { 161420, 2 }, { 161446, 2 }, { 161487, 2 }, { 161511, 3 },
{ 161512, 1 }, { 161580, 2 }, { 161782, 12 }, { 161784, 8 }, { 161786, 2 }, { 161786, 8 }, { 161787, 7 }, { 161795, 2 }, { 161825, 7 }, { 161833, 4 }, { 161892, 2 }, { 161930, 2 }, { 161992, 2 }, { 162054, 2 }, { 162176, 2 }, { 162183, 2 }, { 162219, 2 }, { 162245, 2 }, { 162288, 2 }, { 162361, 3 }, { 162370, 2 }, { 162388, 2 },
{ 162434, 2 }, { 162447, 2 }, { 162524, 2 }, { 162542, 3 }, { 162562, 2 }, { 162594, 2 }, { 162646, 1 }, { 162662, 2 }, { 162761, 2 }, { 162780, 2 }, { 162802, 2 }, { 162820, 3 }, { 162824, 2 }, { 162908, 2 }, { 162968, 2 }, { 163171, 2 }, { 163190, 2 }, { 163288, 1 }, { 163288, 1 }, { 163397, 2 }, { 163405, 6 }, { 163414, 1 },
{ 163506, 1 }, { 163558, 2 }, { 163565, 1 }, { 163568, 3 }, { 163619, 2 }, { 163633, 2 }, { 163678, 2 }, { 163745, 3 }, { 163765, 4 }, { 163773, 2 }, { 163793, 2 }, { 163878, 7 }, { 163949, 2 }, { 163975, 2 }, { 163991, 2 }, { 164016, 2 }, { 164020, 3 }, { 164068, 1 }, { 164076, 4 }, { 164082, 3 }, { 164176, 2 }, { 164236, 2 },
{ 164238, 1 }, { 164315, 2 }, { 164449, 2 }, { 164529, 2 }, { 164574, 4 }, { 164591, 2 }, { 164595, 2 }, { 164611, 2 }, { 164623, 4 }, { 164632, 10 }, { 164691, 2 }, { 164706, 2 }, { 164755, 2 }, { 164761, 2 }, { 164973, 2 }, { 165030, 2 }, { 165090, 2 }, { 165099, 1 }, { 165126, 2 }, { 165188, 2 }, { 165205, 2 }, { 165275, 1 },
{ 165347, 2 }, { 165381, 2 }, { 165562, 2 }, { 165563, 1 }, { 165594, 2 }, { 165641, 2 }, { 165663, 6 }, { 165759, 2 }, { 165811, 2 }, { 165822, 1 }, { 165830, 1 }, { 165903, 1 }, { 165921, 2 }, { 165953, 1 }, { 166022, 1 }, { 166294, 2 }, { 166333, 2 }, { 166420, 2 }, { 166433, 2 }, { 166442, 1 }, { 166536, 2 }, { 166543, 2 },
{ 166556, 2 }, { 166571, 2 }, { 166575, 1 }, { 166588, 2 }, { 166601, 2 }, { 166663, 3 }, { 166692, 1 }, { 166710, 2 }, { 166759, 2 }, { 166785, 3 }, { 166842, 2 }, { 166843, 2 }, { 166864, 2 }, { 166902, 2 }, { 166996, 2 }, { 166999, 2 }, { 167038, 2 }, { 167112, 4 }, { 167112, 2 }, { 167177, 2 }, { 167180, 2 }, { 167229, 1 },
{ 167298, 2 }, { 167306, 4 }, { 167309, 3 }, { 167402, 2 }, { 167405, 2 }, { 167433, 2 }, { 167435, 1 }, { 167461, 3 }, { 167553, 3 }, { 167688, 5 }, { 167689, 2 }, { 167709, 2 }, { 167744, 2 }, { 167821, 2 }, { 167825, 2 }, { 167925, 10 }, { 167969, 2 }, { 168024, 2 }, { 168089, 2 }, { 168104, 2 }, { 168194, 2 }, { 168305, 2 },
{ 168316, 2 }, { 168366, 2 }, { 168423, 2 }, { 168568, 3 }, { 168582, 2 }, { 168615, 3 }, { 168618, 2 }, { 168638, 2 }, { 168671, 2 }, { 168736, 2 }, { 168747, 2 }, { 168750, 4 }, { 168808, 3 }, { 168814, 4 }, { 168820, 2 }, { 168914, 2 }, { 168968, 2 }, { 168979, 2 }, { 169006, 2 }, { 169069, 2 }, { 169106, 3 }, { 169158, 2 },
{ 169158, 2 }, { 169189, 2 }, { 169253, 2 }, { 169259, 1 }, { 169279, 1 }, { 169325, 8 }, { 169349, 2 }, { 169353, 2 }, { 169378, 2 }, { 169432, 2 }, { 169476, 1 }, { 169476, 1 }, { 169525, 2 }, { 169538, 7 }, { 169555, 2 }, { 169571, 2 }, { 169594, 4 }, { 169687, 2 }, { 169799, 2 }, { 169831, 2 }, { 170042, 2 }, { 170061, 2 },
{ 170065, 1 }, { 170128, 6 }, { 170148, 20 }, { 170215, 70 }, { 170256, 60 }, { 170266, 69 }, { 170275, 7 }, { 170277, 6 }, { 170500, 3 }, { 170516, 3 }, { 170601, 2 }, { 170666, 2 }, { 170668, 4 }, { 170668, 1 }, { 170716, 3 }, { 170728, 3 }, { 170735, 5 }, { 170847, 3 }, { 170852, 9 }, { 170858, 2 }, { 170859, 3 }, { 170956, 2 },
{ 170956, 1 }, { 170967, 2 }, { 171005, 2 }, { 171113, 2 }, { 171279, 2 }, { 171400, 2 }, { 171405, 2 }, { 171448, 1 }, { 171490, 2 }, { 171567, 32 }, { 171590, 2 }, { 171723, 2 }, { 171737, 3 }, { 171958, 2 }, { 171967, 2 }
};
}
/* sub-class to avoid 65k limit of a single class */
private static class SampleDataHolder2 {
/*
* Array of [milliseconds, latency]
*/
private static int[][] data = new int[][] { { 0, 3 }, { 43, 33 }, { 45, 11 }, { 45, 1 }, { 68, 13 }, { 88, 10 }, { 158, 68 }, { 158, 4 }, { 169, 168 }, { 267, 68 }, { 342, 68 }, { 438, 68 }, { 464, 7 }, { 504, 68 }, { 541, 6 }, { 541, 68 }, { 562, 68 }, { 581, 3 }, { 636, 68 }, { 778, 68 }, { 825, 1 }, { 859, 68 },
{ 948, 1 }, { 1043, 68 }, { 1145, 68 }, { 1152, 1 }, { 1218, 5 }, { 1229, 68 }, { 1259, 68 }, { 1333, 68 }, { 1349, 68 }, { 1392, 68 }, { 1468, 1 }, { 1551, 68 }, { 1586, 68 }, { 1685, 68 }, { 1696, 1 }, { 1807, 68 }, { 1817, 3 }, { 1817, 6 }, { 1847, 68 }, { 1870, 68 }, { 1939, 68 }, { 2050, 68 }, { 2129, 3 }, { 2141, 68 },
{ 2265, 68 }, { 2414, 1 }, { 2693, 68 }, { 2703, 68 }, { 2791, 68 }, { 2838, 68 }, { 2906, 68 }, { 2981, 68 }, { 3008, 68 }, { 3026, 4 }, { 3077, 68 }, { 3273, 68 }, { 3282, 68 }, { 3286, 68 }, { 3318, 3 }, { 3335, 5 }, { 3710, 68 }, { 3711, 1 }, { 3745, 68 }, { 3748, 4 }, { 3767, 3 }, { 3809, 3 }, { 3835, 35 }, { 4083, 1 },
{ 4116, 68 }, { 4117, 1 }, { 4157, 1 }, { 4279, 68 }, { 4344, 68 }, { 4452, 68 }, { 4530, 68 }, { 4583, 68 }, { 4647, 3 }, { 4758, 68 }, { 4776, 68 }, { 4793, 68 }, { 4901, 68 }, { 4909, 68 }, { 4962, 68 }, { 4984, 68 }, { 5022, 68 }, { 5139, 68 }, { 5166, 1 }, { 5174, 68 }, { 5187, 68 }, { 5225, 68 }, { 5234, 68 }, { 5263, 1 },
{ 5325, 68 }, { 5355, 4 }, { 5407, 1 }, { 5414, 68 }, { 5589, 68 }, { 5595, 68 }, { 5747, 68 }, { 5780, 68 }, { 5788, 68 }, { 5796, 68 }, { 5818, 68 }, { 5975, 1 }, { 6018, 1 }, { 6270, 68 }, { 6272, 68 }, { 6348, 68 }, { 6372, 68 }, { 6379, 68 }, { 6439, 68 }, { 6442, 68 }, { 6460, 68 }, { 6460, 68 }, { 6509, 68 }, { 6511, 1 },
{ 6514, 4 }, { 6530, 8 }, { 6719, 68 }, { 6760, 68 }, { 6784, 68 }, { 6838, 1 }, { 6861, 68 }, { 6947, 68 }, { 7013, 68 }, { 7075, 68 }, { 7122, 5 }, { 7130, 68 }, { 7209, 3 }, { 7259, 68 }, { 7309, 1 }, { 7315, 3 }, { 7322, 68 }, { 7348, 68 }, { 7420, 68 }, { 7461, 68 }, { 7545, 68 }, { 7554, 3 }, { 7630, 68 }, { 7666, 68 },
{ 7815, 1 }, { 7972, 1 }, { 7972, 68 }, { 7988, 68 }, { 8049, 8 }, { 8254, 68 }, { 8269, 68 }, { 8352, 1 }, { 8378, 68 }, { 8526, 68 }, { 8531, 68 }, { 8583, 68 }, { 8615, 68 }, { 8619, 3 }, { 8623, 68 }, { 8692, 1 }, { 8698, 68 }, { 8773, 68 }, { 8777, 3 }, { 8822, 68 }, { 8929, 68 }, { 8935, 68 }, { 9025, 68 }, { 9054, 68 },
{ 9056, 1 }, { 9086, 68 }, { 9147, 3 }, { 9219, 68 }, { 9230, 3 }, { 9248, 68 }, { 9283, 68 }, { 9314, 68 }, { 9418, 1 }, { 9426, 68 }, { 9456, 1 }, { 9594, 68 }, { 9628, 68 }, { 9642, 68 }, { 9646, 68 }, { 9686, 1 }, { 9709, 68 }, { 9771, 3 }, { 9782, 68 }, { 9884, 68 }, { 9914, 5 }, { 10004, 4 }, { 10033, 6 }, { 10052, 68 },
{ 10086, 68 }, { 10168, 68 }, { 10176, 1 }, { 10228, 68 }, { 10312, 68 }, { 10372, 68 }, { 10622, 68 }, { 10685, 68 }, { 10687, 1 }, { 10787, 68 }, { 11010, 68 }, { 11024, 68 }, { 11044, 68 }, { 11086, 68 }, { 11149, 1 }, { 11198, 68 }, { 11265, 68 }, { 11302, 68 }, { 11326, 68 }, { 11354, 68 }, { 11404, 1 }, { 11473, 68 },
{ 11506, 68 }, { 11548, 4 }, { 11575, 68 }, { 11621, 4 }, { 11625, 3 }, { 11625, 1 }, { 11642, 4 }, { 11859, 5 }, { 11870, 68 }, { 11872, 3 }, { 11880, 7 }, { 11886, 3 }, { 11905, 6 }, { 11880, 3 }, { 11912, 6 }, { 11916, 4 }, { 11916, 3 }, { 11965, 4 }, { 12068, 13 }, { 12106, 68 }, { 12120, 68 }, { 12221, 68 }, { 12257, 68 },
{ 12361, 68 }, { 12411, 68 }, { 12473, 3 }, { 12554, 68 }, { 12583, 68 }, { 12654, 68 }, { 12665, 68 }, { 12744, 1 }, { 12775, 68 }, { 12858, 68 }, { 12993, 68 }, { 13007, 3 }, { 13025, 4 }, { 13038, 68 }, { 13092, 4 }, { 13094, 5 }, { 13095, 1 }, { 13110, 68 }, { 13116, 1 }, { 13140, 68 }, { 13169, 1 }, { 13186, 68 },
{ 13202, 68 }, { 13202, 1 }, { 13256, 68 }, { 13344, 68 }, { 13373, 68 }, { 13396, 3 }, { 13446, 68 }, { 13451, 3 }, { 13475, 68 }, { 13521, 1 }, { 13587, 68 }, { 13592, 68 }, { 13708, 3 }, { 13711, 1 }, { 13741, 1 }, { 13757, 1 }, { 13847, 68 }, { 13881, 3 }, { 13915, 1 }, { 14005, 68 }, { 14028, 68 }, { 14037, 68 },
{ 14074, 68 }, { 14135, 68 }, { 14176, 68 }, { 14227, 68 }, { 14228, 68 }, { 14271, 3 }, { 14279, 3 }, { 14493, 68 }, { 14535, 3 }, { 14535, 1 }, { 14680, 68 }, { 14717, 68 }, { 14725, 1 }, { 14790, 68 }, { 14801, 1 }, { 14959, 68 }, { 15052, 68 }, { 15055, 1 }, { 15055, 1 }, { 15075, 68 }, { 15103, 8 }, { 15153, 16 },
{ 15191, 68 }, { 15240, 68 }, { 15313, 68 }, { 15323, 68 }, { 15341, 1 }, { 15383, 68 }, { 15387, 68 }, { 15491, 68 }, { 15534, 68 }, { 15539, 68 }, { 15549, 68 }, { 15554, 1 }, { 15664, 1 }, { 15726, 68 }, { 15807, 68 }, { 15842, 68 }, { 15897, 68 }, { 15913, 3 }, { 15925, 68 }, { 15935, 68 }, { 16131, 1 }, { 16211, 3 },
{ 16249, 68 }, { 16268, 68 }, { 16307, 68 }, { 16398, 68 }, { 16498, 68 }, { 16518, 1 }, { 16552, 1 }, { 16571, 68 }, { 16592, 68 }, { 16601, 3 }, { 16638, 68 }, { 16698, 68 }, { 16712, 1 }, { 16767, 68 }, { 16789, 68 }, { 16992, 68 }, { 17015, 68 }, { 17035, 68 }, { 17074, 3 }, { 17086, 3 }, { 17086, 1 }, { 17092, 1 },
{ 17110, 4 }, { 17116, 3 }, { 17236, 68 }, { 17291, 68 }, { 17291, 68 }, { 17340, 68 }, { 17342, 1 }, { 17360, 3 }, { 17436, 3 }, { 17457, 68 }, { 17508, 1 }, { 17556, 68 }, { 17601, 68 }, { 17639, 68 }, { 17671, 68 }, { 17743, 68 }, { 17857, 68 }, { 17915, 68 }, { 17992, 68 }, { 18077, 1 }, { 18088, 68 }, { 18158, 1 },
{ 18239, 16 }, { 18242, 68 }, { 18252, 3 }, { 18299, 1 }, { 18405, 68 }, { 18433, 68 }, { 18444, 68 }, { 18490, 68 }, { 18497, 68 }, { 18516, 68 }, { 18540, 68 }, { 18598, 68 }, { 18649, 68 }, { 18658, 68 }, { 18683, 68 }, { 18728, 68 }, { 18767, 1 }, { 18821, 68 }, { 18868, 68 }, { 18876, 68 }, { 18914, 14 }, { 19212, 1 },
{ 19215, 1 }, { 19293, 68 }, { 19303, 68 }, { 19336, 68 }, { 19376, 68 }, { 19419, 68 }, { 19558, 68 }, { 19559, 1 }, { 19609, 68 }, { 19688, 68 }, { 19724, 68 }, { 19820, 1 }, { 19851, 68 }, { 19881, 68 }, { 19966, 68 }, { 19983, 3 }, { 19988, 4 }, { 20047, 1 }, { 20062, 68 }, { 20091, 1 }, { 20152, 1 }, { 20183, 1 },
{ 20208, 68 }, { 20346, 68 }, { 20386, 1 }, { 20459, 68 }, { 20505, 68 }, { 20520, 1 }, { 20560, 3 }, { 20566, 3 }, { 20566, 1 }, { 20610, 68 }, { 20652, 68 }, { 20694, 68 }, { 20740, 68 }, { 20756, 68 }, { 20825, 3 }, { 20895, 68 }, { 20959, 1 }, { 20995, 68 }, { 21017, 3 }, { 21039, 68 }, { 21086, 1 }, { 21109, 3 }, { 21139, 3 },
{ 21206, 68 }, { 21230, 68 }, { 21251, 3 }, { 21352, 68 }, { 21353, 68 }, { 21370, 3 }, { 21389, 1 }, { 21445, 3 }, { 21475, 68 }, { 21528, 68 }, { 21559, 3 }, { 21604, 68 }, { 21606, 1 }, { 21815, 68 }, { 21858, 3 }, { 21860, 3 }, { 22015, 68 }, { 22065, 68 }, { 22098, 5 }, { 22105, 68 }, { 22158, 3 }, { 22197, 68 }, { 22254, 1 },
{ 22353, 68 }, { 22404, 4 }, { 22422, 68 }, { 22569, 68 }, { 22634, 68 }, { 22639, 68 }, { 22861, 68 }, { 22868, 68 }, { 22876, 1 }, { 22902, 68 }, { 22925, 68 }, { 23080, 68 }, { 23085, 3 }, { 23089, 5 }, { 23329, 1 }, { 23349, 68 }, { 23559, 5 }, { 23567, 3 }, { 23574, 68 }, { 23584, 3 }, { 23615, 3 }, { 23633, 68 },
{ 23674, 68 }, { 23678, 1 }, { 23853, 68 }, { 23875, 68 }, { 24010, 4 }, { 24076, 68 }, { 24128, 6 }, { 24248, 68 }, { 24253, 68 }, { 24259, 1 }, { 24319, 68 }, { 24319, 1 }, { 24502, 3 }, { 24666, 68 }, { 24781, 3 }, { 24792, 68 }, { 24909, 68 }, { 24993, 68 }, { 25039, 1 }, { 25090, 3 }, { 25137, 1 }, { 25138, 3 }, { 25140, 3 },
{ 25155, 5 }, { 25411, 68 }, { 25460, 68 }, { 25564, 3 }, { 25586, 3 }, { 25630, 68 }, { 25765, 68 }, { 25789, 3 }, { 25803, 68 }, { 25851, 68 }, { 25872, 68 }, { 25887, 68 }, { 25981, 1 }, { 26016, 68 }, { 26019, 1 }, { 26029, 1 }, { 26104, 7 }, { 26144, 68 }, { 26275, 1 }, { 26295, 68 }, { 26298, 1 }, { 26322, 68 },
{ 26380, 68 }, { 26408, 4 }, { 26446, 1 }, { 26553, 1 }, { 26576, 1 }, { 26635, 1 }, { 26668, 68 }, { 26675, 68 }, { 26698, 4 }, { 26748, 9 }, { 26788, 68 }, { 26932, 68 }, { 26962, 68 }, { 27042, 68 }, { 27060, 68 }, { 27163, 3 }, { 27202, 68 }, { 27290, 68 }, { 27337, 3 }, { 27376, 68 }, { 27439, 68 }, { 27458, 4 },
{ 27515, 68 }, { 27518, 1 }, { 27541, 68 }, { 27585, 3 }, { 27633, 68 }, { 27695, 68 }, { 27702, 68 }, { 27861, 68 }, { 27924, 1 }, { 28025, 14 }, { 28058, 68 }, { 28143, 68 }, { 28215, 68 }, { 28240, 68 }, { 28241, 68 }, { 28285, 68 }, { 28324, 3 }, { 28378, 68 }, { 28514, 68 }, { 28529, 68 }, { 28538, 68 }, { 28565, 3 },
{ 28697, 68 }, { 28735, 68 }, { 28769, 68 }, { 28770, 4 }, { 28788, 4 }, { 28807, 3 }, { 28807, 4 }, { 28829, 1 }, { 28853, 68 }, { 28856, 7 }, { 28864, 68 }, { 28865, 3 }, { 28915, 68 }, { 28928, 68 }, { 28964, 68 }, { 28988, 1 }, { 29031, 68 }, { 29095, 68 }, { 29189, 68 }, { 29205, 1 }, { 29230, 1 }, { 29332, 68 },
{ 29339, 68 }, { 29349, 5 }, { 29449, 68 }, { 29471, 68 }, { 29578, 68 }, { 29859, 68 }, { 29878, 68 }, { 29947, 10 }, { 30083, 68 }, { 30121, 68 }, { 30128, 68 }, { 30155, 4 }, { 30157, 1 }, { 30272, 68 }, { 30281, 68 }, { 30286, 68 }, { 30305, 68 }, { 30408, 68 }, { 30444, 268 }, { 30612, 68 }, { 30628, 68 }, { 30747, 68 },
{ 30783, 68 }, { 30808, 5 }, { 30868, 3 }, { 30875, 68 }, { 30997, 68 }, { 31000, 68 }, { 31022, 3 }, { 31111, 1 }, { 31144, 68 }, { 31146, 3 }, { 31187, 68 }, { 31324, 68 }, { 31343, 68 }, { 31416, 68 }, { 31485, 68 }, { 31539, 68 }, { 31638, 68 }, { 31648, 68 }, { 31750, 68 }, { 31754, 68 }, { 31785, 10 }, { 31786, 5 },
{ 31800, 68 }, { 31801, 4 }, { 31807, 7 }, { 31807, 3 }, { 31807, 10 }, { 31808, 3 }, { 31808, 4 }, { 31818, 6 }, { 31825, 7 }, { 31838, 68 }, { 31911, 1 }, { 31974, 68 }, { 32010, 3 }, { 32031, 68 }, { 32040, 68 }, { 32063, 1 }, { 32078, 68 }, { 32156, 68 }, { 32198, 31 }, { 32257, 68 }, { 32257, 68 }, { 32265, 68 },
{ 32330, 68 }, { 32369, 8 }, { 32404, 3 }, { 32425, 68 }, { 32432, 68 }, { 32505, 68 }, { 32531, 68 }, { 32536, 68 }, { 32549, 68 }, { 32582, 3 }, { 32590, 4 }, { 32624, 68 }, { 32644, 68 }, { 32692, 68 }, { 32695, 4 }, { 32699, 3 }, { 32726, 4 }, { 32784, 68 }, { 32832, 68 }, { 32883, 6 }, { 32965, 4 }, { 33044, 68 },
{ 33104, 68 }, { 33184, 68 }, { 33264, 1 }, { 33292, 68 }, { 33312, 1 }, { 33468, 68 }, { 33471, 1 }, { 33565, 68 }, { 33627, 68 }, { 33659, 68 }, { 33709, 68 }, { 33766, 5 }, { 33836, 68 }, { 33875, 68 }, { 33954, 68 }, { 33959, 68 }, { 34050, 68 }, { 34090, 68 }, { 34168, 68 }, { 34233, 68 }, { 34461, 68 }, { 34462, 1 },
{ 34463, 68 }, { 34472, 4 }, { 34500, 68 }, { 34520, 68 }, { 34544, 68 }, { 34614, 68 }, { 34662, 1 }, { 34676, 68 }, { 34729, 4 }, { 34803, 68 }, { 34845, 68 }, { 34913, 68 }, { 34963, 6 }, { 35019, 68 }, { 35022, 68 }, { 35070, 68 }, { 35120, 68 }, { 35132, 68 }, { 35144, 68 }, { 35205, 68 }, { 35230, 3 }, { 35244, 68 },
{ 35271, 4 }, { 35276, 68 }, { 35282, 68 }, { 35324, 3 }, { 35366, 3 }, { 35659, 68 }, { 35680, 68 }, { 35744, 68 }, { 35758, 3 }, { 35796, 68 }, { 35830, 68 }, { 35841, 7 }, { 35843, 68 }, { 35856, 68 }, { 35914, 4 }, { 35929, 13 }, { 35993, 68 }, { 35997, 1 }, { 36046, 4 }, { 36046, 1 }, { 36051, 1 }, { 36111, 68 }, { 36208, 1 },
{ 36208, 1 }, { 36306, 68 }, { 36325, 68 }, { 36386, 68 }, { 36405, 68 }, { 36443, 1 }, { 36455, 1 }, { 36538, 68 }, { 36562, 68 }, { 36566, 68 }, { 36628, 68 }, { 36693, 68 }, { 36713, 68 }, { 36730, 68 }, { 36747, 68 }, { 36786, 68 }, { 36810, 1 }, { 36848, 68 }, { 36914, 1 }, { 36920, 68 }, { 36952, 68 }, { 37071, 68 },
{ 37086, 1 }, { 37094, 3 }, { 37158, 3 }, { 37231, 68 }, { 37241, 68 }, { 37285, 68 }, { 37349, 68 }, { 37404, 68 }, { 37410, 1 }, { 37433, 4 }, { 37615, 68 }, { 37659, 68 }, { 37742, 68 }, { 37773, 68 }, { 37867, 1 }, { 37890, 68 }, { 37960, 68 }, { 38042, 3 }, { 38241, 68 }, { 38400, 68 }, { 38461, 1 }, { 38551, 68 },
{ 38611, 1 }, { 38657, 68 }, { 38729, 68 }, { 38748, 68 }, { 38815, 68 }, { 38852, 68 }, { 38890, 1 }, { 38954, 68 }, { 39119, 68 }, { 39162, 68 }, { 39175, 3 }, { 39176, 68 }, { 39231, 68 }, { 39261, 68 }, { 39467, 68 }, { 39500, 68 }, { 39507, 68 }, { 39566, 68 }, { 39608, 68 }, { 39686, 6 }, { 39730, 68 }, { 39842, 1 },
{ 39853, 1 }, { 39905, 68 }, { 39931, 68 }, { 39989, 68 }, { 40030, 68 }, { 40227, 68 }, { 40268, 68 }, { 40372, 68 }, { 40415, 1 }, { 40488, 3 }, { 40536, 68 }, { 40676, 3 }, { 40677, 68 }, { 40755, 68 }, { 40842, 68 }, { 40849, 1 }, { 40870, 3 }, { 40873, 3 }, { 40972, 68 }, { 41033, 68 }, { 41190, 68 }, { 41273, 5 },
{ 41273, 1 }, { 41293, 68 }, { 41367, 368 }, { 41376, 68 }, { 41420, 68 }, { 41473, 68 }, { 41473, 68 }, { 41493, 4 }, { 41521, 68 }, { 41533, 68 }, { 41554, 68 }, { 41568, 68 }, { 41583, 3 }, { 41728, 68 }, { 41786, 68 }, { 41836, 1 }, { 41875, 68 }, { 41933, 68 }, { 42044, 68 }, { 42075, 68 }, { 42076, 68 }, { 42133, 68 },
{ 42259, 29 }, { 42269, 3 }, { 42294, 68 }, { 42420, 68 }, { 42524, 68 }, { 42524, 1 }, { 42546, 1 }, { 42631, 68 }, { 42693, 68 }, { 42740, 68 }, { 42744, 4 }, { 42755, 1 }, { 42870, 68 }, { 42894, 68 }, { 42939, 68 }, { 42973, 68 }, { 43016, 68 }, { 43070, 68 }, { 43105, 68 }, { 43115, 68 }, { 43375, 3 }, { 43387, 1 },
{ 43424, 3 }, { 43448, 68 }, { 43480, 68 }, { 43498, 68 }, { 43651, 68 }, { 43727, 68 }, { 43879, 68 }, { 43910, 1 }, { 43977, 68 }, { 44003, 68 }, { 44080, 68 }, { 44082, 1 }, { 44136, 68 }, { 44169, 29 }, { 44186, 68 }, { 44339, 68 }, { 44350, 1 }, { 44356, 1 }, { 44430, 68 }, { 44440, 1 }, { 44530, 1 }, { 44538, 68 },
{ 44572, 68 }, { 44585, 68 }, { 44709, 68 }, { 44748, 68 }, { 44748, 68 }, { 44769, 68 }, { 44813, 68 }, { 44890, 68 }, { 45015, 68 }, { 45046, 4 }, { 45052, 68 }, { 45062, 68 }, { 45094, 6 }, { 45184, 68 }, { 45191, 68 }, { 45201, 3 }, { 45216, 3 }, { 45227, 68 }, { 45269, 1 }, { 45294, 68 }, { 45314, 68 }, { 45345, 8 },
{ 45352, 68 }, { 45365, 3 }, { 45378, 1 }, { 45392, 4 }, { 45405, 3 }, { 45410, 68 }, { 45448, 14 }, { 45450, 68 }, { 45457, 68 }, { 45466, 3 }, { 45481, 4 }, { 45486, 7 }, { 45533, 5 }, { 45576, 68 }, { 45649, 68 }, { 45917, 68 }, { 45919, 6 }, { 45919, 1 }, { 45930, 15 }, { 45930, 68 }, { 46001, 5 }, { 46036, 68 }, { 46054, 68 },
{ 46075, 68 }, { 46153, 68 }, { 46155, 68 }, { 46228, 68 }, { 46234, 68 }, { 46273, 68 }, { 46387, 68 }, { 46398, 68 }, { 46517, 68 }, { 46559, 68 }, { 46565, 1 }, { 46598, 68 }, { 46686, 68 }, { 46744, 68 }, { 46816, 3 }, { 46835, 68 }, { 46921, 68 }, { 46938, 68 }, { 46991, 68 }, { 47038, 68 }, { 47098, 3 }, { 47107, 68 },
{ 47201, 3 }, { 47327, 1 }, { 47327, 1 }, { 47338, 68 }, { 47395, 1 }, { 47499, 68 }, { 47504, 68 }, { 47515, 1 }, { 47516, 1 }, { 47600, 1 }, { 47604, 1 }, { 47707, 1 }, { 47728, 1 }, { 47748, 68 }, { 47763, 68 }, { 47807, 4 }, { 47814, 68 }, { 47822, 68 }, { 47834, 68 }, { 47843, 3 }, { 47886, 68 }, { 47893, 68 }, { 48066, 68 },
{ 48126, 68 }, { 48133, 1 }, { 48166, 68 }, { 48299, 1 }, { 48455, 68 }, { 48468, 68 }, { 48568, 68 }, { 48606, 68 }, { 48642, 68 }, { 48698, 68 }, { 48714, 68 }, { 48754, 68 }, { 48765, 3 }, { 48773, 5 }, { 48819, 68 }, { 48833, 68 }, { 48904, 68 }, { 49000, 1 }, { 49113, 168 }, { 49140, 68 }, { 49276, 68 }, { 49353, 68 },
{ 49411, 3 }, { 49418, 68 }, { 49540, 68 }, { 49544, 68 }, { 49584, 68 }, { 49602, 68 }, { 49784, 5 }, { 49822, 4 }, { 49822, 5 }, { 49828, 68 }, { 49866, 68 }, { 49922, 3 }, { 49959, 68 }, { 50045, 68 }, { 50134, 3 }, { 50140, 68 }, { 50237, 68 }, { 50247, 68 }, { 50266, 13 }, { 50290, 68 }, { 50312, 4 }, { 50314, 1 },
{ 50527, 68 }, { 50605, 1 }, { 50730, 68 }, { 50751, 68 }, { 50770, 68 }, { 50858, 68 }, { 50859, 68 }, { 50909, 68 }, { 50948, 3 }, { 51043, 68 }, { 51048, 68 }, { 51089, 68 }, { 51090, 68 }, { 51141, 68 }, { 51163, 68 }, { 51250, 68 }, { 51347, 68 }, { 51475, 68 }, { 51536, 68 }, { 51544, 68 }, { 51595, 68 }, { 51602, 19 },
{ 51643, 5 }, { 51702, 68 }, { 51702, 10 }, { 51764, 68 }, { 51793, 5 }, { 51812, 68 }, { 51839, 1 }, { 51938, 3 }, { 51941, 1 }, { 51967, 4 }, { 52049, 3 }, { 52074, 3 }, { 52098, 68 }, { 52118, 68 }, { 52119, 3 }, { 52227, 11 }, { 52246, 3 }, { 52282, 68 }, { 52451, 68 }, { 52583, 68 }, { 52601, 1 }, { 52605, 68 }, { 52615, 68 },
{ 52668, 68 }, { 52824, 68 }, { 53076, 1 }, { 53120, 1 }, { 53179, 68 }, { 53189, 68 }, { 53193, 1 }, { 53195, 68 }, { 53246, 68 }, { 53249, 68 }, { 53268, 1 }, { 53295, 68 }, { 53312, 68 }, { 53410, 68 }, { 53451, 68 }, { 53570, 68 }, { 53593, 68 }, { 53635, 68 }, { 53657, 68 }, { 53682, 3 }, { 53728, 5 }, { 53733, 68 },
{ 53753, 68 }, { 53787, 4 }, { 53807, 1 }, { 54008, 68 }, { 54059, 68 }, { 54060, 1 }, { 54080, 68 }, { 54090, 1 }, { 54138, 68 }, { 54149, 68 }, { 54168, 1 }, { 54171, 68 }, { 54216, 268 }, { 54233, 6 }, { 54434, 68 }, { 54534, 68 }, { 54562, 68 }, { 54763, 68 }, { 54791, 68 }, { 54816, 68 }, { 54909, 68 }, { 54916, 3 },
{ 54963, 68 }, { 54985, 68 }, { 54991, 3 }, { 55016, 3 }, { 55025, 3 }, { 55032, 68 }, { 55099, 68 }, { 55260, 68 }, { 55261, 68 }, { 55270, 3 }, { 55384, 68 }, { 55455, 68 }, { 55456, 68 }, { 55504, 3 }, { 55510, 68 }, { 55558, 68 }, { 55568, 68 }, { 55585, 68 }, { 55677, 68 }, { 55703, 68 }, { 55749, 68 }, { 55779, 68 },
{ 55789, 3 }, { 55792, 68 }, { 55830, 4 }, { 55835, 68 }, { 55879, 68 }, { 56076, 68 }, { 56118, 68 }, { 56314, 68 }, { 56392, 1 }, { 56411, 68 }, { 56459, 68 }, { 56553, 34 }, { 56575, 68 }, { 56733, 68 }, { 56762, 68 }, { 56793, 3 }, { 56877, 3 }, { 56927, 68 }, { 56981, 68 }, { 57014, 1 }, { 57149, 68 }, { 57162, 68 },
{ 57186, 68 }, { 57254, 68 }, { 57267, 1 }, { 57324, 68 }, { 57327, 68 }, { 57365, 4 }, { 57371, 68 }, { 57445, 68 }, { 57477, 68 }, { 57497, 68 }, { 57536, 68 }, { 57609, 68 }, { 57626, 68 }, { 57666, 68 }, { 57694, 68 }, { 57694, 68 }, { 57749, 68 }, { 57781, 7 }, { 57878, 68 }, { 57953, 68 }, { 58051, 68 }, { 58088, 68 },
{ 58097, 68 }, { 58142, 3 }, { 58142, 1 }, { 58197, 1 }, { 58221, 68 }, { 58222, 68 }, { 58244, 68 }, { 58290, 1 }, { 58296, 1 }, { 58325, 68 }, { 58378, 1 }, { 58389, 3 }, { 58430, 68 }, { 58454, 68 }, { 58551, 29 }, { 58563, 6 }, { 58681, 68 }, { 58751, 8 }, { 58752, 43 }, { 58790, 5 }, { 58846, 68 }, { 58879, 6 }, { 58953, 68 },
{ 58998, 68 }, { 59010, 1 }, { 59038, 5 }, { 59135, 68 }, { 59166, 68 }, { 59180, 68 }, { 59222, 68 }, { 59227, 68 }, { 59307, 68 }, { 59398, 3 }, { 59411, 68 }, { 59436, 3 }, { 59464, 68 }, { 59569, 68 }, { 59587, 68 }, { 59624, 3 }, { 59786, 68 }, { 59834, 68 }, { 59841, 68 }, { 59841, 1 }, { 59984, 68 }, { 59985, 68 },
{ 60003, 3 }, { 60045, 68 }, { 60097, 68 }, { 60148, 68 }, { 60172, 68 }, { 60203, 5 }, { 60565, 68 }, { 60625, 68 }, { 60743, 68 }, { 60781, 68 }, { 60892, 68 }, { 60977, 68 }, { 60979, 68 }, { 61021, 5 }, { 61021, 4 }, { 61026, 68 }, { 61139, 68 }, { 61165, 3 }, { 61204, 68 }, { 61207, 1 }, { 61248, 3 }, { 61257, 68 },
{ 61264, 6 }, { 61272, 3 }, { 61410, 68 }, { 61410, 3 }, { 61416, 68 }, { 61423, 1 }, { 61503, 68 }, { 61503, 68 }, { 61533, 68 }, { 61567, 68 }, { 61575, 68 }, { 61835, 1 }, { 61842, 1 }, { 61924, 68 }, { 61951, 6 }, { 61975, 68 }, { 61986, 3 }, { 62024, 1 }, { 62110, 68 }, { 62135, 68 }, { 62192, 68 }, { 62208, 68 },
{ 62399, 68 }, { 62400, 1 }, { 62414, 68 }, { 62423, 3 }, { 62456, 3 }, { 62459, 3 }, { 62478, 3 }, { 62484, 68 }, { 62510, 6 }, { 62511, 3 }, { 62565, 3 }, { 62610, 68 }, { 62875, 4 }, { 62896, 5 }, { 62898, 68 }, { 62904, 68 }, { 62938, 3 }, { 62943, 68 }, { 62977, 68 }, { 62989, 3 }, { 62998, 5 }, { 63069, 1 }, { 63093, 5 },
{ 63107, 68 }, { 63113, 1 }, { 63231, 4 }, { 63253, 68 }, { 63286, 4 }, { 63289, 68 }, { 63334, 1 }, { 63334, 4 }, { 63413, 68 }, { 63425, 68 }, { 63512, 10 }, { 63537, 1 }, { 63694, 1 }, { 63721, 4 }, { 63749, 68 }, { 63783, 17 }, { 63791, 3 }, { 63792, 68 }, { 63882, 25 }, { 63896, 1 }, { 63936, 68 }, { 63969, 3 }, { 63986, 68 },
{ 63988, 68 }, { 64009, 10 }, { 64018, 68 }, { 64032, 6 }, { 64125, 68 }, { 64195, 1 }, { 64221, 7 }, { 64390, 68 }, { 64459, 68 }, { 64568, 68 }, { 64784, 1 }, { 64789, 68 }, { 64829, 68 }, { 64848, 1 }, { 64914, 68 }, { 64928, 1 }, { 64939, 68 }, { 65026, 68 }, { 65057, 68 }, { 65070, 68 }, { 65193, 4 }, { 65235, 3 },
{ 65242, 68 }, { 65281, 68 }, { 65320, 68 }, { 65365, 1 }, { 65414, 68 }, { 65445, 68 }, { 65581, 68 }, { 65624, 1 }, { 65719, 68 }, { 65766, 68 }, { 65927, 68 }, { 66004, 1 }, { 66031, 68 }, { 66085, 1 }, { 66085, 68 }, { 66133, 68 }, { 66134, 68 }, { 66188, 1 }, { 66240, 68 }, { 66249, 68 }, { 66250, 68 }, { 66295, 68 },
{ 66342, 1 }, { 66352, 3 }, { 66388, 3 }, { 66432, 68 }, { 66437, 47 }, { 66497, 68 }, { 66517, 68 }, { 66526, 68 }, { 66546, 9 }, { 66605, 68 }, { 66753, 68 }, { 66792, 68 }, { 66796, 68 }, { 66828, 68 }, { 66899, 3 }, { 66970, 6 }, { 66981, 68 }, { 66983, 1 }, { 67009, 68 }, { 67017, 4 }, { 67115, 68 }, { 67117, 1 },
{ 67130, 6 }, { 67132, 7 }, { 67162, 68 }, { 67179, 6 }, { 67236, 68 }, { 67263, 3 }, { 67274, 68 }, { 67274, 68 }, { 67349, 3 }, { 67486, 68 }, { 67503, 3 }, { 67517, 1 }, { 67559, 1 }, { 67660, 68 }, { 67727, 68 }, { 67901, 68 }, { 67943, 4 }, { 67950, 68 }, { 67965, 3 }, { 68029, 68 }, { 68048, 68 }, { 68169, 68 }, { 68172, 1 },
{ 68258, 68 }, { 68288, 1 }, { 68359, 68 }, { 68441, 68 }, { 68484, 68 }, { 68488, 68 }, { 68525, 68 }, { 68535, 68 }, { 68575, 7 }, { 68575, 5 }, { 68583, 68 }, { 68588, 4 }, { 68593, 1 }, { 68597, 68 }, { 68636, 68 }, { 68636, 68 }, { 68667, 68 }, { 68785, 1 }, { 68914, 4 }, { 68915, 5 }, { 68940, 3 }, { 69010, 68 },
{ 69063, 68 }, { 69076, 68 }, { 69235, 68 }, { 69270, 68 }, { 69298, 1 }, { 69350, 5 }, { 69432, 68 }, { 69514, 68 }, { 69562, 3 }, { 69562, 4 }, { 69638, 1 }, { 69656, 68 }, { 69709, 68 }, { 69775, 68 }, { 69788, 68 }, { 70193, 68 }, { 70233, 68 }, { 70252, 68 }, { 70259, 68 }, { 70293, 3 }, { 70405, 3 }, { 70462, 68 },
{ 70515, 3 }, { 70518, 68 }, { 70535, 6 }, { 70547, 6 }, { 70577, 6 }, { 70631, 17 }, { 70667, 68 }, { 70680, 1 }, { 70694, 1 }, { 70898, 68 }, { 70916, 1 }, { 70936, 3 }, { 71033, 68 }, { 71126, 68 }, { 71158, 68 }, { 71162, 68 }, { 71421, 1 }, { 71441, 68 }, { 71557, 68 }, { 71789, 1 }, { 71816, 68 }, { 71850, 1 }, { 71869, 1 },
{ 71961, 68 }, { 71973, 4 }, { 72064, 68 }, { 72110, 68 }, { 72117, 3 }, { 72164, 68 }, { 72266, 68 }, { 72325, 68 }, { 72326, 1 }, { 72420, 68 }, { 72693, 68 }, { 72705, 1 }, { 72730, 68 }, { 72793, 68 }, { 72795, 1 }, { 72939, 1 }, { 72945, 3 }, { 72945, 68 }, { 73120, 1 }, { 73121, 5 }, { 73122, 4 }, { 73126, 1 }, { 73126, 1 },
{ 73196, 3 }, { 73219, 68 }, { 73241, 6 }, { 73272, 3 }, { 73354, 1 }, { 73368, 68 }, { 73467, 1 }, { 73517, 68 }, { 73554, 68 }, { 73678, 68 }, { 73838, 1 }, { 73881, 68 }, { 73958, 68 }, { 73985, 15 }, { 74092, 68 }, { 74205, 68 }, { 74245, 68 }, { 74277, 68 }, { 74286, 68 }, { 74353, 68 }, { 74403, 68 }, { 74428, 1 },
{ 74468, 68 }, { 74481, 3 }, { 74511, 68 }, { 74537, 68 }, { 74596, 68 }, { 74750, 68 }, { 74754, 68 }, { 74861, 68 }, { 74933, 4 }, { 74970, 1 }, { 75003, 3 }, { 75077, 1 }, { 75159, 68 }, { 75170, 68 }, { 75234, 45 }, { 75300, 3 }, { 75337, 68 }, { 75345, 68 }, { 75419, 1 }, { 75429, 68 }, { 75477, 1 }, { 75513, 68 },
{ 75536, 68 }, { 75536, 68 }, { 75539, 1 }, { 75551, 68 }, { 75561, 68 }, { 75565, 68 }, { 75590, 68 }, { 75623, 5 }, { 75773, 6 }, { 75777, 6 }, { 75785, 68 }, { 75791, 68 }, { 75804, 68 }, { 75862, 68 }, { 75924, 3 }, { 75927, 68 }, { 75996, 11 }, { 76000, 1 }, { 76006, 68 }, { 76020, 3 }, { 76110, 68 }, { 76126, 3 },
{ 76131, 68 }, { 76136, 68 }, { 76144, 68 }, { 76203, 68 }, { 76229, 3 }, { 76244, 15 }, { 76246, 68 }, { 76300, 1 }, { 76403, 3 }, { 76545, 68 }, { 76569, 68 }, { 76813, 68 }, { 76821, 68 }, { 76837, 68 }, { 76863, 68 }, { 77027, 68 }, { 77037, 65 }, { 77074, 3 }, { 77170, 68 }, { 77191, 68 }, { 77220, 68 }, { 77230, 68 },
{ 77261, 68 }, { 77277, 68 }, { 77309, 68 }, { 77314, 68 }, { 77412, 68 }, { 77419, 68 }, { 77457, 68 }, { 77633, 3 }, { 77714, 68 }, { 77855, 68 }, { 77857, 1 }, { 77876, 68 }, { 77895, 68 }, { 77916, 5 }, { 77947, 68 }, { 77948, 1 }, { 77966, 1 }, { 77996, 68 }, { 78025, 1 }, { 78064, 68 }, { 78100, 68 }, { 78113, 1 },
{ 78114, 3 }, { 78167, 68 }, { 78175, 68 }, { 78260, 68 }, { 78261, 1 }, { 78265, 68 }, { 78286, 1 }, { 78300, 68 }, { 78327, 3 }, { 78363, 1 }, { 78384, 68 }, { 78459, 68 }, { 78516, 68 }, { 78612, 68 }, { 78643, 68 }, { 78655, 68 }, { 78698, 1 }, { 78720, 3 }, { 78789, 76 }, { 78838, 5 }, { 78893, 1 }, { 78954, 7 },
{ 79007, 68 }, { 79132, 3 }, { 79193, 68 }, { 79193, 68 }, { 79226, 68 }, { 79411, 68 }, { 79422, 1 }, { 79502, 68 }, { 79593, 68 }, { 79622, 68 }, { 79657, 3 }, { 79771, 68 }, { 79866, 68 }, { 79909, 68 }, { 80005, 68 }, { 80032, 68 }, { 80060, 1 }, { 80132, 68 }, { 80149, 3 }, { 80251, 68 }, { 80363, 68 }, { 80379, 1 },
{ 80464, 68 }, { 80498, 68 }, { 80553, 68 }, { 80556, 3 }, { 80559, 1 }, { 80571, 68 }, { 80652, 1 }, { 80703, 68 }, { 80754, 68 }, { 80754, 68 }, { 80860, 68 }, { 81055, 68 }, { 81087, 4 }, { 81210, 68 }, { 81211, 1 }, { 81216, 1 }, { 81223, 1 }, { 81231, 1 }, { 81288, 68 }, { 81317, 68 }, { 81327, 65 }, { 81332, 68 },
{ 81376, 68 }, { 81469, 68 }, { 81579, 68 }, { 81617, 1 }, { 81630, 68 }, { 81666, 68 }, { 81800, 68 }, { 81832, 68 }, { 81848, 68 }, { 81869, 68 }, { 81941, 3 }, { 82177, 3 }, { 82179, 68 }, { 82180, 68 }, { 82182, 4 }, { 82185, 68 }, { 82195, 68 }, { 82238, 4 }, { 82265, 3 }, { 82295, 10 }, { 82299, 9 }, { 82367, 3 },
{ 82379, 3 }, { 82380, 1 }, { 82505, 68 }, { 82568, 68 }, { 82620, 1 }, { 82637, 5 }, { 82821, 68 }, { 82841, 68 }, { 82945, 1 }, { 83020, 168 }, { 83072, 68 }, { 83181, 68 }, { 83240, 68 }, { 83253, 3 }, { 83261, 68 }, { 83288, 68 }, { 83291, 4 }, { 83295, 3 }, { 83365, 68 }, { 83368, 68 }, { 83408, 68 }, { 83458, 68 },
{ 83470, 68 }, { 83471, 1 }, { 83637, 3 }, { 83693, 68 }, { 83703, 68 }, { 83732, 68 }, { 83745, 1 }, { 83800, 4 }, { 83801, 3 }, { 83856, 3 }, { 83863, 5 }, { 83867, 68 }, { 83868, 3 }, { 83898, 7 }, { 83900, 4 }, { 83901, 5 }, { 83989, 68 }, { 84049, 35 }, { 84086, 68 }, { 84089, 68 }, { 84115, 3 }, { 84130, 3 }, { 84132, 68 },
{ 84143, 54 }, { 84173, 68 }, { 84185, 5 }, { 84297, 68 }, { 84390, 68 }, { 84497, 4 }, { 84657, 68 }, { 84657, 68 }, { 84724, 68 }, { 84775, 68 }, { 84870, 68 }, { 84892, 68 }, { 84910, 3 }, { 84935, 3 }, { 85002, 68 }, { 85051, 68 }, { 85052, 68 }, { 85135, 25 }, { 85135, 68 }, { 85144, 68 }, { 85165, 3 }, { 85205, 68 },
{ 85232, 68 }, { 85281, 5 }, { 85423, 6 }, { 85539, 68 }, { 85582, 4 }, { 85609, 68 }, { 85701, 36 }, { 85705, 68 }, { 85824, 68 }, { 85824, 68 }, { 85858, 30 }, { 85858, 28 }, { 85904, 35 }, { 85910, 68 }, { 85913, 68 }, { 85926, 3 }, { 85942, 4 }, { 85969, 4 }, { 85996, 1 }, { 86013, 3 }, { 86034, 13 }, { 86068, 8 },
{ 86069, 8 }, { 86089, 8 }, { 86193, 13 }, { 86217, 7 }, { 86219, 68 }, { 86250, 68 }, { 86304, 16 }, { 86317, 68 }, { 86322, 4 }, { 86325, 68 }, { 86333, 68 }, { 86394, 68 }, { 86433, 68 }, { 86469, 3 }, { 86512, 4 }, { 86537, 68 }, { 86627, 68 }, { 86658, 68 }, { 86810, 68 }, { 86813, 68 }, { 86884, 68 }, { 86947, 68 },
{ 87003, 68 }, { 87010, 5 }, { 87019, 68 }, { 87027, 68 }, { 87105, 68 }, { 87107, 68 }, { 87183, 68 }, { 87273, 68 }, { 87358, 3 }, { 87388, 3 }, { 87503, 4 }, { 87639, 68 }, { 87649, 4 }, { 87722, 68 }, { 87829, 68 }, { 87829, 1 }, { 87863, 68 }, { 87894, 68 }, { 87988, 368 }, { 88035, 27 }, { 88059, 3 }, { 88094, 5 },
{ 88111, 21 }, { 88129, 68 }, { 88175, 5 }, { 88256, 68 }, { 88329, 76 }, { 88415, 3 }, { 88482, 68 }, { 88502, 1 }, { 88529, 68 }, { 88551, 3 }, { 88552, 1 }, { 88713, 68 }, { 88797, 68 }, { 88844, 27 }, { 88925, 5 }, { 88935, 68 }, { 88944, 1 }, { 89073, 68 }, { 89095, 3 }, { 89283, 68 }, { 89294, 3 }, { 89299, 68 },
{ 89324, 68 }, { 89368, 68 }, { 89387, 68 }, { 89464, 68 }, { 89607, 68 }, { 89737, 68 }, { 89791, 68 }, { 89794, 3 }, { 89840, 68 }, { 89849, 3 }, { 89859, 68 }, { 89905, 68 }, { 89952, 38 }, { 90030, 7 }, { 90030, 6 }, { 90031, 1 }, { 90072, 68 }, { 90090, 68 }, { 90146, 3 }, { 90202, 23 }, { 90302, 3 }, { 90328, 14 },
{ 90335, 14 }, { 90338, 8 }, { 90380, 68 }, { 90434, 1 }, { 90482, 68 }, { 90527, 9 }, { 90537, 68 }, { 90545, 68 }, { 90639, 5 }, { 90642, 68 }, { 90709, 68 }, { 90775, 1 }, { 90806, 68 }, { 90845, 19 }, { 90872, 4 }, { 90884, 68 }, { 90910, 68 }, { 90994, 5 }, { 91046, 8 }, { 91059, 8 }, { 91096, 39 }, { 91147, 68 },
{ 91168, 1 }, { 91493, 68 }, { 91513, 3 }, { 91618, 3 }, { 91653, 68 }, { 91817, 68 }, { 91831, 3 }, { 91833, 3 }, { 91885, 68 }, { 91919, 68 }, { 91934, 68 }, { 92245, 1 }, { 92284, 68 }, { 92292, 4 }, { 92369, 3 }, { 92388, 68 }, { 92426, 7 }, { 92720, 14 }, { 92720, 6 }, { 92729, 9 }, { 92733, 13 }, { 92735, 6 }, { 92786, 68 },
{ 92853, 31 }, { 92906, 68 }, { 93031, 7 }, { 93077, 68 }, { 93102, 68 }, { 93109, 68 }, { 93122, 3 }, { 93214, 68 }, { 93330, 68 }, { 93395, 68 }, { 93506, 68 }, { 93564, 9 }, { 93713, 9 }, { 93722, 4 }, { 93840, 68 }, { 93877, 4 }, { 93891, 3 }, { 93948, 68 }, { 93981, 68 }, { 94012, 3 }, { 94033, 68 }, { 94121, 68 },
{ 94165, 368 }, { 94181, 3 }, { 94210, 68 }, { 94216, 68 }, { 94230, 68 }, { 94333, 31 }, { 94433, 3 }, { 94497, 3 }, { 94609, 68 }, { 94623, 68 }, { 94763, 68 }, { 94780, 68 }, { 95287, 68 }, { 95348, 68 }, { 95433, 5 }, { 95446, 68 }, { 95493, 7 }, { 95517, 3 }, { 95580, 68 }, { 95610, 5 }, { 95620, 68 }, { 95678, 3 },
{ 95683, 68 }, { 95689, 68 }, { 95760, 68 }, { 95792, 68 }, { 95850, 68 }, { 95908, 68 }, { 95908, 68 }, { 95967, 68 }, { 96022, 3 }, { 96088, 65 }, { 96460, 68 }, { 96554, 68 }, { 96597, 68 }, { 96763, 68 }, { 96808, 68 }, { 96854, 1 }, { 96963, 1 }, { 97007, 3 }, { 97125, 1 }, { 97128, 68 }, { 97133, 3 }, { 97142, 3 },
{ 97156, 68 }, { 97223, 68 }, { 97244, 68 }, { 97303, 68 }, { 97355, 68 }, { 97356, 3 }, { 97393, 3 }, { 97409, 1 }, { 97451, 68 }, { 97539, 68 }, { 97546, 68 }, { 97553, 68 }, { 97627, 68 }, { 97640, 68 }, { 97650, 6 }, { 97675, 68 }, { 97685, 3 }, { 97773, 68 }, { 97802, 4 }, { 97826, 19 }, { 97860, 68 }, { 97956, 68 },
{ 97958, 68 }, { 97973, 3 }, { 97982, 68 }, { 98039, 68 }, { 98051, 68 }, { 98059, 68 }, { 98088, 68 }, { 98092, 4 }, { 98147, 68 }, { 98147, 68 }, { 98169, 68 }, { 98207, 65 }, { 98277, 1 }, { 98277, 268 }, { 98285, 68 }, { 98324, 3 }, { 98324, 3 }, { 98381, 31 }, { 98390, 68 }, { 98404, 68 }, { 98415, 4 }, { 98460, 68 },
{ 98462, 1 }, { 98475, 3 }, { 98485, 68 }, { 98640, 1 }, { 98798, 68 }, { 98800, 4 }, { 98821, 68 }, { 98895, 68 }, { 98936, 68 }, { 98950, 68 }, { 98980, 68 }, { 99033, 68 }, { 99045, 68 }, { 99135, 68 }, { 99315, 30 }, { 99324, 68 }, { 99346, 68 }, { 99418, 68 }, { 99505, 68 }, { 99557, 68 }, { 99559, 68 }, { 99586, 68 },
{ 99622, 68 }, { 99770, 1 }, { 99790, 68 }, { 99810, 68 }, { 99871, 1 }, { 99926, 68 }, { 99927, 68 }, { 99978, 68 }, { 99980, 68 }, { 100022, 3 }, { 100024, 1 }, { 100069, 68 }, { 100150, 68 }, { 100225, 63 }, { 100246, 1 }, { 100310, 68 }, { 100361, 68 }, { 100428, 1 }, { 100434, 68 }, { 100450, 4 }, { 100546, 68 },
{ 100551, 68 }, { 100551, 68 }, { 100554, 1 }, { 100597, 68 }, { 100676, 68 }, { 100693, 68 }, { 100827, 68 }, { 100928, 68 }, { 100928, 1 }, { 100935, 68 }, { 100937, 3 }, { 101034, 68 }, { 101041, 68 }, { 101154, 68 }, { 101200, 4 }, { 101250, 68 }, { 101352, 68 }, { 101403, 68 }, { 101430, 1 }, { 101508, 3 }, { 101509, 3 },
{ 101523, 10 }, { 101604, 68 }, { 101637, 68 }, { 101681, 4 }, { 101759, 1 }, { 101773, 1 }, { 101836, 1 }, { 101882, 4 }, { 101895, 68 }, { 101897, 68 }, { 101939, 68 }, { 101951, 6 }, { 101956, 5 }, { 102055, 1 }, { 102085, 68 }, { 102093, 67 }, { 102209, 68 }, { 102258, 6 }, { 102271, 68 }, { 102284, 68 }, { 102332, 68 },
{ 102354, 68 }, { 102366, 68 }, { 102424, 3 }, { 102456, 68 }, { 102496, 1 }, { 102497, 3 }, { 102519, 3 }, { 102554, 1 }, { 102610, 5 }, { 102657, 68 }, { 102661, 4 }, { 102695, 4 }, { 102707, 168 }, { 102910, 68 }, { 102930, 5 }, { 102937, 9 }, { 102938, 7 }, { 102965, 6 }, { 102969, 7 }, { 103031, 68 }, { 103062, 68 },
{ 103096, 68 }, { 103146, 68 }, { 103159, 68 }, { 103223, 68 }, { 103267, 68 }, { 103296, 68 }, { 103303, 68 }, { 103487, 68 }, { 103491, 68 }, { 103599, 68 }, { 103677, 68 }, { 103903, 1 }, { 104040, 68 }, { 104047, 1 }, { 104052, 68 }, { 104057, 4 }, { 104057, 68 }, { 104062, 98 }, { 104091, 68 }, { 104189, 3 }, { 104283, 8 },
{ 104288, 4 }, { 104305, 3 }, { 104445, 68 }, { 104472, 68 }, { 104475, 1 }, { 104497, 4 }, { 104548, 68 }, { 104582, 68 }, { 104626, 1 }, { 104716, 68 }, { 104826, 68 }, { 104849, 68 }, { 104872, 1 }, { 104945, 1 }, { 104948, 68 }, { 105066, 68 }, { 105071, 1 }, { 105198, 4 }, { 105198, 4 }, { 105203, 68 }, { 105256, 6 },
{ 105263, 68 }, { 105329, 68 }, { 105515, 68 }, { 105566, 68 }, { 105566, 68 }, { 105585, 68 }, { 105678, 68 }, { 105852, 68 }, { 105877, 68 }, { 105911, 68 }, { 106022, 1 }, { 106033, 68 }, { 106080, 68 }, { 106192, 68 }, { 106220, 3 }, { 106243, 68 }, { 106323, 11 }, { 106371, 68 }, { 106608, 68 }, { 106624, 87 }, { 106680, 3 },
{ 106688, 1 }, { 106800, 1 }, { 106800, 1 }, { 106821, 4 }, { 106853, 1 }, { 106930, 3 }, { 106937, 68 }, { 106955, 68 }, { 106996, 68 }, { 106996, 1 }, { 107148, 4 }, { 107213, 16 }, { 107213, 68 }, { 107243, 68 }, { 107360, 68 }, { 107408, 68 }, { 107509, 4 }, { 107572, 68 }, { 107592, 68 }, { 107644, 5 }, { 107679, 68 },
{ 107705, 3 }, { 107761, 4 }, { 107780, 68 }, { 107825, 68 }, { 108007, 68 }, { 108041, 4 }, { 108058, 68 }, { 108071, 1 }, { 108132, 68 }, { 108164, 68 }, { 108189, 68 }, { 108210, 68 }, { 108330, 68 }, { 108430, 68 }, { 108450, 68 }, { 108469, 68 }, { 108484, 68 }, { 108533, 68 }, { 108588, 68 }, { 108594, 68 }, { 108690, 68 },
{ 108785, 76 }, { 108814, 68 }, { 108818, 1 }, { 108820, 68 }, { 108889, 68 }, { 108951, 68 }, { 108959, 68 }, { 108963, 68 }, { 109034, 68 }, { 109172, 1 }, { 109176, 68 }, { 109195, 3 }, { 109229, 68 }, { 109256, 68 }, { 109290, 68 }, { 109304, 68 }, { 109333, 68 }, { 109343, 4 }, { 109347, 7 }, { 109387, 68 }, { 109421, 1 },
{ 109497, 68 }, { 109501, 3 }, { 109513, 68 }, { 109525, 3 }, { 109625, 4 }, { 109710, 68 }, { 109740, 68 }, { 109751, 68 }, { 109761, 68 }, { 109890, 8 }, { 109891, 4 }, { 109909, 68 }, { 109923, 1 }, { 110017, 68 }, { 110046, 68 }, { 110111, 68 }, { 110258, 68 }, { 110340, 68 }, { 110352, 68 }, { 110398, 68 }, { 110583, 68 },
{ 110600, 13 }, { 110626, 3 }, { 110709, 68 }, { 110772, 4 }, { 110773, 68 }, { 110813, 1 }, { 110890, 68 }, { 110898, 68 }, { 110954, 68 }, { 111120, 68 }, { 111132, 3 }, { 111163, 8 }, { 111224, 68 }, { 111340, 68 }, { 111398, 68 }, { 111555, 68 }, { 111597, 3 }, { 111607, 68 }, { 111655, 68 }, { 111691, 3 }, { 111835, 68 },
{ 111854, 68 }, { 111876, 16 }, { 111884, 1 }, { 111884, 56 }, { 111929, 68 }, { 111941, 68 }, { 111969, 68 }, { 112003, 68 }, { 112165, 68 }, { 112365, 68 }, { 112450, 1 }, { 112521, 68 }, { 112649, 4 }, { 112665, 68 }, { 112881, 1 }, { 112882, 68 }, { 112906, 68 }, { 112951, 68 }, { 112994, 68 }, { 112997, 68 }, { 113002, 68 },
{ 113056, 1 }, { 113077, 68 }, { 113208, 1 }, { 113320, 68 }, { 113326, 3 }, { 113375, 68 }, { 113530, 30 }, { 113530, 30 }, { 113537, 1 }, { 113563, 14 }, { 113592, 68 }, { 113637, 68 }, { 113768, 68 }, { 113850, 5 }, { 113892, 68 }, { 113916, 68 }, { 113965, 68 }, { 113976, 68 }, { 114037, 68 }, { 114149, 1 }, { 114158, 9 },
{ 114201, 68 }, { 114262, 68 }, { 114268, 4 }, { 114353, 68 }, { 114388, 68 }, { 114404, 68 }, { 114428, 5 }, { 114438, 68 }, { 114541, 68 }, { 114550, 68 }, { 114561, 68 }, { 114625, 3 }, { 114730, 68 }, { 114770, 1 }, { 114815, 4 }, { 114998, 68 }, { 115077, 68 }, { 115093, 68 }, { 115120, 68 }, { 115194, 68 }, { 115216, 3 },
{ 115299, 68 }, { 115391, 3 }, { 115410, 68 }, { 115542, 33 }, { 115581, 68 }, { 115618, 68 }, { 115645, 23 }, { 115647, 68 }, { 115697, 68 }, { 115725, 68 }, { 115740, 68 }, { 115757, 68 }, { 115763, 68 }, { 115770, 68 }, { 115787, 68 }, { 115916, 68 }, { 115928, 68 }, { 115962, 68 }, { 116020, 68 }, { 116022, 1 }, { 116089, 68 },
{ 116159, 1 }, { 116196, 68 }, { 116247, 68 }, { 116254, 7 }, { 116336, 68 }, { 116409, 68 }, { 116459, 68 }, { 116569, 68 }, { 116619, 68 }, { 116688, 68 }, { 116733, 68 }, { 116807, 3 }, { 116843, 68 }, { 116886, 1 }, { 116902, 68 }, { 116931, 68 }, { 116952, 68 }, { 116952, 68 }, { 117177, 68 }, { 117189, 68 }, { 117206, 68 },
{ 117260, 29 }, { 117271, 6 }, { 117276, 3 }, { 117276, 5 }, { 117278, 3 }, { 117278, 68 }, { 117359, 4 }, { 117380, 68 }, { 117414, 1 }, { 117503, 68 }, { 117517, 68 }, { 117530, 68 }, { 117574, 4 }, { 117575, 5 }, { 117577, 68 }, { 117606, 68 }, { 117645, 68 }, { 117655, 68 }, { 117692, 68 }, { 117705, 1 }, { 117731, 1 },
{ 117762, 4 }, { 117780, 68 }, { 117974, 1 }, { 118057, 1 }, { 118099, 68 }, { 118107, 68 }, { 118113, 68 }, { 118175, 68 }, { 118198, 68 }, { 118232, 45 }, { 118326, 1 }, { 118438, 31 }, { 118469, 68 }, { 118521, 31 }, { 118565, 68 }, { 118593, 68 }, { 118602, 68 }, { 118652, 68 }, { 118668, 68 }, { 118689, 3 }, { 118703, 14 },
{ 118705, 68 }, { 118813, 68 }, { 118825, 68 }, { 118894, 3 }, { 118915, 68 }, { 118962, 68 }, { 118986, 68 }, { 119045, 68 }, { 119054, 1 }, { 119054, 1 }, { 119119, 68 }, { 119149, 68 }, { 119206, 1 }, { 119316, 68 }, { 119387, 68 }, { 119404, 3 }, { 119516, 68 }, { 119520, 68 }, { 119571, 3 }, { 119573, 68 }, { 119610, 5 },
{ 119621, 68 }, { 119623, 4 }, { 119672, 68 }, { 119692, 3 }, { 119734, 68 }, { 119742, 1 }, { 119754, 1 }, { 119785, 68 }, { 120001, 68 }, { 120115, 4 }, { 120260, 68 }, { 120314, 68 }, { 120416, 68 }, { 120435, 1 }, { 120450, 3 }, { 120530, 68 }, { 120550, 5 }, { 120730, 68 }, { 120731, 68 }, { 120751, 3 }, { 120755, 68 },
{ 120869, 68 }, { 120988, 68 }, { 121061, 68 }, { 121177, 68 }, { 121212, 68 }, { 121214, 1 }, { 121286, 68 }, { 121331, 1 }, { 121344, 68 }, { 121407, 68 }, { 121424, 1 }, { 121491, 68 }, { 121568, 76 }, { 121588, 6 }, { 121651, 68 }, { 121676, 68 }, { 121785, 4 }, { 121830, 3 }, { 121919, 1 }, { 121951, 68 }, { 121991, 1 },
{ 122056, 68 }, { 122062, 68 }, { 122144, 68 }, { 122183, 1 }, { 122331, 68 }, { 122466, 68 }, { 122558, 68 }, { 122570, 68 }, { 122676, 68 }, { 122733, 68 }, { 122774, 6 }, { 122783, 68 }, { 122825, 68 }, { 122865, 68 }, { 122884, 68 }, { 122892, 68 }, { 122911, 68 }, { 122929, 68 }, { 122936, 68 }, { 123190, 68 }, { 123271, 68 },
{ 123271, 68 }, { 123302, 7 }, { 123391, 68 }, { 123394, 68 }, { 123416, 1 }, { 123708, 68 }, { 123752, 68 }, { 123761, 68 }, { 123783, 68 }, { 123794, 68 }, { 123817, 68 }, { 123820, 1 }, { 123823, 1 }, { 123857, 3 }, { 123886, 56 }, { 124023, 1 }, { 124029, 68 }, { 124042, 68 }, { 124056, 3 }, { 124071, 6 }, { 124105, 5 },
{ 124143, 68 }, { 124191, 68 }, { 124207, 1 }, { 124257, 68 }, { 124306, 3 }, { 124338, 68 }, { 124388, 8 }, { 124400, 68 }, { 124418, 68 }, { 124502, 68 }, { 124521, 1 }, { 124533, 68 }, { 124645, 68 }, { 124685, 1 }, { 124694, 68 }, { 124700, 1 }, { 124736, 68 }, { 124891, 7 }, { 124920, 68 }, { 124983, 68 }, { 125014, 68 },
{ 125038, 68 }, { 125084, 68 }, { 125162, 68 }, { 125193, 68 }, { 125285, 68 }, { 125368, 68 }, { 125409, 68 }, { 125570, 68 }, { 125601, 68 }, { 125641, 1 }, { 125721, 68 }, { 125731, 68 }, { 125803, 68 }, { 125904, 68 }, { 125973, 68 }, { 126018, 1 }, { 126034, 5 }, { 126094, 1 }, { 126144, 1 }, { 126195, 68 }, { 126297, 68 },
{ 126389, 68 }, { 126429, 68 }, { 126439, 68 }, { 126499, 68 }, { 126501, 1 }, { 126587, 68 }, { 126663, 68 }, { 126681, 68 }, { 126687, 1 }, { 126781, 68 }, { 126783, 68 }, { 126840, 8 }, { 126843, 68 }, { 126959, 68 }, { 127015, 68 }, { 127101, 68 }, { 127149, 68 }, { 127197, 54 }, { 127268, 68 }, { 127372, 68 }, { 127385, 68 },
{ 127473, 4 }, { 127539, 68 }, { 127598, 68 }, { 127613, 14 }, { 127683, 3 }, { 127684, 68 }, { 127697, 68 }, { 127698, 3 }, { 127773, 68 }, { 127781, 1 }, { 127839, 68 }, { 127905, 68 }, { 127949, 68 }, { 128035, 68 }, { 128046, 1 }, { 128167, 68 }, { 128271, 68 }, { 128307, 1 }, { 128320, 68 }, { 128330, 68 }, { 128375, 68 },
{ 128381, 4 }, { 128447, 68 }, { 128462, 68 }, { 128466, 3 }, { 128466, 68 }, { 128496, 68 }, { 128589, 68 }, { 128616, 3 }, { 128679, 1 }, { 128770, 1 }, { 128793, 68 }, { 128802, 68 }, { 128813, 68 }, { 128900, 68 }, { 128949, 68 }, { 129269, 68 }, { 129271, 3 }, { 129278, 68 }, { 129343, 1 }, { 129408, 67 }, { 129408, 1 },
{ 129421, 6 }, { 129461, 68 }, { 129469, 3 }, { 129482, 68 }, { 129502, 68 }, { 129512, 68 }, { 129551, 68 }, { 129629, 68 }, { 129632, 68 }, { 129679, 1 }, { 129725, 68 }, { 130007, 68 }, { 130018, 16 }, { 130057, 68 }, { 130071, 68 }, { 130087, 68 }, { 130188, 1 }, { 130202, 68 }, { 130316, 68 }, { 130328, 1 }, { 130466, 68 },
{ 130549, 68 }, { 130649, 68 }, { 130705, 3 }, { 130800, 68 }, { 130907, 68 }, { 130989, 68 }, { 131103, 68 }, { 131127, 68 }, { 131200, 5 }, { 131241, 6 }, { 131351, 68 }, { 131413, 68 }, { 131448, 68 }, { 131599, 68 }, { 131634, 1 }, { 131687, 68 }, { 131739, 68 }, { 131758, 68 }, { 131765, 68 }, { 131787, 3 }, { 131819, 3 },
{ 131868, 68 }, { 131886, 68 }, { 131901, 4 }, { 131977, 68 }, { 131990, 68 }, { 132035, 68 }, { 132035, 68 }, { 132043, 68 }, { 132173, 68 }, { 132181, 4 }, { 132181, 6 }, { 132194, 5 }, { 132252, 68 }, { 132262, 6 }, { 132271, 1 }, { 132285, 68 }, { 132328, 68 }, { 132335, 1 }, { 132337, 1 }, { 132389, 5 }, { 132430, 68 },
{ 132451, 68 }, { 132499, 87 }, { 132503, 1 }, { 132520, 4 }, { 132541, 4 }, { 132860, 68 }, { 132862, 4 }, { 132874, 168 }, { 132874, 13 }, { 132875, 168 }, { 132911, 68 }, { 132973, 68 }, { 133051, 68 }, { 133062, 68 }, { 133067, 68 }, { 133138, 68 }, { 133184, 68 }, { 133231, 68 }, { 133297, 3 }, { 133344, 68 }, { 133385, 4 },
{ 133408, 68 }, { 133464, 68 }, { 133522, 68 }, { 133631, 68 }, { 133631, 68 }, { 133702, 68 }, { 133705, 1 }, { 133721, 68 }, { 133746, 68 }, { 133773, 3 }, { 133819, 68 }, { 133843, 68 }, { 133929, 68 }, { 133946, 68 }, { 134113, 4 }, { 134151, 68 }, { 134289, 1 }, { 134385, 68 }, { 134429, 68 }, { 134506, 68 }, { 134511, 68 },
{ 134521, 68 }, { 134558, 1 }, { 134710, 68 }, { 134738, 68 }, { 134751, 3 }, { 134818, 68 }, { 134820, 4 }, { 134879, 68 }, { 134919, 68 }, { 134947, 68 }, { 134948, 3 }, { 135040, 3 }, { 135125, 10 }, { 135155, 68 }, { 135228, 68 }, { 135255, 68 }, { 135296, 3 }, { 135322, 68 }, { 135349, 68 }, { 135428, 3 }, { 135476, 1 },
{ 135503, 68 }, { 135524, 68 }, { 135550, 4 }, { 135594, 68 }, { 135597, 68 }, { 135624, 3 }, { 135741, 68 }, { 135753, 68 }, { 135842, 68 }, { 135853, 68 }, { 135896, 3 }, { 136004, 1 }, { 136061, 1 }, { 136068, 1 }, { 136106, 68 }, { 136145, 68 }, { 136145, 68 }, { 136173, 68 }, { 136186, 68 }, { 136196, 68 }, { 136201, 68 },
{ 136211, 68 }, { 136268, 68 }, { 136298, 68 }, { 136377, 68 }, { 136420, 68 }, { 136475, 23 }, { 136486, 1 }, { 136554, 68 }, { 136641, 68 }, { 136770, 1 }, { 136873, 68 }, { 136877, 1 }, { 136906, 68 }, { 137092, 68 }, { 137143, 68 }, { 137200, 3 }, { 137232, 68 }, { 137239, 68 }, { 137248, 68 }, { 137281, 1 }, { 137301, 68 },
{ 137314, 3 }, { 137352, 1 }, { 137365, 68 }, { 137375, 68 }, { 137411, 68 }, { 137424, 68 }, { 137516, 68 }, { 137532, 68 }, { 137593, 68 }, { 137600, 68 }, { 137658, 68 }, { 137703, 68 }, { 137766, 68 }, { 137791, 68 }, { 137801, 68 }, { 137864, 68 }, { 137870, 3 }, { 137931, 68 }, { 138009, 3 }, { 138013, 1 }, { 138013, 1 },
{ 138066, 68 }, { 138073, 68 }, { 138114, 68 }, { 138150, 68 }, { 138236, 68 }, { 138276, 68 }, { 138286, 68 }, { 138298, 3 }, { 138309, 1 }, { 138373, 3 }, { 138524, 68 }, { 138535, 1 }, { 138593, 4 }, { 138611, 1 }, { 138725, 68 }, { 138807, 68 }, { 138819, 3 }, { 138849, 5 }, { 138867, 68 }, { 138907, 68 }, { 138930, 3 },
{ 139026, 68 }, { 139102, 68 }, { 139108, 3 }, { 139184, 1 }, { 139209, 3 }, { 139282, 68 }, { 139289, 4 }, { 139382, 1 }, { 139421, 1 }, { 139436, 68 }, { 139450, 1 }, { 139523, 3 }, { 139533, 68 }, { 139590, 68 }, { 139590, 68 }, { 139722, 68 }, { 139785, 68 }, { 139785, 1 }, { 139798, 68 }, { 139813, 68 }, { 139868, 68 },
{ 139935, 3 }, { 139990, 3 }, { 140050, 68 }, { 140177, 68 }, { 140177, 4 }, { 140408, 68 }, { 140420, 3 }, { 140461, 68 }, { 140578, 15 }, { 140605, 1368 }, { 140662, 1 }, { 140755, 68 }, { 140786, 68 }, { 140846, 68 }, { 140874, 68 }, { 140959, 1 }, { 140973, 68 }, { 141128, 68 }, { 141132, 68 }, { 141257, 68 }, { 141290, 1 },
{ 141360, 68 }, { 141472, 68 }, { 141545, 68 }, { 141545, 68 }, { 141575, 1 }, { 141606, 5 }, { 141655, 68 }, { 141735, 68 }, { 141767, 5 }, { 141796, 68 }, { 141841, 68 }, { 141915, 68 }, { 141923, 1 }, { 141932, 68 }, { 141994, 68 }, { 142018, 68 }, { 142029, 3 }, { 142072, 68 }, { 142128, 68 }, { 142133, 1 }, { 142261, 68 },
{ 142304, 1 }, { 142400, 68 }, { 142401, 68 }, { 142409, 68 }, { 142479, 68 }, { 142522, 1 }, { 142552, 1 }, { 142589, 68 }, { 142596, 68 }, { 142753, 1 }, { 142766, 68 }, { 142796, 68 }, { 142836, 68 }, { 142871, 68 }, { 143058, 3 }, { 143059, 6 }, { 143063, 3 }, { 143065, 68 }, { 143141, 4 }, { 143173, 68 }, { 143374, 68 },
{ 143399, 68 }, { 143406, 68 }, { 143429, 3 }, { 143430, 68 }, { 143462, 1 }, { 143579, 68 }, { 143663, 68 }, { 143844, 3 }, { 143851, 68 }, { 143926, 68 }, { 143931, 68 }, { 144051, 6 }, { 144085, 10 }, { 144147, 68 }, { 144188, 4 }, { 144238, 4 }, { 144353, 68 }, { 144465, 68 }, { 144474, 68 }, { 144637, 68 }, { 144638, 1 },
{ 144648, 1 }, { 144661, 3 }, { 144812, 68 }, { 144847, 68 }, { 144901, 8 }, { 145058, 68 }, { 145122, 8 }, { 145134, 68 }, { 145150, 68 }, { 145299, 1 }, { 145313, 68 }, { 145314, 3 }, { 145374, 68 }, { 145412, 68 }, { 145432, 68 }, { 145446, 68 }, { 145534, 3 }, { 145592, 68 }, { 145614, 68 }, { 145648, 68 }, { 145721, 68 },
{ 145858, 1 }, { 145970, 3 }, { 145984, 3 }, { 146004, 68 }, { 146016, 3 }, { 146048, 68 }, { 146097, 3 }, { 146103, 68 }, { 146136, 68 }, { 146194, 3 }, { 146230, 1 }, { 146254, 68 }, { 146261, 4 }, { 146269, 4 }, { 146393, 68 }, { 146411, 3 }, { 146501, 68 }, { 146547, 68 }, { 146547, 68 }, { 146573, 68 }, { 146616, 68 },
{ 146622, 3 }, { 146728, 3 }, { 146781, 5 }, { 146805, 4 }, { 146921, 68 }, { 147002, 3 }, { 147072, 68 }, { 147159, 68 }, { 147170, 68 }, { 147203, 1 }, { 147245, 68 }, { 147278, 68 }, { 147422, 68 }, { 147471, 68 }, { 147491, 68 }, { 147607, 23 }, { 147693, 68 }, { 147763, 68 }, { 147775, 6 }, { 147776, 4 }, { 147824, 68 },
{ 147922, 68 }, { 147922, 68 }, { 147937, 68 }, { 147957, 68 }, { 147980, 68 }, { 148008, 68 }, { 148018, 68 }, { 148046, 3 }, { 148071, 4 }, { 148106, 3 }, { 148122, 68 }, { 148139, 68 }, { 148175, 68 }, { 164238, 18 }, { 164315, 28 }, { 164449, 28 }, { 164529, 28 }, { 164574, 348 }, { 164591, 968 }, { 164595, 28 },
{ 164611, 28 }, { 164623, 48 }, { 164632, 108 }, { 164691, 28 }, { 164706, 28 }, { 164755, 28 }, { 164761, 28 }, { 164973, 28 }, { 165030, 28 }, { 165090, 28 }, { 165099, 18 }, { 165126, 28 }, { 165188, 28 }, { 165205, 28 }, { 165275, 18 }, { 165347, 28 }, { 165381, 28 }, { 165562, 28 }, { 165563, 18 }, { 165594, 568 },
{ 165641, 868 }, { 165663, 68 }, { 165759, 28 }, { 165811, 28 }, { 165822, 18 }, { 165830, 18 }, { 165903, 18 }, { 165921, 28 }, { 165953, 18 }, { 166022, 18 }, { 166294, 28 }, { 166333, 28 }, { 166420, 28 }, { 166433, 28 }, { 166442, 18 }, { 166536, 28 }, { 166543, 28 }, { 166556, 28 }, { 166571, 28 }, { 166575, 18 },
{ 166588, 28 }, { 166601, 678 }, { 166663, 788 }, { 166692, 18 }, { 166710, 28 }, { 166759, 28 }, { 166785, 38 }, { 166842, 28 }, { 166843, 28 }, { 166864, 28 }, { 166902, 28 }, { 166996, 28 }, { 166999, 28 }, { 167038, 28 }, { 167112, 48 }, { 167112, 28 }, { 167177, 28 }, { 167180, 28 }, { 167229, 18 }, { 167298, 28 },
{ 167306, 48 }, { 167309, 38 }, { 167402, 28 }, { 167405, 878 }, { 167433, 568 }, { 167435, 18 }, { 167461, 38 }, { 167553, 38 }, { 167688, 58 }, { 167689, 28 }, { 167709, 28 }, { 167744, 28 }, { 167821, 28 }, { 167825, 28 }, { 167925, 108 }, { 167969, 28 }, { 168024, 28 }, { 168089, 28 }, { 168104, 28 }, { 168194, 28 },
{ 168305, 28 }, { 168316, 28 }, { 168366, 28 }, { 168423, 28 }, { 168568, 38 }, { 168582, 558 }, { 168615, 768 }, { 168618, 28 }, { 168638, 28 }, { 168671, 28 }, { 168736, 28 }, { 168747, 28 }, { 168750, 48 }, { 168808, 38 }, { 168814, 48 }, { 168820, 28 }, { 168914, 28 }, { 168968, 28 }, { 168979, 28 }, { 169006, 28 },
{ 169069, 28 }, { 169106, 38 }, { 169158, 28 }, { 169158, 28 }, { 169189, 28 }, { 169253, 28 }, { 169259, 18 }, { 169279, 658 }, { 169325, 568 }, { 169349, 28 }, { 169353, 28 }, { 169378, 28 }, { 169432, 28 }, { 169476, 18 }, { 169476, 18 }, { 169525, 28 }, { 169538, 78 }, { 169555, 28 }, { 169571, 28 }, { 169594, 48 },
{ 169687, 28 }, { 169799, 28 }, { 169831, 28 }, { 170042, 28 }, { 170061, 28 }, { 170065, 18 }, { 170128, 68 }, { 170148, 208 }, { 170215, 708 }, { 170256, 608 }, { 170266, 698 }, { 170275, 78 }, { 170277, 68 }, { 170500, 38 }, { 170516, 38 }, { 170601, 28 }, { 170666, 28 }, { 170668, 48 }, { 170668, 18 }, { 170716, 38 },
{ 170728, 38 }, { 170735, 58 }, { 170847, 38 }, { 170852, 98 }, { 170858, 438 }, { 170859, 568 }, { 170956, 568 }, { 170956, 18 }, { 170967, 28 }, { 171005, 28 }, { 171113, 28 }, { 171279, 28 }, { 171400, 28 }, { 171405, 28 }, { 171448, 18 }, { 171490, 28 }, { 171567, 328 }, { 171590, 28 }, { 171723, 28 }, { 171737, 38 },
{ 171958, 28 }, { 171967, 68 }, { 164238, 18 }, { 164315, 28 }, { 164449, 28 }, { 164529, 28 }, { 164574, 348 }, { 164591, 968 }, { 164595, 28 }, { 164611, 28 }, { 164623, 48 }, { 164632, 108 }, { 164691, 28 }, { 164706, 28 }, { 164755, 28 }, { 164761, 28 }, { 164973, 28 }, { 165030, 28 }, { 165090, 28 }, { 165099, 18 },
{ 165126, 28 }, { 165188, 28 }, { 165205, 28 }, { 165275, 18 }, { 165347, 28 }, { 165381, 28 }, { 165562, 28 }, { 165563, 18 }, { 165594, 568 }, { 165641, 868 }, { 165663, 68 }, { 165759, 28 }, { 165811, 28 }, { 165822, 18 }, { 165830, 18 }, { 165903, 18 }, { 165921, 28 }, { 165953, 18 }, { 166022, 18 }, { 166294, 28 },
{ 166333, 28 }, { 166420, 28 }, { 166433, 28 }, { 166442, 18 }, { 166536, 28 }, { 166543, 28 }, { 166556, 28 }, { 166571, 28 }, { 166575, 18 }, { 166588, 28 }, { 166601, 678 }, { 166663, 788 }, { 166692, 18 }, { 166710, 28 }, { 166759, 28 }, { 166785, 38 }, { 166842, 28 }, { 166843, 28 }, { 166864, 28 }, { 166902, 28 },
{ 166996, 28 }, { 166999, 28 }, { 167038, 28 }, { 167112, 48 }, { 167112, 28 }, { 167177, 28 }, { 167180, 28 }, { 167229, 18 }, { 167298, 28 }, { 167306, 48 }, { 167309, 38 }, { 167402, 28 }, { 167405, 878 }, { 167433, 568 }, { 167435, 18 }, { 167461, 38 }, { 167553, 38 }, { 167688, 58 }, { 167689, 28 }, { 167709, 28 },
{ 167744, 28 }, { 167821, 28 }, { 167825, 28 }, { 167925, 108 }, { 167969, 28 }, { 168024, 28 }, { 168089, 28 }, { 168104, 28 }, { 168194, 28 }, { 168305, 28 }, { 168316, 28 }, { 168366, 28 }, { 168423, 28 }, { 168568, 38 }, { 168582, 558 }, { 168615, 768 }, { 168618, 28 }, { 168638, 28 }, { 168671, 28 }, { 168736, 28 },
{ 168747, 28 }, { 168750, 48 }, { 168808, 38 }, { 168814, 48 }, { 168820, 28 }, { 168914, 28 }, { 168968, 28 }, { 168979, 28 }, { 169006, 28 }, { 169069, 28 }, { 169106, 38 }, { 169158, 28 }, { 169158, 28 }, { 169189, 28 }, { 169253, 28 }, { 169259, 18 }, { 169279, 658 }, { 169325, 568 }, { 169349, 28 }, { 169353, 28 },
{ 169378, 28 }, { 169432, 28 }, { 169476, 18 }, { 169476, 18 }, { 169525, 28 }, { 169538, 78 }, { 169555, 28 }, { 169571, 28 }, { 169594, 48 }, { 169687, 28 }, { 169799, 28 }, { 169831, 28 }, { 170042, 28 }, { 170061, 28 }, { 170065, 18 }, { 170128, 68 }, { 170148, 208 }, { 170215, 708 }, { 170256, 608 }, { 170266, 698 },
{ 170275, 78 }, { 170277, 68 }, { 170500, 38 }, { 170516, 38 }, { 170601, 28 }, { 170666, 28 }, { 170668, 48 }, { 170668, 18 }, { 170716, 38 }, { 170728, 38 }, { 170735, 58 }, { 170847, 38 }, { 170852, 98 }, { 170858, 438 }, { 170859, 568 }, { 170956, 568 }, { 170956, 18 }, { 170967, 28 }, { 171005, 28 }, { 171113, 28 },
{ 171279, 28 }, { 171400, 28 }, { 171405, 28 }, { 171448, 18 }, { 171490, 28 }, { 171567, 328 }, { 171590, 28 }, { 171723, 28 }, { 171737, 38 }, { 171958, 28 }, { 171967, 2 } };
}
} | 4,589 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/util/ExceptionsTest.java | package com.netflix.hystrix.util;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class ExceptionsTest {
@Test
public void testCastOfException(){
Exception exception = new IOException("simulated checked exception message");
try{
Exceptions.sneakyThrow(exception);
fail();
} catch(Exception e){
assertTrue(e instanceof IOException);
}
}
}
| 4,590 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/util/HystrixTimerTest.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.util;
import com.netflix.hystrix.HystrixTimerThreadPoolProperties;
import com.netflix.hystrix.strategy.HystrixPlugins;
import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy;
import com.netflix.hystrix.util.HystrixTimer.ScheduledExecutor;
import com.netflix.hystrix.util.HystrixTimer.TimerListener;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.lang.ref.Reference;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.*;
public class HystrixTimerTest {
@Before
public void setUp() {
HystrixTimer timer = HystrixTimer.getInstance();
HystrixTimer.reset();
HystrixPlugins.reset();
}
@After
public void tearDown() {
HystrixPlugins.reset();
}
@Test
public void testSingleCommandSingleInterval() {
HystrixTimer timer = HystrixTimer.getInstance();
TestListener l1 = new TestListener(50, "A");
timer.addTimerListener(l1);
TestListener l2 = new TestListener(50, "B");
timer.addTimerListener(l2);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// we should have 7 or more 50ms ticks within 500ms
System.out.println("l1 ticks: " + l1.tickCount.get());
System.out.println("l2 ticks: " + l2.tickCount.get());
assertTrue(l1.tickCount.get() > 7);
assertTrue(l2.tickCount.get() > 7);
}
@Test
public void testSingleCommandMultipleIntervals() {
HystrixTimer timer = HystrixTimer.getInstance();
TestListener l1 = new TestListener(100, "A");
timer.addTimerListener(l1);
TestListener l2 = new TestListener(10, "B");
timer.addTimerListener(l2);
TestListener l3 = new TestListener(25, "C");
timer.addTimerListener(l3);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// we should have 3 or more 100ms ticks within 500ms
System.out.println("l1 ticks: " + l1.tickCount.get());
assertTrue(l1.tickCount.get() >= 3);
// but it can't be more than 6
assertTrue(l1.tickCount.get() < 6);
// we should have 30 or more 10ms ticks within 500ms
System.out.println("l2 ticks: " + l2.tickCount.get());
assertTrue(l2.tickCount.get() > 30);
assertTrue(l2.tickCount.get() < 550);
// we should have 15-20 25ms ticks within 500ms
System.out.println("l3 ticks: " + l3.tickCount.get());
assertTrue(l3.tickCount.get() > 14);
assertTrue(l3.tickCount.get() < 25);
}
@Test
public void testSingleCommandRemoveListener() {
HystrixTimer timer = HystrixTimer.getInstance();
TestListener l1 = new TestListener(50, "A");
timer.addTimerListener(l1);
TestListener l2 = new TestListener(50, "B");
Reference<TimerListener> l2ref = timer.addTimerListener(l2);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// we should have 7 or more 50ms ticks within 500ms
System.out.println("l1 ticks: " + l1.tickCount.get());
System.out.println("l2 ticks: " + l2.tickCount.get());
assertTrue(l1.tickCount.get() > 7);
assertTrue(l2.tickCount.get() > 7);
// remove l2
l2ref.clear();
// reset counts
l1.tickCount.set(0);
l2.tickCount.set(0);
// wait for time to pass again
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// we should have 7 or more 50ms ticks within 500ms
System.out.println("l1 ticks: " + l1.tickCount.get());
System.out.println("l2 ticks: " + l2.tickCount.get());
// l1 should continue ticking
assertTrue(l1.tickCount.get() > 7);
// we should have no ticks on l2 because we removed it
System.out.println("tickCount.get(): " + l2.tickCount.get() + " on l2: " + l2);
assertEquals(0, l2.tickCount.get());
}
@Test
public void testReset() {
HystrixTimer timer = HystrixTimer.getInstance();
TestListener l1 = new TestListener(50, "A");
timer.addTimerListener(l1);
ScheduledExecutor ex = timer.executor.get();
assertFalse(ex.executor.isShutdown());
// perform reset which should shut it down
HystrixTimer.reset();
assertTrue(ex.executor.isShutdown());
assertNull(timer.executor.get());
// assert it starts up again on use
TestListener l2 = new TestListener(50, "A");
timer.addTimerListener(l2);
ScheduledExecutor ex2 = timer.executor.get();
assertFalse(ex2.executor.isShutdown());
// reset again to shutdown what we just started
HystrixTimer.reset();
// try resetting again to make sure it's idempotent (ie. doesn't blow up on an NPE)
HystrixTimer.reset();
}
@Test
public void testThreadPoolSizeDefault() {
HystrixTimer hystrixTimer = HystrixTimer.getInstance();
hystrixTimer.startThreadIfNeeded();
assertEquals(Runtime.getRuntime().availableProcessors(), hystrixTimer.executor.get().getThreadPool().getCorePoolSize());
}
@Test
public void testThreadPoolSizeConfiguredWithBuilder() {
HystrixTimerThreadPoolProperties.Setter builder = HystrixTimerThreadPoolProperties.Setter().withCoreSize(1);
final HystrixTimerThreadPoolProperties props = new HystrixTimerThreadPoolProperties(builder) {
};
HystrixPropertiesStrategy strategy = new HystrixPropertiesStrategy() {
@Override
public HystrixTimerThreadPoolProperties getTimerThreadPoolProperties() {
return props;
}
};
HystrixPlugins.getInstance().registerPropertiesStrategy(strategy);
HystrixTimer hystrixTimer = HystrixTimer.getInstance();
hystrixTimer.startThreadIfNeeded();
assertEquals(1, hystrixTimer.executor.get().getThreadPool().getCorePoolSize());
}
private static class TestListener implements TimerListener {
private final int interval;
AtomicInteger tickCount = new AtomicInteger();
TestListener(int interval, String value) {
this.interval = interval;
}
@Override
public void tick() {
tickCount.incrementAndGet();
}
@Override
public int getIntervalTimeInMilliseconds() {
return interval;
}
}
public static void main(String args[]) {
PlayListener l1 = new PlayListener();
PlayListener l2 = new PlayListener();
PlayListener l3 = new PlayListener();
PlayListener l4 = new PlayListener();
PlayListener l5 = new PlayListener();
Reference<TimerListener> ref = HystrixTimer.getInstance().addTimerListener(l1);
HystrixTimer.getInstance().addTimerListener(l2);
HystrixTimer.getInstance().addTimerListener(l3);
HystrixTimer.getInstance().addTimerListener(l4);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ref.clear();
HystrixTimer.getInstance().addTimerListener(l5);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("counter: " + l1.counter);
System.out.println("counter: " + l2.counter);
System.out.println("counter: " + l3.counter);
System.out.println("counter: " + l4.counter);
System.out.println("counter: " + l5.counter);
}
public static class PlayListener implements TimerListener {
int counter = 0;
@Override
public void tick() {
counter++;
}
@Override
public int getIntervalTimeInMilliseconds() {
return 10;
}
}
}
| 4,591 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/config/HystrixConfigurationStreamTest.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.hystrix.config;
import com.hystrix.junit.HystrixRequestContextRule;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.config.HystrixConfiguration;
import com.netflix.hystrix.config.HystrixConfigurationStream;
import com.netflix.hystrix.metric.CommandStreamTest;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.schedulers.Schedulers;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class HystrixConfigurationStreamTest extends CommandStreamTest {
@Rule
public HystrixRequestContextRule ctx = new HystrixRequestContextRule();
HystrixConfigurationStream stream;
private final static HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("Config");
private final static HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey("Command");
@Before
public void init() {
stream = HystrixConfigurationStream.getNonSingletonInstanceOnlyUsedInUnitTests(10);
}
@Test
public void testStreamHasData() throws Exception {
final AtomicBoolean commandShowsUp = new AtomicBoolean(false);
final AtomicBoolean threadPoolShowsUp = new AtomicBoolean(false);
final CountDownLatch latch = new CountDownLatch(1);
final int NUM = 10;
for (int i = 0; i < 2; i++) {
HystrixCommand<Integer> cmd = Command.from(groupKey, commandKey, HystrixEventType.SUCCESS, 50);
cmd.observe();
}
stream.observe().take(NUM).subscribe(
new Subscriber<HystrixConfiguration>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " OnCompleted");
latch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " OnError : " + e);
latch.countDown();
}
@Override
public void onNext(HystrixConfiguration configuration) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Received data with : " + configuration.getCommandConfig().size() + " commands");
if (configuration.getCommandConfig().containsKey(commandKey)) {
commandShowsUp.set(true);
}
if (!configuration.getThreadPoolConfig().isEmpty()) {
threadPoolShowsUp.set(true);
}
}
});
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
assertTrue(commandShowsUp.get());
assertTrue(threadPoolShowsUp.get());
}
@Test
public void testTwoSubscribersOneUnsubscribes() throws Exception {
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final AtomicInteger payloads1 = new AtomicInteger(0);
final AtomicInteger payloads2 = new AtomicInteger(0);
Subscription s1 = stream
.observe()
.take(100)
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
latch1.countDown();
}
})
.subscribe(new Subscriber<HystrixConfiguration>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 1 OnCompleted");
latch1.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 1 OnError : " + e);
latch1.countDown();
}
@Override
public void onNext(HystrixConfiguration configuration) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 1 OnNext : " + configuration);
payloads1.incrementAndGet();
}
});
Subscription s2 = stream
.observe()
.take(100)
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
latch2.countDown();
}
})
.subscribe(new Subscriber<HystrixConfiguration>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 2 OnCompleted");
latch2.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 2 OnError : " + e);
latch2.countDown();
}
@Override
public void onNext(HystrixConfiguration configuration) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 2 OnNext : " + configuration);
payloads2.incrementAndGet();
}
});
//execute 1 command, then unsubscribe from first stream. then execute the rest
for (int i = 0; i < 50; i++) {
HystrixCommand<Integer> cmd = Command.from(groupKey, commandKey, HystrixEventType.SUCCESS, 50);
cmd.execute();
if (i == 1) {
s1.unsubscribe();
}
}
assertTrue(latch1.await(10000, TimeUnit.MILLISECONDS));
assertTrue(latch2.await(10000, TimeUnit.MILLISECONDS));
System.out.println("s1 got : " + payloads1.get() + ", s2 got : " + payloads2.get());
assertTrue("s1 got data", payloads1.get() > 0);
assertTrue("s2 got data", payloads2.get() > 0);
assertTrue("s1 got less data than s2", payloads2.get() > payloads1.get());
}
@Test
public void testTwoSubscribersBothUnsubscribe() throws Exception {
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final AtomicInteger payloads1 = new AtomicInteger(0);
final AtomicInteger payloads2 = new AtomicInteger(0);
Subscription s1 = stream
.observe()
.take(100)
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
latch1.countDown();
}
})
.subscribe(new Subscriber<HystrixConfiguration>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 1 OnCompleted");
latch1.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 1 OnError : " + e);
latch1.countDown();
}
@Override
public void onNext(HystrixConfiguration configuration) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 1 OnNext : " + configuration);
payloads1.incrementAndGet();
}
});
Subscription s2 = stream
.observe()
.take(100)
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
latch2.countDown();
}
})
.subscribe(new Subscriber<HystrixConfiguration>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 2 OnCompleted");
latch2.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 2 OnError : " + e);
latch2.countDown();
}
@Override
public void onNext(HystrixConfiguration configuration) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 2 OnNext : " + configuration);
payloads2.incrementAndGet();
}
});
//execute 2 commands, then unsubscribe from both streams, then execute the rest
for (int i = 0; i < 10; i++) {
HystrixCommand<Integer> cmd = Command.from(groupKey, commandKey, HystrixEventType.SUCCESS, 50);
cmd.execute();
if (i == 2) {
s1.unsubscribe();
s2.unsubscribe();
}
}
assertFalse(stream.isSourceCurrentlySubscribed()); //both subscriptions have been cancelled - source should be too
assertTrue(latch1.await(10000, TimeUnit.MILLISECONDS));
assertTrue(latch2.await(10000, TimeUnit.MILLISECONDS));
System.out.println("s1 got : " + payloads1.get() + ", s2 got : " + payloads2.get());
assertTrue("s1 got data", payloads1.get() > 0);
assertTrue("s2 got data", payloads2.get() > 0);
}
@Test
public void testTwoSubscribersOneSlowOneFast() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicBoolean foundError = new AtomicBoolean(false);
Observable<HystrixConfiguration> fast = stream
.observe()
.observeOn(Schedulers.newThread());
Observable<HystrixConfiguration> slow = stream
.observe()
.observeOn(Schedulers.newThread())
.map(new Func1<HystrixConfiguration, HystrixConfiguration>() {
@Override
public HystrixConfiguration call(HystrixConfiguration config) {
try {
Thread.sleep(100);
return config;
} catch (InterruptedException ex) {
return config;
}
}
});
Observable<Boolean> checkZippedEqual = Observable.zip(fast, slow, new Func2<HystrixConfiguration, HystrixConfiguration, Boolean>() {
@Override
public Boolean call(HystrixConfiguration payload, HystrixConfiguration payload2) {
return payload == payload2;
}
});
Subscription s1 = checkZippedEqual
.take(10000)
.subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : OnCompleted");
latch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : OnError : " + e);
e.printStackTrace();
foundError.set(true);
latch.countDown();
}
@Override
public void onNext(Boolean b) {
//System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : OnNext : " + b);
}
});
for (int i = 0; i < 50; i++) {
HystrixCommand<Integer> cmd = Command.from(groupKey, commandKey, HystrixEventType.SUCCESS, 50);
cmd.execute();
}
latch.await(10000, TimeUnit.MILLISECONDS);
assertFalse(foundError.get());
}
}
| 4,592 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/collapser/CollapsedRequestSubjectTest.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.collapser;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.junit.Test;
import rx.Observable;
public class CollapsedRequestSubjectTest {
@Test
public void testSetResponseSuccess() throws InterruptedException, ExecutionException {
CollapsedRequestSubject<String, String> cr = new CollapsedRequestSubject<String, String>("hello");
Observable<String> o = cr.toObservable();
Future<String> v = o.toBlocking().toFuture();
cr.setResponse("theResponse");
// fetch value
assertEquals("theResponse", v.get());
}
@Test
public void testSetNullResponseSuccess() throws InterruptedException, ExecutionException {
CollapsedRequestSubject<String, String> cr = new CollapsedRequestSubject<String, String>("hello");
Observable<String> o = cr.toObservable();
Future<String> v = o.toBlocking().toFuture();
cr.setResponse(null);
// fetch value
assertEquals(null, v.get());
}
@Test
public void testSetException() throws InterruptedException, ExecutionException {
CollapsedRequestSubject<String, String> cr = new CollapsedRequestSubject<String, String>("hello");
Observable<String> o = cr.toObservable();
Future<String> v = o.toBlocking().toFuture();
cr.setException(new RuntimeException("anException"));
// fetch value
try {
v.get();
fail("expected exception");
} catch (ExecutionException e) {
assertEquals("anException", e.getCause().getMessage());
}
}
@Test
public void testSetExceptionAfterResponse() throws InterruptedException, ExecutionException {
CollapsedRequestSubject<String, String> cr = new CollapsedRequestSubject<String, String>("hello");
Observable<String> o = cr.toObservable();
Future<String> v = o.toBlocking().toFuture();
cr.setResponse("theResponse");
try {
cr.setException(new RuntimeException("anException"));
fail("expected IllegalState");
} catch (IllegalStateException e) {
}
assertEquals("theResponse", v.get());
}
@Test
public void testSetResponseAfterException() throws InterruptedException, ExecutionException {
CollapsedRequestSubject<String, String> cr = new CollapsedRequestSubject<String, String>("hello");
Observable<String> o = cr.toObservable();
Future<String> v = o.toBlocking().toFuture();
cr.setException(new RuntimeException("anException"));
try {
cr.setResponse("theResponse");
fail("expected IllegalState");
} catch (IllegalStateException e) {
}
try {
v.get();
fail("expected exception");
} catch (ExecutionException e) {
assertEquals("anException", e.getCause().getMessage());
}
}
@Test
public void testSetResponseDuplicate() throws InterruptedException, ExecutionException {
CollapsedRequestSubject<String, String> cr = new CollapsedRequestSubject<String, String>("hello");
Observable<String> o = cr.toObservable();
Future<String> v = o.toBlocking().toFuture();
cr.setResponse("theResponse");
try {
cr.setResponse("theResponse2");
fail("expected IllegalState");
} catch (IllegalStateException e) {
}
assertEquals("theResponse", v.get());
}
@Test(expected = CancellationException.class)
public void testSetResponseAfterUnsubscribe() throws InterruptedException, ExecutionException {
CollapsedRequestSubject<String, String> cr = new CollapsedRequestSubject<String, String>("hello");
Observable<String> o = cr.toObservable();
Future<String> f = o.toBlocking().toFuture();
// cancel/unsubscribe
f.cancel(true);
try {
cr.setResponse("theResponse");
} catch (IllegalStateException e) {
fail("this should have done nothing as it was unsubscribed already");
}
// expect CancellationException after cancelling
f.get();
}
@Test(expected = CancellationException.class)
public void testSetExceptionAfterUnsubscribe() throws InterruptedException, ExecutionException {
CollapsedRequestSubject<String, String> cr = new CollapsedRequestSubject<String, String>("hello");
Observable<String> o = cr.toObservable();
Future<String> f = o.toBlocking().toFuture();
// cancel/unsubscribe
f.cancel(true);
try {
cr.setException(new RuntimeException("anException"));
} catch (IllegalStateException e) {
fail("this should have done nothing as it was unsubscribed already");
}
// expect CancellationException after cancelling
f.get();
}
@Test
public void testUnsubscribeAfterSetResponse() throws InterruptedException, ExecutionException {
CollapsedRequestSubject<String, String> cr = new CollapsedRequestSubject<String, String>("hello");
Observable<String> o = cr.toObservable();
Future<String> v = o.toBlocking().toFuture();
cr.setResponse("theResponse");
// unsubscribe after the value is sent
v.cancel(true);
// still get value as it was set before canceling
assertEquals("theResponse", v.get());
}
}
| 4,593 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/metric/HystrixCommandCompletionStreamTest.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.metric;
import com.netflix.hystrix.ExecutionResult;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.HystrixThreadPoolKey;
import org.junit.Test;
import rx.Subscriber;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class HystrixCommandCompletionStreamTest {
private <T> Subscriber<T> getLatchedSubscriber(final CountDownLatch latch) {
return new Subscriber<T>() {
@Override
public void onCompleted() {
latch.countDown();
}
@Override
public void onError(Throwable e) {
fail(e.getMessage());
e.printStackTrace();
latch.countDown();
}
@Override
public void onNext(T value) {
System.out.println("OnNext : " + value);
}
};
}
static final HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey("COMMAND");
static final HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool");
final HystrixCommandCompletionStream commandStream = new HystrixCommandCompletionStream(commandKey);
@Test
public void noEvents() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
Subscriber<HystrixCommandCompletion> subscriber = getLatchedSubscriber(latch);
commandStream.observe().take(1).subscribe(subscriber);
//no writes
assertFalse(latch.await(1000, TimeUnit.MILLISECONDS));
}
@Test
public void testSingleWriteSingleSubscriber() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
Subscriber<HystrixCommandCompletion> subscriber = getLatchedSubscriber(latch);
commandStream.observe().take(1).subscribe(subscriber);
ExecutionResult result = ExecutionResult.from(HystrixEventType.SUCCESS).setExecutedInThread();
HystrixCommandCompletion event = HystrixCommandCompletion.from(result, commandKey, threadPoolKey);
commandStream.write(event);
assertTrue(latch.await(1000, TimeUnit.MILLISECONDS));
}
@Test
public void testSingleWriteMultipleSubscribers() throws InterruptedException {
CountDownLatch latch1 = new CountDownLatch(1);
Subscriber<HystrixCommandCompletion> subscriber1 = getLatchedSubscriber(latch1);
CountDownLatch latch2 = new CountDownLatch(1);
Subscriber<HystrixCommandCompletion> subscriber2 = getLatchedSubscriber(latch2);
commandStream.observe().take(1).subscribe(subscriber1);
commandStream.observe().take(1).subscribe(subscriber2);
ExecutionResult result = ExecutionResult.from(HystrixEventType.SUCCESS).setExecutedInThread();
HystrixCommandCompletion event = HystrixCommandCompletion.from(result, commandKey, threadPoolKey);
commandStream.write(event);
assertTrue(latch1.await(1000, TimeUnit.MILLISECONDS));
assertTrue(latch2.await(10, TimeUnit.MILLISECONDS));
}
} | 4,594 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/metric/CommandStreamTest.java | /**
* Copyright 2015 Netflix, Inc.
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.metric;
import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.HystrixCollapserKey;
import com.netflix.hystrix.HystrixCollapserProperties;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import rx.functions.Func2;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public abstract class CommandStreamTest {
static final AtomicInteger uniqueId = new AtomicInteger(0);
public static class Command extends HystrixCommand<Integer> {
final String arg;
final HystrixEventType executionResult;
final int executionLatency;
final HystrixEventType fallbackExecutionResult;
final int fallbackExecutionLatency;
private Command(Setter setter, HystrixEventType executionResult, int executionLatency, String arg,
HystrixEventType fallbackExecutionResult, int fallbackExecutionLatency) {
super(setter);
this.executionResult = executionResult;
this.executionLatency = executionLatency;
this.fallbackExecutionResult = fallbackExecutionResult;
this.fallbackExecutionLatency = fallbackExecutionLatency;
this.arg = arg;
}
public static Command from(HystrixCommandGroupKey groupKey, HystrixCommandKey key, HystrixEventType desiredEventType) {
return from(groupKey, key, desiredEventType, 0);
}
public static Command from(HystrixCommandGroupKey groupKey, HystrixCommandKey key, HystrixEventType desiredEventType, int latency) {
return from(groupKey, key, desiredEventType, latency, HystrixCommandProperties.ExecutionIsolationStrategy.THREAD);
}
public static Command from(HystrixCommandGroupKey groupKey, HystrixCommandKey key, HystrixEventType desiredEventType, int latency,
HystrixEventType desiredFallbackEventType) {
return from(groupKey, key, desiredEventType, latency, HystrixCommandProperties.ExecutionIsolationStrategy.THREAD, desiredFallbackEventType);
}
public static Command from(HystrixCommandGroupKey groupKey, HystrixCommandKey key, HystrixEventType desiredEventType, int latency,
HystrixEventType desiredFallbackEventType, int fallbackLatency) {
return from(groupKey, key, desiredEventType, latency, HystrixCommandProperties.ExecutionIsolationStrategy.THREAD, desiredFallbackEventType, fallbackLatency);
}
public static Command from(HystrixCommandGroupKey groupKey, HystrixCommandKey key, HystrixEventType desiredEventType, int latency,
HystrixCommandProperties.ExecutionIsolationStrategy isolationStrategy) {
return from(groupKey, key, desiredEventType, latency, isolationStrategy, HystrixEventType.FALLBACK_SUCCESS, 0);
}
public static Command from(HystrixCommandGroupKey groupKey, HystrixCommandKey key, HystrixEventType desiredEventType, int latency,
HystrixCommandProperties.ExecutionIsolationStrategy isolationStrategy,
HystrixEventType desiredFallbackEventType) {
return from(groupKey, key, desiredEventType, latency, isolationStrategy, desiredFallbackEventType, 0);
}
public static Command from(HystrixCommandGroupKey groupKey, HystrixCommandKey key, HystrixEventType desiredEventType, int latency,
HystrixCommandProperties.ExecutionIsolationStrategy isolationStrategy,
HystrixEventType desiredFallbackEventType, int fallbackLatency) {
Setter setter = Setter.withGroupKey(groupKey)
.andCommandKey(key)
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withExecutionTimeoutInMilliseconds(600)
.withExecutionIsolationStrategy(isolationStrategy)
.withCircuitBreakerEnabled(true)
.withCircuitBreakerRequestVolumeThreshold(3)
.withMetricsHealthSnapshotIntervalInMilliseconds(100)
.withMetricsRollingStatisticalWindowInMilliseconds(1000)
.withMetricsRollingStatisticalWindowBuckets(10)
.withRequestCacheEnabled(true)
.withRequestLogEnabled(true)
.withFallbackIsolationSemaphoreMaxConcurrentRequests(5))
.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(groupKey.name()))
.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
.withCoreSize(10)
.withMaxQueueSize(-1));
String uniqueArg;
switch (desiredEventType) {
case SUCCESS:
uniqueArg = uniqueId.incrementAndGet() + "";
return new Command(setter, HystrixEventType.SUCCESS, latency, uniqueArg, desiredFallbackEventType, 0);
case FAILURE:
uniqueArg = uniqueId.incrementAndGet() + "";
return new Command(setter, HystrixEventType.FAILURE, latency, uniqueArg, desiredFallbackEventType, fallbackLatency);
case TIMEOUT:
uniqueArg = uniqueId.incrementAndGet() + "";
return new Command(setter, HystrixEventType.SUCCESS, 700, uniqueArg, desiredFallbackEventType, fallbackLatency);
case BAD_REQUEST:
uniqueArg = uniqueId.incrementAndGet() + "";
return new Command(setter, HystrixEventType.BAD_REQUEST, latency, uniqueArg, desiredFallbackEventType, 0);
case RESPONSE_FROM_CACHE:
String arg = uniqueId.get() + "";
return new Command(setter, HystrixEventType.SUCCESS, 0, arg, desiredFallbackEventType, 0);
default:
throw new RuntimeException("not supported yet");
}
}
public static List<Command> getCommandsWithResponseFromCache(HystrixCommandGroupKey groupKey, HystrixCommandKey key) {
Command cmd1 = Command.from(groupKey, key, HystrixEventType.SUCCESS);
Command cmd2 = Command.from(groupKey, key, HystrixEventType.RESPONSE_FROM_CACHE);
List<Command> cmds = new ArrayList<Command>();
cmds.add(cmd1);
cmds.add(cmd2);
return cmds;
}
@Override
protected Integer run() throws Exception {
try {
Thread.sleep(executionLatency);
switch (executionResult) {
case SUCCESS:
return 1;
case FAILURE:
throw new RuntimeException("induced failure");
case BAD_REQUEST:
throw new HystrixBadRequestException("induced bad request");
default:
throw new RuntimeException("unhandled HystrixEventType : " + executionResult);
}
} catch (InterruptedException ex) {
System.out.println("Received InterruptedException : " + ex);
throw ex;
}
}
@Override
protected Integer getFallback() {
try {
Thread.sleep(fallbackExecutionLatency);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
switch (fallbackExecutionResult) {
case FALLBACK_SUCCESS: return -1;
case FALLBACK_FAILURE: throw new RuntimeException("induced failure");
case FALLBACK_MISSING: throw new UnsupportedOperationException("fallback not defined");
default: throw new RuntimeException("unhandled HystrixEventType : " + fallbackExecutionResult);
}
}
@Override
protected String getCacheKey() {
return arg;
}
}
public static class Collapser extends HystrixCollapser<List<Integer>, Integer, Integer> {
private final Integer arg;
public static Collapser from(Integer arg) {
return new Collapser(HystrixCollapserKey.Factory.asKey("Collapser"), arg);
}
public static Collapser from(HystrixCollapserKey key, Integer arg) {
return new Collapser(key, arg);
}
private Collapser(HystrixCollapserKey key, Integer arg) {
super(Setter.withCollapserKey(key)
.andCollapserPropertiesDefaults(
HystrixCollapserProperties.Setter()
.withTimerDelayInMilliseconds(100)));
this.arg = arg;
}
@Override
public Integer getRequestArgument() {
return arg;
}
@Override
protected HystrixCommand<List<Integer>> createCommand(Collection<CollapsedRequest<Integer, Integer>> collapsedRequests) {
List<Integer> args = new ArrayList<Integer>();
for (CollapsedRequest<Integer, Integer> collapsedReq: collapsedRequests) {
args.add(collapsedReq.getArgument());
}
return new BatchCommand(args);
}
@Override
protected void mapResponseToRequests(List<Integer> batchResponse, Collection<CollapsedRequest<Integer, Integer>> collapsedRequests) {
for (CollapsedRequest<Integer, Integer> collapsedReq: collapsedRequests) {
collapsedReq.emitResponse(collapsedReq.getArgument());
collapsedReq.setComplete();
}
}
@Override
protected String getCacheKey() {
return arg.toString();
}
}
private static class BatchCommand extends HystrixCommand<List<Integer>> {
private List<Integer> args;
protected BatchCommand(List<Integer> args) {
super(HystrixCommandGroupKey.Factory.asKey("BATCH"));
this.args = args;
}
@Override
protected List<Integer> run() throws Exception {
System.out.println(Thread.currentThread().getName() + " : Executing batch of : " + args.size());
return args;
}
}
protected static String bucketToString(long[] eventCounts) {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (HystrixEventType eventType : HystrixEventType.values()) {
if (eventCounts[eventType.ordinal()] > 0) {
sb.append(eventType.name()).append("->").append(eventCounts[eventType.ordinal()]).append(", ");
}
}
sb.append("]");
return sb.toString();
}
protected static boolean hasData(long[] eventCounts) {
for (HystrixEventType eventType : HystrixEventType.values()) {
if (eventCounts[eventType.ordinal()] > 0) {
return true;
}
}
return false;
}
}
| 4,595 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/metric/HystrixThreadEventStreamTest.java | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix.metric;
import com.netflix.hystrix.ExecutionResult;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.HystrixThreadPoolKey;
import org.junit.Test;
import rx.Subscriber;
import rx.functions.Action1;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
public class HystrixThreadEventStreamTest {
HystrixCommandKey commandKey;
HystrixThreadPoolKey threadPoolKey;
HystrixThreadEventStream writeToStream;
HystrixCommandCompletionStream readCommandStream;
HystrixThreadPoolCompletionStream readThreadPoolStream;
public HystrixThreadEventStreamTest() {
commandKey = HystrixCommandKey.Factory.asKey("CMD-ThreadStream");
threadPoolKey = HystrixThreadPoolKey.Factory.asKey("TP-ThreadStream");
writeToStream = HystrixThreadEventStream.getInstance();
readCommandStream = HystrixCommandCompletionStream.getInstance(commandKey);
readThreadPoolStream = HystrixThreadPoolCompletionStream.getInstance(threadPoolKey);
}
private <T> Subscriber<T> getLatchedSubscriber(final CountDownLatch latch) {
return new Subscriber<T>() {
@Override
public void onCompleted() {
latch.countDown();
}
@Override
public void onError(Throwable e) {
fail(e.getMessage());
e.printStackTrace();
latch.countDown();
}
@Override
public void onNext(T value) {
System.out.println("OnNext : " + value);
}
};
}
@Test
public void noEvents() throws InterruptedException {
CountDownLatch commandLatch = new CountDownLatch(1);
CountDownLatch threadPoolLatch = new CountDownLatch(1);
Subscriber<HystrixCommandCompletion> commandSubscriber = getLatchedSubscriber(commandLatch);
readCommandStream.observe().take(1).subscribe(commandSubscriber);
Subscriber<HystrixCommandCompletion> threadPoolSubscriber = getLatchedSubscriber(threadPoolLatch);
readThreadPoolStream.observe().take(1).subscribe(threadPoolSubscriber);
//no writes
assertFalse(commandLatch.await(1000, TimeUnit.MILLISECONDS));
assertFalse(threadPoolLatch.await(1000, TimeUnit.MILLISECONDS));
}
@Test
public void testThreadIsolatedSuccess() throws InterruptedException {
CountDownLatch commandLatch = new CountDownLatch(1);
CountDownLatch threadPoolLatch = new CountDownLatch(1);
Subscriber<HystrixCommandCompletion> commandSubscriber = getLatchedSubscriber(commandLatch);
readCommandStream.observe().take(1).subscribe(commandSubscriber);
Subscriber<HystrixCommandCompletion> threadPoolSubscriber = getLatchedSubscriber(threadPoolLatch);
readThreadPoolStream.observe().take(1).subscribe(threadPoolSubscriber);
ExecutionResult result = ExecutionResult.from(HystrixEventType.SUCCESS).setExecutedInThread();
writeToStream.executionDone(result, commandKey, threadPoolKey);
assertTrue(commandLatch.await(1000, TimeUnit.MILLISECONDS));
assertTrue(threadPoolLatch.await(1000, TimeUnit.MILLISECONDS));
}
@Test
public void testSemaphoreIsolatedSuccess() throws Exception {
CountDownLatch commandLatch = new CountDownLatch(1);
CountDownLatch threadPoolLatch = new CountDownLatch(1);
Subscriber<HystrixCommandCompletion> commandSubscriber = getLatchedSubscriber(commandLatch);
readCommandStream.observe().take(1).subscribe(commandSubscriber);
Subscriber<HystrixCommandCompletion> threadPoolSubscriber = getLatchedSubscriber(threadPoolLatch);
readThreadPoolStream.observe().take(1).subscribe(threadPoolSubscriber);
ExecutionResult result = ExecutionResult.from(HystrixEventType.SUCCESS);
writeToStream.executionDone(result, commandKey, threadPoolKey);
assertTrue(commandLatch.await(1000, TimeUnit.MILLISECONDS));
assertFalse(threadPoolLatch.await(1000, TimeUnit.MILLISECONDS));
}
@Test
public void testThreadIsolatedFailure() throws Exception {
CountDownLatch commandLatch = new CountDownLatch(1);
CountDownLatch threadPoolLatch = new CountDownLatch(1);
Subscriber<HystrixCommandCompletion> commandSubscriber = getLatchedSubscriber(commandLatch);
readCommandStream.observe().take(1).subscribe(commandSubscriber);
Subscriber<HystrixCommandCompletion> threadPoolSubscriber = getLatchedSubscriber(threadPoolLatch);
readThreadPoolStream.observe().take(1).subscribe(threadPoolSubscriber);
ExecutionResult result = ExecutionResult.from(HystrixEventType.FAILURE).setExecutedInThread();
writeToStream.executionDone(result, commandKey, threadPoolKey);
assertTrue(commandLatch.await(1000, TimeUnit.MILLISECONDS));
assertTrue(threadPoolLatch.await(1000, TimeUnit.MILLISECONDS));
}
@Test
public void testSemaphoreIsolatedFailure() throws Exception {
CountDownLatch commandLatch = new CountDownLatch(1);
CountDownLatch threadPoolLatch = new CountDownLatch(1);
Subscriber<HystrixCommandCompletion> commandSubscriber = getLatchedSubscriber(commandLatch);
readCommandStream.observe().take(1).subscribe(commandSubscriber);
Subscriber<HystrixCommandCompletion> threadPoolSubscriber = getLatchedSubscriber(threadPoolLatch);
readThreadPoolStream.observe().take(1).subscribe(threadPoolSubscriber);
ExecutionResult result = ExecutionResult.from(HystrixEventType.FAILURE);
writeToStream.executionDone(result, commandKey, threadPoolKey);
assertTrue(commandLatch.await(1000, TimeUnit.MILLISECONDS));
assertFalse(threadPoolLatch.await(1000, TimeUnit.MILLISECONDS));
}
@Test
public void testThreadIsolatedTimeout() throws Exception {
CountDownLatch commandLatch = new CountDownLatch(1);
CountDownLatch threadPoolLatch = new CountDownLatch(1);
Subscriber<HystrixCommandCompletion> commandSubscriber = getLatchedSubscriber(commandLatch);
readCommandStream.observe().take(1).subscribe(commandSubscriber);
Subscriber<HystrixCommandCompletion> threadPoolSubscriber = getLatchedSubscriber(threadPoolLatch);
readThreadPoolStream.observe().take(1).subscribe(threadPoolSubscriber);
ExecutionResult result = ExecutionResult.from(HystrixEventType.TIMEOUT).setExecutedInThread();
writeToStream.executionDone(result, commandKey, threadPoolKey);
assertTrue(commandLatch.await(1000, TimeUnit.MILLISECONDS));
assertTrue(threadPoolLatch.await(1000, TimeUnit.MILLISECONDS));
}
@Test
public void testSemaphoreIsolatedTimeout() throws Exception {
CountDownLatch commandLatch = new CountDownLatch(1);
CountDownLatch threadPoolLatch = new CountDownLatch(1);
Subscriber<HystrixCommandCompletion> commandSubscriber = getLatchedSubscriber(commandLatch);
readCommandStream.observe().take(1).subscribe(commandSubscriber);
Subscriber<HystrixCommandCompletion> threadPoolSubscriber = getLatchedSubscriber(threadPoolLatch);
readThreadPoolStream.observe().take(1).subscribe(threadPoolSubscriber);
ExecutionResult result = ExecutionResult.from(HystrixEventType.TIMEOUT);
writeToStream.executionDone(result, commandKey, threadPoolKey);
assertTrue(commandLatch.await(1000, TimeUnit.MILLISECONDS));
assertFalse(threadPoolLatch.await(1000, TimeUnit.MILLISECONDS));
}
@Test
public void testThreadIsolatedBadRequest() throws Exception {
CountDownLatch commandLatch = new CountDownLatch(1);
CountDownLatch threadPoolLatch = new CountDownLatch(1);
Subscriber<HystrixCommandCompletion> commandSubscriber = getLatchedSubscriber(commandLatch);
readCommandStream.observe().take(1).subscribe(commandSubscriber);
Subscriber<HystrixCommandCompletion> threadPoolSubscriber = getLatchedSubscriber(threadPoolLatch);
readThreadPoolStream.observe().take(1).subscribe(threadPoolSubscriber);
ExecutionResult result = ExecutionResult.from(HystrixEventType.BAD_REQUEST).setExecutedInThread();
writeToStream.executionDone(result, commandKey, threadPoolKey);
assertTrue(commandLatch.await(1000, TimeUnit.MILLISECONDS));
assertTrue(threadPoolLatch.await(1000, TimeUnit.MILLISECONDS));
}
@Test
public void testSemaphoreIsolatedBadRequest() throws Exception {
CountDownLatch commandLatch = new CountDownLatch(1);
CountDownLatch threadPoolLatch = new CountDownLatch(1);
Subscriber<HystrixCommandCompletion> commandSubscriber = getLatchedSubscriber(commandLatch);
readCommandStream.observe().take(1).subscribe(commandSubscriber);
Subscriber<HystrixCommandCompletion> threadPoolSubscriber = getLatchedSubscriber(threadPoolLatch);
readThreadPoolStream.observe().take(1).subscribe(threadPoolSubscriber);
ExecutionResult result = ExecutionResult.from(HystrixEventType.BAD_REQUEST);
writeToStream.executionDone(result, commandKey, threadPoolKey);
assertTrue(commandLatch.await(1000, TimeUnit.MILLISECONDS));
assertFalse(threadPoolLatch.await(1000, TimeUnit.MILLISECONDS));
}
@Test
public void testThreadRejectedCommand() throws Exception {
CountDownLatch commandLatch = new CountDownLatch(1);
CountDownLatch threadPoolLatch = new CountDownLatch(1);
Subscriber<HystrixCommandCompletion> commandSubscriber = getLatchedSubscriber(commandLatch);
readCommandStream.observe().take(1).subscribe(commandSubscriber);
Subscriber<HystrixCommandCompletion> threadPoolSubscriber = getLatchedSubscriber(threadPoolLatch);
readThreadPoolStream.observe().take(1).subscribe(threadPoolSubscriber);
ExecutionResult result = ExecutionResult.from(HystrixEventType.THREAD_POOL_REJECTED);
writeToStream.executionDone(result, commandKey, threadPoolKey);
assertTrue(commandLatch.await(1000, TimeUnit.MILLISECONDS));
assertTrue(threadPoolLatch.await(1000, TimeUnit.MILLISECONDS));
}
@Test
public void testSemaphoreRejectedCommand() throws Exception {
CountDownLatch commandLatch = new CountDownLatch(1);
CountDownLatch threadPoolLatch = new CountDownLatch(1);
Subscriber<HystrixCommandCompletion> commandSubscriber = getLatchedSubscriber(commandLatch);
readCommandStream.observe().take(1).subscribe(commandSubscriber);
Subscriber<HystrixCommandCompletion> threadPoolSubscriber = getLatchedSubscriber(threadPoolLatch);
readThreadPoolStream.observe().take(1).subscribe(threadPoolSubscriber);
ExecutionResult result = ExecutionResult.from(HystrixEventType.SEMAPHORE_REJECTED);
writeToStream.executionDone(result, commandKey, threadPoolKey);
assertTrue(commandLatch.await(1000, TimeUnit.MILLISECONDS));
assertFalse(threadPoolLatch.await(1000, TimeUnit.MILLISECONDS));
}
@Test
public void testThreadIsolatedResponseFromCache() throws Exception {
CountDownLatch commandLatch = new CountDownLatch(1);
CountDownLatch threadPoolLatch = new CountDownLatch(1);
Subscriber<List<HystrixCommandCompletion>> commandListSubscriber = getLatchedSubscriber(commandLatch);
readCommandStream.observe().buffer(500, TimeUnit.MILLISECONDS).take(1)
.doOnNext(new Action1<List<HystrixCommandCompletion>>() {
@Override
public void call(List<HystrixCommandCompletion> hystrixCommandCompletions) {
System.out.println("LIST : " + hystrixCommandCompletions);
assertEquals(3, hystrixCommandCompletions.size());
}
})
.subscribe(commandListSubscriber);
Subscriber<HystrixCommandCompletion> threadPoolSubscriber = getLatchedSubscriber(threadPoolLatch);
readThreadPoolStream.observe().take(1).subscribe(threadPoolSubscriber);
ExecutionResult result = ExecutionResult.from(HystrixEventType.SUCCESS).setExecutedInThread();
ExecutionResult cache1 = ExecutionResult.from(HystrixEventType.RESPONSE_FROM_CACHE);
ExecutionResult cache2 = ExecutionResult.from(HystrixEventType.RESPONSE_FROM_CACHE);
writeToStream.executionDone(result, commandKey, threadPoolKey);
writeToStream.executionDone(cache1, commandKey, threadPoolKey);
writeToStream.executionDone(cache2, commandKey, threadPoolKey);
assertTrue(commandLatch.await(1000, TimeUnit.MILLISECONDS));
assertTrue(threadPoolLatch.await(1000, TimeUnit.MILLISECONDS));
}
@Test
public void testSemaphoreIsolatedResponseFromCache() throws Exception {
CountDownLatch commandLatch = new CountDownLatch(1);
CountDownLatch threadPoolLatch = new CountDownLatch(1);
Subscriber<List<HystrixCommandCompletion>> commandListSubscriber = getLatchedSubscriber(commandLatch);
readCommandStream.observe().buffer(500, TimeUnit.MILLISECONDS).take(1)
.doOnNext(new Action1<List<HystrixCommandCompletion>>() {
@Override
public void call(List<HystrixCommandCompletion> hystrixCommandCompletions) {
System.out.println("LIST : " + hystrixCommandCompletions);
assertEquals(3, hystrixCommandCompletions.size());
}
})
.subscribe(commandListSubscriber);
Subscriber<HystrixCommandCompletion> threadPoolSubscriber = getLatchedSubscriber(threadPoolLatch);
readThreadPoolStream.observe().take(1).subscribe(threadPoolSubscriber);
ExecutionResult result = ExecutionResult.from(HystrixEventType.SUCCESS);
ExecutionResult cache1 = ExecutionResult.from(HystrixEventType.RESPONSE_FROM_CACHE);
ExecutionResult cache2 = ExecutionResult.from(HystrixEventType.RESPONSE_FROM_CACHE);
writeToStream.executionDone(result, commandKey, threadPoolKey);
writeToStream.executionDone(cache1, commandKey, threadPoolKey);
writeToStream.executionDone(cache2, commandKey, threadPoolKey);
assertTrue(commandLatch.await(1000, TimeUnit.MILLISECONDS));
assertFalse(threadPoolLatch.await(1000, TimeUnit.MILLISECONDS));
}
@Test
public void testShortCircuit() throws Exception {
CountDownLatch commandLatch = new CountDownLatch(1);
CountDownLatch threadPoolLatch = new CountDownLatch(1);
Subscriber<HystrixCommandCompletion> commandSubscriber = getLatchedSubscriber(commandLatch);
readCommandStream.observe().take(1).subscribe(commandSubscriber);
Subscriber<HystrixCommandCompletion> threadPoolSubscriber = getLatchedSubscriber(threadPoolLatch);
readThreadPoolStream.observe().take(1).subscribe(threadPoolSubscriber);
ExecutionResult result = ExecutionResult.from(HystrixEventType.SHORT_CIRCUITED);
writeToStream.executionDone(result, commandKey, threadPoolKey);
assertTrue(commandLatch.await(1000, TimeUnit.MILLISECONDS));
assertFalse(threadPoolLatch.await(1000, TimeUnit.MILLISECONDS));
}
}
| 4,596 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/metric | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/metric/sample/HystrixUtilizationStreamTest.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.hystrix.metric.sample;
import com.hystrix.junit.HystrixRequestContextRule;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.metric.CommandStreamTest;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.schedulers.Schedulers;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class HystrixUtilizationStreamTest extends CommandStreamTest {
@Rule
public HystrixRequestContextRule ctx = new HystrixRequestContextRule();
HystrixUtilizationStream stream;
private final static HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("Util");
private final static HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey("Command");
@Before
public void init() {
stream = HystrixUtilizationStream.getNonSingletonInstanceOnlyUsedInUnitTests(10);
}
@Test
public void testStreamHasData() throws Exception {
final AtomicBoolean commandShowsUp = new AtomicBoolean(false);
final AtomicBoolean threadPoolShowsUp = new AtomicBoolean(false);
final CountDownLatch latch = new CountDownLatch(1);
final int NUM = 10;
for (int i = 0; i < 2; i++) {
HystrixCommand<Integer> cmd = Command.from(groupKey, commandKey, HystrixEventType.SUCCESS, 50);
cmd.observe();
}
stream.observe().take(NUM).subscribe(
new Subscriber<HystrixUtilization>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " OnCompleted");
latch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " OnError : " + e);
latch.countDown();
}
@Override
public void onNext(HystrixUtilization utilization) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Received data with : " + utilization.getCommandUtilizationMap().size() + " commands");
if (utilization.getCommandUtilizationMap().containsKey(commandKey)) {
commandShowsUp.set(true);
}
if (!utilization.getThreadPoolUtilizationMap().isEmpty()) {
threadPoolShowsUp.set(true);
}
}
});
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
assertTrue(commandShowsUp.get());
assertTrue(threadPoolShowsUp.get());
}
@Test
public void testTwoSubscribersOneUnsubscribes() throws Exception {
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final AtomicInteger payloads1 = new AtomicInteger(0);
final AtomicInteger payloads2 = new AtomicInteger(0);
Subscription s1 = stream
.observe()
.take(100)
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
latch1.countDown();
}
})
.subscribe(new Subscriber<HystrixUtilization>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 1 OnCompleted");
latch1.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 1 OnError : " + e);
latch1.countDown();
}
@Override
public void onNext(HystrixUtilization utilization) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 1 OnNext : " + utilization);
payloads1.incrementAndGet();
}
});
Subscription s2 = stream
.observe()
.take(100)
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
latch2.countDown();
}
})
.subscribe(new Subscriber<HystrixUtilization>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 2 OnCompleted");
latch2.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 2 OnError : " + e);
latch2.countDown();
}
@Override
public void onNext(HystrixUtilization utilization) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 2 OnNext : " + utilization);
payloads2.incrementAndGet();
}
});
//execute 1 command, then unsubscribe from first stream. then execute the rest
for (int i = 0; i < 50; i++) {
HystrixCommand<Integer> cmd = Command.from(groupKey, commandKey, HystrixEventType.SUCCESS, 50);
cmd.execute();
if (i == 1) {
s1.unsubscribe();
}
}
assertTrue(latch1.await(10000, TimeUnit.MILLISECONDS));
assertTrue(latch2.await(10000, TimeUnit.MILLISECONDS));
System.out.println("s1 got : " + payloads1.get() + ", s2 got : " + payloads2.get());
assertTrue("s1 got data", payloads1.get() > 0);
assertTrue("s2 got data", payloads2.get() > 0);
assertTrue("s1 got less data than s2", payloads2.get() > payloads1.get());
}
@Test
public void testTwoSubscribersBothUnsubscribe() throws Exception {
final CountDownLatch latch1 = new CountDownLatch(1);
final CountDownLatch latch2 = new CountDownLatch(1);
final AtomicInteger payloads1 = new AtomicInteger(0);
final AtomicInteger payloads2 = new AtomicInteger(0);
Subscription s1 = stream
.observe()
.take(100)
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
latch1.countDown();
}
})
.subscribe(new Subscriber<HystrixUtilization>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 1 OnCompleted");
latch1.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 1 OnError : " + e);
latch1.countDown();
}
@Override
public void onNext(HystrixUtilization utilization) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 1 OnNext : " + utilization);
payloads1.incrementAndGet();
}
});
Subscription s2 = stream
.observe()
.take(100)
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
latch2.countDown();
}
})
.subscribe(new Subscriber<HystrixUtilization>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 2 OnCompleted");
latch2.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 2 OnError : " + e);
latch2.countDown();
}
@Override
public void onNext(HystrixUtilization utilization) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 2 OnNext : " + utilization);
payloads2.incrementAndGet();
}
});
//execute 2 commands, then unsubscribe from both streams, then execute the rest
for (int i = 0; i < 10; i++) {
HystrixCommand<Integer> cmd = Command.from(groupKey, commandKey, HystrixEventType.SUCCESS, 50);
cmd.execute();
if (i == 2) {
s1.unsubscribe();
s2.unsubscribe();
}
}
assertFalse(stream.isSourceCurrentlySubscribed()); //both subscriptions have been cancelled - source should be too
assertTrue(latch1.await(10000, TimeUnit.MILLISECONDS));
assertTrue(latch2.await(10000, TimeUnit.MILLISECONDS));
System.out.println("s1 got : " + payloads1.get() + ", s2 got : " + payloads2.get());
assertTrue("s1 got data", payloads1.get() > 0);
assertTrue("s2 got data", payloads2.get() > 0);
}
@Test
public void testTwoSubscribersOneSlowOneFast() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicBoolean foundError = new AtomicBoolean(false);
Observable<HystrixUtilization> fast = stream
.observe()
.observeOn(Schedulers.newThread());
Observable<HystrixUtilization> slow = stream
.observe()
.observeOn(Schedulers.newThread())
.map(new Func1<HystrixUtilization, HystrixUtilization>() {
@Override
public HystrixUtilization call(HystrixUtilization util) {
try {
Thread.sleep(100);
return util;
} catch (InterruptedException ex) {
return util;
}
}
});
Observable<Boolean> checkZippedEqual = Observable.zip(fast, slow, new Func2<HystrixUtilization, HystrixUtilization, Boolean>() {
@Override
public Boolean call(HystrixUtilization payload, HystrixUtilization payload2) {
return payload == payload2;
}
});
Subscription s1 = checkZippedEqual
.take(10000)
.subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : OnCompleted");
latch.countDown();
}
@Override
public void onError(Throwable e) {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : OnError : " + e);
e.printStackTrace();
foundError.set(true);
latch.countDown();
}
@Override
public void onNext(Boolean b) {
//System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : OnNext : " + b);
}
});
for (int i = 0; i < 50; i++) {
HystrixCommand<Integer> cmd = Command.from(groupKey, commandKey, HystrixEventType.SUCCESS, 50);
cmd.execute();
}
latch.await(10000, TimeUnit.MILLISECONDS);
assertFalse(foundError.get());
}
}
| 4,597 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/metric | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/metric/consumer/RollingThreadPoolMaxConcurrencyStreamTest.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.hystrix.metric.consumer;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.HystrixRequestLog;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.metric.CommandStreamTest;
import com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import rx.Subscriber;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
public class RollingThreadPoolMaxConcurrencyStreamTest extends CommandStreamTest {
RollingThreadPoolMaxConcurrencyStream stream;
HystrixRequestContext context;
ExecutorService threadPool;
private static Subscriber<Integer> getSubscriber(final CountDownLatch latch) {
return new Subscriber<Integer>() {
@Override
public void onCompleted() {
latch.countDown();
}
@Override
public void onError(Throwable e) {
fail(e.getMessage());
}
@Override
public void onNext(Integer maxConcurrency) {
System.out.println("OnNext @ " + System.currentTimeMillis() + " : Max of " + maxConcurrency);
}
};
}
@Before
public void setUp() {
context = HystrixRequestContext.initializeContext();
threadPool = Executors.newFixedThreadPool(20);
}
@After
public void tearDown() {
context.shutdown();
stream.unsubscribe();
RollingCommandMaxConcurrencyStream.reset();
threadPool.shutdown();
}
@Test
public void testEmptyStreamProducesZeros() {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ThreadPool-Concurrency-A");
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-Concurrency-A");
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingConcurrency-A");
stream = RollingThreadPoolMaxConcurrencyStream.getInstance(threadPoolKey, 10, 100);
stream.startCachingStreamValuesIfUnstarted();
final CountDownLatch latch = new CountDownLatch(1);
stream.observe().take(10).subscribe(getSubscriber(latch));
//no writes
try {
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
} catch (InterruptedException ex) {
fail("Interrupted ex");
}
assertEquals(0, stream.getLatestRollingMax());
}
@Test
public void testStartsAndEndsInSameBucketProduceValue() throws InterruptedException {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ThreadPool-Concurrency-B");
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-Concurrency-B");
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingConcurrency-B");
stream = RollingThreadPoolMaxConcurrencyStream.getInstance(threadPoolKey, 10, 100);
stream.startCachingStreamValuesIfUnstarted();
final CountDownLatch latch = new CountDownLatch(1);
stream.observe().take(10).subscribe(getSubscriber(latch));
Command cmd1 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 50);
Command cmd2 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 40);
cmd1.observe();
Thread.sleep(1);
cmd2.observe();
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
assertEquals(2, stream.getLatestRollingMax());
}
@Test
public void testStartsAndEndsInSameBucketSemaphoreIsolated() throws InterruptedException {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ThreadPool-Concurrency-C");
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-Concurrency-C");
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingConcurrency-C");
stream = RollingThreadPoolMaxConcurrencyStream.getInstance(threadPoolKey, 10, 100);
stream.startCachingStreamValuesIfUnstarted();
final CountDownLatch latch = new CountDownLatch(1);
stream.observe().take(10).subscribe(getSubscriber(latch));
Command cmd1 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 10, HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE);
Command cmd2 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 14, HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE);
cmd1.observe();
Thread.sleep(1);
cmd2.observe();
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
//since commands run in semaphore isolation, they are not tracked by threadpool metrics
assertEquals(0, stream.getLatestRollingMax());
}
/***
* 3 Commands,
* Command 1 gets started in Bucket A and not completed until Bucket B
* Commands 2 and 3 both start and end in Bucket B, and there should be a max-concurrency of 3
*/
@Test
public void testOneCommandCarriesOverToNextBucket() throws InterruptedException {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ThreadPool-Concurrency-D");
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-Concurrency-D");
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingConcurrency-D");
stream = RollingThreadPoolMaxConcurrencyStream.getInstance(threadPoolKey, 10, 100);
stream.startCachingStreamValuesIfUnstarted();
final CountDownLatch latch = new CountDownLatch(1);
stream.observe().take(10).subscribe(getSubscriber(latch));
Command cmd1 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 560);
Command cmd2 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 50);
Command cmd3 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 75);
cmd1.observe();
Thread.sleep(150); //bucket roll
cmd2.observe();
Thread.sleep(1);
cmd3.observe();
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
assertEquals(3, stream.getLatestRollingMax());
}
/**
* BUCKETS
* A | B | C | D | E |
* 1: [-------------------------------]
* 2: [-------------------------------]
* 3: [--]
* 4: [--]
*
* Max concurrency should be 3
*/
@Test
public void testMultipleCommandsCarryOverMultipleBuckets() throws InterruptedException {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ThreadPool-Concurrency-E");
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-Concurrency-E");
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingConcurrency-E");
stream = RollingThreadPoolMaxConcurrencyStream.getInstance(threadPoolKey, 10, 100);
stream.startCachingStreamValuesIfUnstarted();
final CountDownLatch latch = new CountDownLatch(1);
stream.observe().take(10).subscribe(getSubscriber(latch));
Command cmd1 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 300);
Command cmd2 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 300);
Command cmd3 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 10);
Command cmd4 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 10);
cmd1.observe();
Thread.sleep(100); //bucket roll
cmd2.observe();
Thread.sleep(100);
cmd3.observe();
Thread.sleep(100);
cmd4.observe();
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
assertEquals(3, stream.getLatestRollingMax());
}
/**
* BUCKETS
* A | B | C | D | E |
* 1: [-------------------------------] ThreadPool x
* 2: [-------------------------------] y
* 3: [--] x
* 4: [--] x
*
* Same input data as above test, just that command 2 runs in a separate threadpool, so concurrency should not get tracked
* Max concurrency should be 2 for x
*/
@Test
public void testMultipleCommandsCarryOverMultipleBucketsForMultipleThreadPools() throws InterruptedException {
HystrixCommandGroupKey groupKeyX = HystrixCommandGroupKey.Factory.asKey("ThreadPool-Concurrency-X");
HystrixCommandGroupKey groupKeyY = HystrixCommandGroupKey.Factory.asKey("ThreadPool-Concurrency-Y");
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-Concurrency-X");
HystrixCommandKey keyX = HystrixCommandKey.Factory.asKey("RollingConcurrency-X");
HystrixCommandKey keyY = HystrixCommandKey.Factory.asKey("RollingConcurrency-Y");
stream = RollingThreadPoolMaxConcurrencyStream.getInstance(threadPoolKey, 10, 100);
stream.startCachingStreamValuesIfUnstarted();
final CountDownLatch latch = new CountDownLatch(1);
stream.observe().take(10).subscribe(getSubscriber(latch));
Command cmd1 = Command.from(groupKeyX, keyX, HystrixEventType.SUCCESS, 300);
Command cmd2 = Command.from(groupKeyY, keyY, HystrixEventType.SUCCESS, 300);
Command cmd3 = Command.from(groupKeyX, keyY, HystrixEventType.SUCCESS, 10);
Command cmd4 = Command.from(groupKeyX, keyY, HystrixEventType.SUCCESS, 10);
cmd1.observe();
Thread.sleep(100); //bucket roll
cmd2.observe();
Thread.sleep(100);
cmd3.observe();
Thread.sleep(100);
cmd4.observe();
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
assertEquals(2, stream.getLatestRollingMax());
}
/**
* BUCKETS
* A | B | C | D | E |
* 1: [-------------------------------]
* 2: [-------------------------------]
* 3: [--]
* 4: [--]
*
* Max concurrency should be 3, but by waiting for 30 bucket rolls, final max concurrency should be 0
*/
@Test
public void testMultipleCommandsCarryOverMultipleBucketsAndThenAgeOut() throws InterruptedException {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ThreadPool-Concurrency-F");
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-Concurrency-F");
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingConcurrency-F");
stream = RollingThreadPoolMaxConcurrencyStream.getInstance(threadPoolKey, 10, 100);
stream.startCachingStreamValuesIfUnstarted();
final CountDownLatch latch = new CountDownLatch(1);
stream.observe().take(30).subscribe(getSubscriber(latch));
Command cmd1 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 300);
Command cmd2 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 300);
Command cmd3 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 10);
Command cmd4 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 10);
cmd1.observe();
Thread.sleep(100); //bucket roll
cmd2.observe();
Thread.sleep(100);
cmd3.observe();
Thread.sleep(100);
cmd4.observe();
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
assertEquals(0, stream.getLatestRollingMax());
}
@Test
public void testConcurrencyStreamProperlyFiltersOutResponseFromCache() throws InterruptedException {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ThreadPool-Concurrency-G");
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-Concurrency-G");
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingConcurrency-G");
stream = RollingThreadPoolMaxConcurrencyStream.getInstance(threadPoolKey, 10, 100);
stream.startCachingStreamValuesIfUnstarted();
final CountDownLatch latch = new CountDownLatch(1);
stream.observe().take(10).subscribe(getSubscriber(latch));
Command cmd1 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 40);
Command cmd2 = Command.from(groupKey, key, HystrixEventType.RESPONSE_FROM_CACHE);
Command cmd3 = Command.from(groupKey, key, HystrixEventType.RESPONSE_FROM_CACHE);
Command cmd4 = Command.from(groupKey, key, HystrixEventType.RESPONSE_FROM_CACHE);
cmd1.observe();
Thread.sleep(5);
cmd2.observe();
cmd3.observe();
cmd4.observe();
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertTrue(cmd2.isResponseFromCache());
assertTrue(cmd3.isResponseFromCache());
assertTrue(cmd4.isResponseFromCache());
assertEquals(1, stream.getLatestRollingMax());
}
@Test
public void testConcurrencyStreamProperlyFiltersOutShortCircuits() throws InterruptedException {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ThreadPool-Concurrency-H");
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-Concurrency-H");
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingConcurrency-H");
stream = RollingThreadPoolMaxConcurrencyStream.getInstance(threadPoolKey, 10, 100);
stream.startCachingStreamValuesIfUnstarted();
final CountDownLatch latch = new CountDownLatch(1);
stream.observe().take(10).subscribe(getSubscriber(latch));
//after 3 failures, next command should short-circuit.
//to prove short-circuited commands don't contribute to concurrency, execute 3 FAILURES in the first bucket sequentially
//then when circuit is open, execute 20 concurrent commands. they should all get short-circuited, and max concurrency should be 1
Command failure1 = Command.from(groupKey, key, HystrixEventType.FAILURE);
Command failure2 = Command.from(groupKey, key, HystrixEventType.FAILURE);
Command failure3 = Command.from(groupKey, key, HystrixEventType.FAILURE);
List<Command> shortCircuited = new ArrayList<Command>();
for (int i = 0; i < 20; i++) {
shortCircuited.add(Command.from(groupKey, key, HystrixEventType.SUCCESS, 100));
}
failure1.execute();
failure2.execute();
failure3.execute();
Thread.sleep(150);
for (Command cmd: shortCircuited) {
cmd.observe();
}
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
for (Command cmd: shortCircuited) {
assertTrue(cmd.isResponseShortCircuited());
}
assertEquals(1, stream.getLatestRollingMax());
}
@Test
public void testConcurrencyStreamProperlyFiltersOutSemaphoreRejections() throws InterruptedException {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ThreadPool-Concurrency-I");
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-Concurrency-I");
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingConcurrency-I");
stream = RollingThreadPoolMaxConcurrencyStream.getInstance(threadPoolKey, 10, 100);
stream.startCachingStreamValuesIfUnstarted();
final CountDownLatch latch = new CountDownLatch(1);
stream.observe().take(10).subscribe(getSubscriber(latch));
//10 commands executed concurrently on different caller threads should saturate semaphore
//once these are in-flight, execute 10 more concurrently on new caller threads.
//since these are semaphore-rejected, the max concurrency should be 10
List<Command> saturators = new ArrayList<Command>();
for (int i = 0; i < 10; i++) {
saturators.add(Command.from(groupKey, key, HystrixEventType.SUCCESS, 400, HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE));
}
final List<Command> rejected = new ArrayList<Command>();
for (int i = 0; i < 10; i++) {
rejected.add(Command.from(groupKey, key, HystrixEventType.SUCCESS, 100, HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE));
}
for (final Command saturatingCmd: saturators) {
threadPool.submit(new HystrixContextRunnable(new Runnable() {
@Override
public void run() {
saturatingCmd.observe();
}
}));
}
Thread.sleep(30);
for (final Command rejectedCmd: rejected) {
threadPool.submit(new HystrixContextRunnable(new Runnable() {
@Override
public void run() {
rejectedCmd.observe();
}
}));
}
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
for (Command rejectedCmd: rejected) {
assertTrue(rejectedCmd.isResponseSemaphoreRejected() || rejectedCmd.isResponseShortCircuited());
}
//should be 0 since all are executed in a semaphore
assertEquals(0, stream.getLatestRollingMax());
}
@Test
public void testConcurrencyStreamProperlyFiltersOutThreadPoolRejections() throws InterruptedException {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ThreadPool-Concurrency-J");
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-Concurrency-J");
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingConcurrency-J");
stream = RollingThreadPoolMaxConcurrencyStream.getInstance(threadPoolKey, 10, 100);
stream.startCachingStreamValuesIfUnstarted();
final CountDownLatch latch = new CountDownLatch(1);
stream.observe().take(10).subscribe(getSubscriber(latch));
//10 commands executed concurrently should saturate the Hystrix threadpool
//once these are in-flight, execute 10 more concurrently
//since these are threadpool-rejected, the max concurrency should be 10
List<Command> saturators = new ArrayList<Command>();
for (int i = 0; i < 10; i++) {
saturators.add(Command.from(groupKey, key, HystrixEventType.SUCCESS, 400));
}
final List<Command> rejected = new ArrayList<Command>();
for (int i = 0; i < 10; i++) {
rejected.add(Command.from(groupKey, key, HystrixEventType.SUCCESS, 100));
}
for (final Command saturatingCmd: saturators) {
saturatingCmd.observe();
}
Thread.sleep(30);
for (final Command rejectedCmd: rejected) {
rejectedCmd.observe();
}
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
for (Command rejectedCmd: rejected) {
assertTrue(rejectedCmd.isResponseThreadPoolRejected());
}
//this should not count rejected commands
assertEquals(10, stream.getLatestRollingMax());
}
}
| 4,598 |
0 | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/metric | Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/metric/consumer/CumulativeThreadPoolEventCounterStreamTest.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.hystrix.metric.consumer;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixEventType;
import com.netflix.hystrix.HystrixRequestLog;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolMetrics;
import com.netflix.hystrix.metric.CommandStreamTest;
import com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import rx.Subscriber;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
public class CumulativeThreadPoolEventCounterStreamTest extends CommandStreamTest {
HystrixRequestContext context;
CumulativeThreadPoolEventCounterStream stream;
private static Subscriber<long[]> getSubscriber(final CountDownLatch latch) {
return new Subscriber<long[]>() {
@Override
public void onCompleted() {
latch.countDown();
}
@Override
public void onError(Throwable e) {
fail(e.getMessage());
}
@Override
public void onNext(long[] eventCounts) {
System.out.println("OnNext @ " + System.currentTimeMillis() + " : " + eventCounts[0] + " : " + eventCounts[1]);
}
};
}
@Before
public void setUp() {
context = HystrixRequestContext.initializeContext();
}
@After
public void tearDown() {
context.shutdown();
stream.unsubscribe();
RollingCommandEventCounterStream.reset();
}
@Test
public void testEmptyStreamProducesZeros() {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("Cumulative-ThreadPool-A");
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("Cumulative-ThreadPool-A");
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("Cumulative-Counter-A");
stream = CumulativeThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 100);
stream.startCachingStreamValuesIfUnstarted();
final CountDownLatch latch = new CountDownLatch(1);
stream.observe().take(10).subscribe(getSubscriber(latch));
//no writes
try {
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
} catch (InterruptedException ex) {
fail("Interrupted ex");
}
assertEquals(2, stream.getLatest().length);
assertEquals(0, stream.getLatestCount(HystrixEventType.ThreadPool.EXECUTED));
assertEquals(0, stream.getLatestCount(HystrixEventType.ThreadPool.REJECTED));
}
@Test
public void testSingleSuccess() {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("Cumulative-ThreadPool-B");
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("Cumulative-ThreadPool-B");
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("Cumulative-Counter-B");
stream = CumulativeThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 100);
stream.startCachingStreamValuesIfUnstarted();
final CountDownLatch latch = new CountDownLatch(1);
stream.observe().take(10).subscribe(getSubscriber(latch));
CommandStreamTest.Command cmd = CommandStreamTest.Command.from(groupKey, key, HystrixEventType.SUCCESS, 20);
cmd.observe();
try {
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
} catch (InterruptedException ex) {
fail("Interrupted ex");
}
assertEquals(2, stream.getLatest().length);
assertEquals(1, stream.getLatestCount(HystrixEventType.ThreadPool.EXECUTED));
assertEquals(0, stream.getLatestCount(HystrixEventType.ThreadPool.REJECTED));
}
@Test
public void testSingleFailure() {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("Cumulative-ThreadPool-C");
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("Cumulative-ThreadPool-C");
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("Cumulative-Counter-C");
stream = CumulativeThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 100);
stream.startCachingStreamValuesIfUnstarted();
final CountDownLatch latch = new CountDownLatch(1);
stream.observe().take(10).subscribe(getSubscriber(latch));
CommandStreamTest.Command cmd = CommandStreamTest.Command.from(groupKey, key, HystrixEventType.FAILURE, 20);
cmd.observe();
try {
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
} catch (InterruptedException ex) {
fail("Interrupted ex");
}
assertEquals(2, stream.getLatest().length);
assertEquals(1, stream.getLatestCount(HystrixEventType.ThreadPool.EXECUTED));
assertEquals(0, stream.getLatestCount(HystrixEventType.ThreadPool.REJECTED));
}
@Test
public void testSingleTimeout() {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("Cumulative-ThreadPool-D");
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("Cumulative-ThreadPool-D");
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("Cumulative-Counter-D");
stream = CumulativeThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 100);
stream.startCachingStreamValuesIfUnstarted();
final CountDownLatch latch = new CountDownLatch(1);
stream.observe().take(10).subscribe(getSubscriber(latch));
CommandStreamTest.Command cmd = CommandStreamTest.Command.from(groupKey, key, HystrixEventType.TIMEOUT);
cmd.observe();
try {
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
} catch (InterruptedException ex) {
fail("Interrupted ex");
}
assertEquals(2, stream.getLatest().length);
assertEquals(1, stream.getLatestCount(HystrixEventType.ThreadPool.EXECUTED));
assertEquals(0, stream.getLatestCount(HystrixEventType.ThreadPool.REJECTED));
}
@Test
public void testSingleBadRequest() {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("Cumulative-ThreadPool-E");
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("Cumulative-ThreadPool-E");
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("Cumulative-Counter-E");
stream = CumulativeThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 100);
stream.startCachingStreamValuesIfUnstarted();
final CountDownLatch latch = new CountDownLatch(1);
stream.observe().take(10).subscribe(getSubscriber(latch));
CommandStreamTest.Command cmd = CommandStreamTest.Command.from(groupKey, key, HystrixEventType.BAD_REQUEST);
cmd.observe();
try {
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
} catch (InterruptedException ex) {
fail("Interrupted ex");
}
assertEquals(2, stream.getLatest().length);
assertEquals(1, stream.getLatestCount(HystrixEventType.ThreadPool.EXECUTED));
assertEquals(0, stream.getLatestCount(HystrixEventType.ThreadPool.REJECTED));
}
@Test
public void testRequestFromCache() {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("Cumulative-ThreadPool-F");
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("Cumulative-ThreadPool-F");
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("Cumulative-Counter-F");
stream = CumulativeThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 100);
stream.startCachingStreamValuesIfUnstarted();
final CountDownLatch latch = new CountDownLatch(1);
stream.observe().take(10).subscribe(getSubscriber(latch));
CommandStreamTest.Command cmd1 = CommandStreamTest.Command.from(groupKey, key, HystrixEventType.SUCCESS, 20);
CommandStreamTest.Command cmd2 = CommandStreamTest.Command.from(groupKey, key, HystrixEventType.RESPONSE_FROM_CACHE);
CommandStreamTest.Command cmd3 = CommandStreamTest.Command.from(groupKey, key, HystrixEventType.RESPONSE_FROM_CACHE);
cmd1.observe();
cmd2.observe();
cmd3.observe();
try {
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
} catch (InterruptedException ex) {
fail("Interrupted ex");
}
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
//RESPONSE_FROM_CACHE should not show up at all in thread pool counters - just the success
assertEquals(2, stream.getLatest().length);
assertEquals(1, stream.getLatestCount(HystrixEventType.ThreadPool.EXECUTED));
assertEquals(0, stream.getLatestCount(HystrixEventType.ThreadPool.REJECTED));
}
@Test
public void testShortCircuited() {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("Cumulative-ThreadPool-G");
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("Cumulative-ThreadPool-G");
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("Cumulative-Counter-G");
stream = CumulativeThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 100);
stream.startCachingStreamValuesIfUnstarted();
final CountDownLatch latch = new CountDownLatch(1);
stream.observe().take(10).subscribe(getSubscriber(latch));
//3 failures in a row will trip circuit. let bucket roll once then submit 2 requests.
//should see 3 FAILUREs and 2 SHORT_CIRCUITs and each should see a FALLBACK_SUCCESS
CommandStreamTest.Command failure1 = CommandStreamTest.Command.from(groupKey, key, HystrixEventType.FAILURE, 20);
CommandStreamTest.Command failure2 = CommandStreamTest.Command.from(groupKey, key, HystrixEventType.FAILURE, 20);
CommandStreamTest.Command failure3 = CommandStreamTest.Command.from(groupKey, key, HystrixEventType.FAILURE, 20);
CommandStreamTest.Command shortCircuit1 = CommandStreamTest.Command.from(groupKey, key, HystrixEventType.SUCCESS);
CommandStreamTest.Command shortCircuit2 = CommandStreamTest.Command.from(groupKey, key, HystrixEventType.SUCCESS);
failure1.observe();
failure2.observe();
failure3.observe();
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
fail(ie.getMessage());
}
shortCircuit1.observe();
shortCircuit2.observe();
try {
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
} catch (InterruptedException ex) {
fail("Interrupted ex");
}
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertTrue(shortCircuit1.isResponseShortCircuited());
assertTrue(shortCircuit2.isResponseShortCircuited());
//only the FAILUREs should show up in thread pool counters
assertEquals(2, stream.getLatest().length);
assertEquals(3, stream.getLatestCount(HystrixEventType.ThreadPool.EXECUTED));
assertEquals(0, stream.getLatestCount(HystrixEventType.ThreadPool.REJECTED));
}
@Test
public void testSemaphoreRejected() {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("Cumulative-ThreadPool-H");
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("Cumulative-ThreadPool-H");
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("Cumulative-Counter-H");
stream = CumulativeThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 100);
stream.startCachingStreamValuesIfUnstarted();
final CountDownLatch latch = new CountDownLatch(1);
stream.observe().take(10).subscribe(getSubscriber(latch));
//10 commands will saturate semaphore when called from different threads.
//submit 2 more requests and they should be SEMAPHORE_REJECTED
//should see 10 SUCCESSes, 2 SEMAPHORE_REJECTED and 2 FALLBACK_SUCCESSes
List<Command> saturators = new ArrayList<Command>();
for (int i = 0; i < 10; i++) {
saturators.add(CommandStreamTest.Command.from(groupKey, key, HystrixEventType.SUCCESS, 300, HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE));
}
CommandStreamTest.Command rejected1 = CommandStreamTest.Command.from(groupKey, key, HystrixEventType.SUCCESS, 0, HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE);
CommandStreamTest.Command rejected2 = CommandStreamTest.Command.from(groupKey, key, HystrixEventType.SUCCESS, 0, HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE);
for (final CommandStreamTest.Command saturator : saturators) {
new Thread(new HystrixContextRunnable(new Runnable() {
@Override
public void run() {
saturator.observe();
}
})).start();
}
try {
Thread.sleep(10);
} catch (InterruptedException ie) {
fail(ie.getMessage());
}
rejected1.observe();
rejected2.observe();
try {
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
} catch (InterruptedException ex) {
fail("Interrupted ex");
}
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertTrue(rejected1.isResponseSemaphoreRejected());
assertTrue(rejected2.isResponseSemaphoreRejected());
//none of these got executed on a thread-pool, so thread pool metrics should be 0
assertEquals(2, stream.getLatest().length);
assertEquals(0, stream.getLatestCount(HystrixEventType.ThreadPool.EXECUTED));
assertEquals(0, stream.getLatestCount(HystrixEventType.ThreadPool.REJECTED));
}
@Test
public void testThreadPoolRejected() {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("Cumulative-ThreadPool-I");
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("Cumulative-ThreadPool-I");
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("Cumulative-Counter-I");
stream = CumulativeThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 100);
stream.startCachingStreamValuesIfUnstarted();
final CountDownLatch latch = new CountDownLatch(1);
stream.observe().take(10).subscribe(getSubscriber(latch));
//10 commands will saturate threadpools when called concurrently.
//submit 2 more requests and they should be THREADPOOL_REJECTED
//should see 10 SUCCESSes, 2 THREADPOOL_REJECTED and 2 FALLBACK_SUCCESSes
List<CommandStreamTest.Command> saturators = new ArrayList<CommandStreamTest.Command>();
for (int i = 0; i < 10; i++) {
saturators.add(CommandStreamTest.Command.from(groupKey, key, HystrixEventType.SUCCESS, 700));
}
CommandStreamTest.Command rejected1 = CommandStreamTest.Command.from(groupKey, key, HystrixEventType.SUCCESS, 0);
CommandStreamTest.Command rejected2 = CommandStreamTest.Command.from(groupKey, key, HystrixEventType.SUCCESS, 0);
for (final CommandStreamTest.Command saturator : saturators) {
saturator.observe();
}
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
fail(ie.getMessage());
}
rejected1.observe();
rejected2.observe();
try {
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
} catch (InterruptedException ex) {
fail("Interrupted ex");
}
System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
assertTrue(rejected1.isResponseThreadPoolRejected());
assertTrue(rejected2.isResponseThreadPoolRejected());
//all 12 commands got submitted to thread pool, 10 accepted, 2 rejected is expected
assertEquals(2, stream.getLatest().length);
assertEquals(10, stream.getLatestCount(HystrixEventType.ThreadPool.EXECUTED));
assertEquals(2, stream.getLatestCount(HystrixEventType.ThreadPool.REJECTED));
}
@Test
public void testFallbackFailure() {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("Cumulative-ThreadPool-J");
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("Cumulative-ThreadPool-J");
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("Cumulative-Counter-J");
stream = CumulativeThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 100);
stream.startCachingStreamValuesIfUnstarted();
final CountDownLatch latch = new CountDownLatch(1);
stream.observe().take(10).subscribe(getSubscriber(latch));
CommandStreamTest.Command cmd = CommandStreamTest.Command.from(groupKey, key, HystrixEventType.FAILURE, 20, HystrixEventType.FALLBACK_FAILURE);
cmd.observe();
try {
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
} catch (InterruptedException ex) {
fail("Interrupted ex");
}
assertEquals(2, stream.getLatest().length);
assertEquals(1, stream.getLatestCount(HystrixEventType.ThreadPool.EXECUTED));
assertEquals(0, stream.getLatestCount(HystrixEventType.ThreadPool.REJECTED));
}
@Test
public void testFallbackMissing() {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("Cumulative-ThreadPool-K");
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("Cumulative-ThreadPool-K");
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("Cumulative-Counter-K");
stream = CumulativeThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 100);
stream.startCachingStreamValuesIfUnstarted();
final CountDownLatch latch = new CountDownLatch(1);
stream.observe().take(10).subscribe(getSubscriber(latch));
CommandStreamTest.Command cmd = CommandStreamTest.Command.from(groupKey, key, HystrixEventType.FAILURE, 20, HystrixEventType.FALLBACK_MISSING);
cmd.observe();
try {
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
} catch (InterruptedException ex) {
fail("Interrupted ex");
}
assertEquals(2, stream.getLatest().length);
assertEquals(1, stream.getLatestCount(HystrixEventType.ThreadPool.EXECUTED));
assertEquals(0, stream.getLatestCount(HystrixEventType.ThreadPool.REJECTED));
}
@Test
public void testFallbackRejection() {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("Cumulative-ThreadPool-L");
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("Cumulative-ThreadPool-L");
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("Cumulative-Counter-L");
stream = CumulativeThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 100);
stream.startCachingStreamValuesIfUnstarted();
final CountDownLatch latch = new CountDownLatch(1);
stream.observe().take(10).subscribe(getSubscriber(latch));
//fallback semaphore size is 5. So let 5 commands saturate that semaphore, then
//let 2 more commands go to fallback. they should get rejected by the fallback-semaphore
List<CommandStreamTest.Command> fallbackSaturators = new ArrayList<CommandStreamTest.Command>();
for (int i = 0; i < 5; i++) {
fallbackSaturators.add(CommandStreamTest.Command.from(groupKey, key, HystrixEventType.FAILURE, 20, HystrixEventType.FALLBACK_SUCCESS, 400));
}
CommandStreamTest.Command rejection1 = CommandStreamTest.Command.from(groupKey, key, HystrixEventType.FAILURE, 20, HystrixEventType.FALLBACK_SUCCESS, 0);
CommandStreamTest.Command rejection2 = CommandStreamTest.Command.from(groupKey, key, HystrixEventType.FAILURE, 20, HystrixEventType.FALLBACK_SUCCESS, 0);
for (CommandStreamTest.Command saturator: fallbackSaturators) {
saturator.observe();
}
try {
Thread.sleep(70);
} catch (InterruptedException ex) {
fail(ex.getMessage());
}
rejection1.observe();
rejection2.observe();
try {
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
} catch (InterruptedException ex) {
fail("Interrupted ex");
}
//all 7 commands executed on-thread, so should be executed according to thread-pool metrics
assertEquals(2, stream.getLatest().length);
assertEquals(7, stream.getLatestCount(HystrixEventType.ThreadPool.EXECUTED));
assertEquals(0, stream.getLatestCount(HystrixEventType.ThreadPool.REJECTED));
}
//in a rolling window, take(30) would age out all counters. in the cumulative count, we expect them to remain non-zero forever
@Test
public void testMultipleEventsOverTimeGetStoredAndDoNotAgeOut() {
HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("Cumulative-ThreadPool-M");
HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("Cumulative-ThreadPool-M");
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("Cumulative-Counter-M");
stream = CumulativeThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 100);
stream.startCachingStreamValuesIfUnstarted();
final CountDownLatch latch = new CountDownLatch(1);
stream.observe().take(30).subscribe(getSubscriber(latch));
CommandStreamTest.Command cmd1 = CommandStreamTest.Command.from(groupKey, key, HystrixEventType.SUCCESS, 20);
CommandStreamTest.Command cmd2 = CommandStreamTest.Command.from(groupKey, key, HystrixEventType.FAILURE, 10);
cmd1.observe();
cmd2.observe();
try {
assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
} catch (InterruptedException ex) {
fail("Interrupted ex");
}
//all commands should have aged out
assertEquals(2, stream.getLatest().length);
assertEquals(2, stream.getLatestCount(HystrixEventType.ThreadPool.EXECUTED));
assertEquals(0, stream.getLatestCount(HystrixEventType.ThreadPool.REJECTED));
}
}
| 4,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.