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-core/src/test/java/com/netflix/hystrix/metric
Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/metric/consumer/RollingCollapserEventCounterStreamTest.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.HystrixCollapserKey; import com.netflix.hystrix.HystrixCollapserMetrics; import com.netflix.hystrix.HystrixEventType; import com.netflix.hystrix.HystrixRequestLog; import com.netflix.hystrix.metric.CommandStreamTest; 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.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.junit.Assert.*; public class RollingCollapserEventCounterStreamTest extends CommandStreamTest { HystrixRequestContext context; RollingCollapserEventCounterStream 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() + " : " + collapserEventsToStr(eventCounts)); } }; } @Before public void setUp() { context = HystrixRequestContext.initializeContext(); } @After public void tearDown() { context.shutdown(); stream.unsubscribe(); RollingCollapserEventCounterStream.reset(); } protected static String collapserEventsToStr(long[] eventCounts) { StringBuilder sb = new StringBuilder(); sb.append("["); for (HystrixEventType.Collapser eventType : HystrixEventType.Collapser.values()) { if (eventCounts[eventType.ordinal()] > 0) { sb.append(eventType.name()).append("->").append(eventCounts[eventType.ordinal()]).append(", "); } } sb.append("]"); return sb.toString(); } @Test public void testEmptyStreamProducesZeros() { HystrixCollapserKey key = HystrixCollapserKey.Factory.asKey("RollingCollapser-A"); stream = RollingCollapserEventCounterStream.getInstance(key, 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"); } System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertEquals(HystrixEventType.Collapser.values().length, stream.getLatest().length); assertEquals(0, stream.getLatest(HystrixEventType.Collapser.ADDED_TO_BATCH)); assertEquals(0, stream.getLatest(HystrixEventType.Collapser.BATCH_EXECUTED)); assertEquals(0, stream.getLatest(HystrixEventType.Collapser.RESPONSE_FROM_CACHE)); } @Test public void testCollapsed() { HystrixCollapserKey key = HystrixCollapserKey.Factory.asKey("RollingCollapser-B"); stream = RollingCollapserEventCounterStream.getInstance(key, 10, 100); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(10).subscribe(getSubscriber(latch)); for (int i = 0; i < 3; i++) { CommandStreamTest.Collapser.from(key, i).observe(); } try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertEquals(HystrixEventType.Collapser.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.Collapser.values().length]; expected[HystrixEventType.Collapser.BATCH_EXECUTED.ordinal()] = 1; expected[HystrixEventType.Collapser.ADDED_TO_BATCH.ordinal()] = 3; System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertArrayEquals(expected, stream.getLatest()); } @Test public void testCollapsedAndResponseFromCache() { HystrixCollapserKey key = HystrixCollapserKey.Factory.asKey("RollingCollapser-C"); stream = RollingCollapserEventCounterStream.getInstance(key, 10, 100); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(10).subscribe(getSubscriber(latch)); for (int i = 0; i < 3; i++) { CommandStreamTest.Collapser.from(key, i).observe(); CommandStreamTest.Collapser.from(key, i).observe(); //same arg - should get a response from cache CommandStreamTest.Collapser.from(key, i).observe(); //same arg - should get a response from cache } try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertEquals(HystrixEventType.Collapser.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.Collapser.values().length]; expected[HystrixEventType.Collapser.BATCH_EXECUTED.ordinal()] = 1; expected[HystrixEventType.Collapser.ADDED_TO_BATCH.ordinal()] = 3; expected[HystrixEventType.Collapser.RESPONSE_FROM_CACHE.ordinal()] = 6; System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertArrayEquals(expected, stream.getLatest()); } //by doing a take(30), we expect all values to return to 0 as they age out of rolling window @Test public void testCollapsedAndResponseFromCacheAgeOutOfRollingWindow() { HystrixCollapserKey key = HystrixCollapserKey.Factory.asKey("RollingCollapser-D"); stream = RollingCollapserEventCounterStream.getInstance(key, 10, 100); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(30).subscribe(getSubscriber(latch)); for (int i = 0; i < 3; i++) { CommandStreamTest.Collapser.from(key, i).observe(); CommandStreamTest.Collapser.from(key, i).observe(); //same arg - should get a response from cache CommandStreamTest.Collapser.from(key, i).observe(); //same arg - should get a response from cache } try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertEquals(HystrixEventType.Collapser.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.Collapser.values().length]; expected[HystrixEventType.Collapser.BATCH_EXECUTED.ordinal()] = 0; expected[HystrixEventType.Collapser.ADDED_TO_BATCH.ordinal()] = 0; expected[HystrixEventType.Collapser.RESPONSE_FROM_CACHE.ordinal()] = 0; System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertArrayEquals(expected, stream.getLatest()); } }
4,600
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/RollingCommandMaxConcurrencyStreamTest.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.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 RollingCommandMaxConcurrencyStreamTest extends CommandStreamTest { RollingCommandMaxConcurrencyStream stream; HystrixRequestContext context; ExecutorService threadPool; static HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("Command-Concurrency"); 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() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Concurrency-A"); stream = RollingCommandMaxConcurrencyStream.getInstance(key, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).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 { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Concurrency-B"); stream = RollingCommandMaxConcurrencyStream.getInstance(key, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).subscribe(getSubscriber(latch)); Command cmd1 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 100); Command cmd2 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 100); cmd1.observe(); Thread.sleep(1); cmd2.observe(); assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); assertEquals(2, 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 { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Concurrency-C"); stream = RollingCommandMaxConcurrencyStream.getInstance(key, 10, 100); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).subscribe(getSubscriber(latch)); Command cmd1 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 160); Command cmd2 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 10); Command cmd3 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 15); cmd1.observe(); Thread.sleep(100); //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 { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Concurrency-D"); stream = RollingCommandMaxConcurrencyStream.getInstance(key, 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: [-------------------------------] * 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 { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Concurrency-E"); stream = RollingCommandMaxConcurrencyStream.getInstance(key, 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 { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Concurrency-F"); stream = RollingCommandMaxConcurrencyStream.getInstance(key, 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()); assertEquals(1, stream.getLatestRollingMax()); } @Test public void testConcurrencyStreamProperlyFiltersOutShortCircuits() throws InterruptedException { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Concurrency-G"); stream = RollingCommandMaxConcurrencyStream.getInstance(key, 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()); assertEquals(1, stream.getLatestRollingMax()); } @Test public void testConcurrencyStreamProperlyFiltersOutSemaphoreRejections() throws InterruptedException { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Concurrency-H"); stream = RollingCommandMaxConcurrencyStream.getInstance(key, 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()); assertEquals(10, stream.getLatestRollingMax()); } @Test public void testConcurrencyStreamProperlyFiltersOutThreadPoolRejections() throws InterruptedException { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Concurrency-I"); stream = RollingCommandMaxConcurrencyStream.getInstance(key, 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()); assertEquals(10, stream.getLatestRollingMax()); } }
4,601
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/RollingCollapserBatchSizeDistributionStreamTest.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.HystrixCollapserKey; import com.netflix.hystrix.metric.CachedValuesHistogram; import com.netflix.hystrix.metric.CommandStreamTest; 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.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class RollingCollapserBatchSizeDistributionStreamTest extends CommandStreamTest { RollingCollapserBatchSizeDistributionStream stream; HystrixRequestContext context; @Before public void setUp() { context = HystrixRequestContext.initializeContext(); } @After public void tearDown() { stream.unsubscribe(); context.shutdown(); RollingCollapserBatchSizeDistributionStream.reset(); } @Test public void testEmptyStreamProducesEmptyDistributions() { HystrixCollapserKey key = HystrixCollapserKey.Factory.asKey("Collapser-Batch-Size-A"); stream = RollingCollapserBatchSizeDistributionStream.getInstance(key, 10, 100); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().skip(10).take(10).subscribe(new Subscriber<CachedValuesHistogram>() { @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Throwable e) { fail(e.getMessage()); } @Override public void onNext(CachedValuesHistogram distribution) { System.out.println("OnNext @ " + System.currentTimeMillis()); assertEquals(0, distribution.getTotalCount()); } }); //no writes try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertEquals(0, stream.getLatest().getTotalCount()); } @Test public void testBatches() { HystrixCollapserKey key = HystrixCollapserKey.Factory.asKey("Collapser-Batch-Size-B"); stream = RollingCollapserBatchSizeDistributionStream.getInstance(key, 10, 100); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(10).subscribe(new Subscriber<CachedValuesHistogram>() { @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Throwable e) { fail(e.getMessage()); } @Override public void onNext(CachedValuesHistogram distribution) { System.out.println("OnNext @ " + System.currentTimeMillis()); } }); Collapser.from(key, 1).observe(); Collapser.from(key, 2).observe(); Collapser.from(key, 3).observe(); try { Thread.sleep(250); } catch (InterruptedException ex) { fail("Interrupted ex"); } Collapser.from(key, 4).observe(); try { Thread.sleep(250); } catch (InterruptedException ex) { fail("Interrupted ex"); } Collapser.from(key, 5).observe(); Collapser.from(key, 6).observe(); Collapser.from(key, 7).observe(); Collapser.from(key, 8).observe(); Collapser.from(key, 9).observe(); try { Thread.sleep(250); } catch (InterruptedException ex) { fail("Interrupted ex"); } Collapser.from(key, 10).observe(); Collapser.from(key, 11).observe(); Collapser.from(key, 12).observe(); try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } //should have 4 batches: 3, 1, 5, 3 assertEquals(4, stream.getLatest().getTotalCount()); assertEquals(3, stream.getLatestMean()); assertEquals(1, stream.getLatestPercentile(0)); assertEquals(5, stream.getLatestPercentile(100)); } //by doing a take(30), all metrics should fall out of window and we should observe an empty histogram @Test public void testBatchesAgeOut() { HystrixCollapserKey key = HystrixCollapserKey.Factory.asKey("Collapser-Batch-Size-B"); stream = RollingCollapserBatchSizeDistributionStream.getInstance(key, 10, 100); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(30).subscribe(new Subscriber<CachedValuesHistogram>() { @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Throwable e) { fail(e.getMessage()); } @Override public void onNext(CachedValuesHistogram distribution) { System.out.println("OnNext @ " + System.currentTimeMillis()); } }); Collapser.from(key, 1).observe(); Collapser.from(key, 2).observe(); Collapser.from(key, 3).observe(); try { Thread.sleep(200); } catch (InterruptedException ex) { fail("Interrupted ex"); } Collapser.from(key, 4).observe(); try { Thread.sleep(200); } catch (InterruptedException ex) { fail("Interrupted ex"); } Collapser.from(key, 5).observe(); Collapser.from(key, 6).observe(); Collapser.from(key, 7).observe(); Collapser.from(key, 8).observe(); Collapser.from(key, 9).observe(); try { Thread.sleep(200); } catch (InterruptedException ex) { fail("Interrupted ex"); } Collapser.from(key, 10).observe(); Collapser.from(key, 11).observe(); Collapser.from(key, 12).observe(); try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertEquals(0, stream.getLatest().getTotalCount()); assertEquals(0, stream.getLatestMean()); } }
4,602
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/RollingThreadPoolEventCounterStreamTest.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 RollingThreadPoolEventCounterStreamTest extends CommandStreamTest { HystrixRequestContext context; RollingThreadPoolEventCounterStream 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("ThreadPool-A"); HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-A"); HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingCounter-A"); stream = RollingThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).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) + stream.getLatestCount(HystrixEventType.ThreadPool.REJECTED)); } @Test public void testSingleSuccess() { HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ThreadPool-B"); HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-B"); HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingCounter-B"); stream = RollingThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).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("ThreadPool-C"); HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-C"); HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingCounter-C"); stream = RollingThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).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("ThreadPool-D"); HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-D"); HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingCounter-D"); stream = RollingThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).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("ThreadPool-E"); HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-E"); HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingCounter-E"); stream = RollingThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).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("ThreadPool-F"); HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-F"); HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingCounter-F"); stream = RollingThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).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("ThreadPool-G"); HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-G"); HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingCounter-G"); stream = RollingThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).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("ThreadPool-H"); HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-H"); HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingCounter-H"); stream = RollingThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).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, 500, 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(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.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("ThreadPool-I"); HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-I"); HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingCounter-I"); stream = RollingThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).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, 200)); } 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("ThreadPool-J"); HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-J"); HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingCounter-J"); stream = RollingThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).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("ThreadPool-K"); HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-K"); HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingCounter-K"); stream = RollingThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).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("ThreadPool-L"); HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-L"); HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingCounter-L"); stream = RollingThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).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)); } @Test public void testMultipleEventsOverTimeGetStoredAndAgeOut() { HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("ThreadPool-M"); HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("ThreadPool-M"); HystrixCommandKey key = HystrixCommandKey.Factory.asKey("RollingCounter-M"); stream = RollingThreadPoolEventCounterStream.getInstance(threadPoolKey, 10, 250); stream.startCachingStreamValuesIfUnstarted(); //by doing a take(20), we ensure that all rolling counts go back to 0 final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(20).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(0, stream.getLatestCount(HystrixEventType.ThreadPool.EXECUTED)); assertEquals(0, stream.getLatestCount(HystrixEventType.ThreadPool.REJECTED)); } }
4,603
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/CumulativeCollapserEventCounterStreamTest.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.HystrixCollapserKey; import com.netflix.hystrix.HystrixCollapserMetrics; import com.netflix.hystrix.HystrixEventType; import com.netflix.hystrix.HystrixRequestLog; import com.netflix.hystrix.metric.CommandStreamTest; 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.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.junit.Assert.*; public class CumulativeCollapserEventCounterStreamTest extends CommandStreamTest { HystrixRequestContext context; CumulativeCollapserEventCounterStream 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() + " : " + collapserEventsToStr(eventCounts)); } }; } @Before public void setUp() { context = HystrixRequestContext.initializeContext(); } @After public void tearDown() { context.shutdown(); stream.unsubscribe(); CumulativeCollapserEventCounterStream.reset(); } protected static String collapserEventsToStr(long[] eventCounts) { StringBuilder sb = new StringBuilder(); sb.append("["); for (HystrixEventType.Collapser eventType : HystrixEventType.Collapser.values()) { if (eventCounts[eventType.ordinal()] > 0) { sb.append(eventType.name()).append("->").append(eventCounts[eventType.ordinal()]).append(", "); } } sb.append("]"); return sb.toString(); } @Test public void testEmptyStreamProducesZeros() { HystrixCollapserKey key = HystrixCollapserKey.Factory.asKey("CumulativeCollapser-A"); stream = CumulativeCollapserEventCounterStream.getInstance(key, 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"); } System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertEquals(HystrixEventType.Collapser.values().length, stream.getLatest().length); assertEquals(0, stream.getLatest(HystrixEventType.Collapser.ADDED_TO_BATCH)); assertEquals(0, stream.getLatest(HystrixEventType.Collapser.BATCH_EXECUTED)); assertEquals(0, stream.getLatest(HystrixEventType.Collapser.RESPONSE_FROM_CACHE)); } @Test public void testCollapsed() { HystrixCollapserKey key = HystrixCollapserKey.Factory.asKey("CumulativeCollapser-B"); stream = CumulativeCollapserEventCounterStream.getInstance(key, 10, 100); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(10).subscribe(getSubscriber(latch)); for (int i = 0; i < 3; i++) { CommandStreamTest.Collapser.from(key, i).observe(); } try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertEquals(HystrixEventType.Collapser.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.Collapser.values().length]; expected[HystrixEventType.Collapser.BATCH_EXECUTED.ordinal()] = 1; expected[HystrixEventType.Collapser.ADDED_TO_BATCH.ordinal()] = 3; System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertArrayEquals(expected, stream.getLatest()); } @Test public void testCollapsedAndResponseFromCache() { HystrixCollapserKey key = HystrixCollapserKey.Factory.asKey("CumulativeCollapser-C"); stream = CumulativeCollapserEventCounterStream.getInstance(key, 10, 100); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(10).subscribe(getSubscriber(latch)); for (int i = 0; i < 3; i++) { CommandStreamTest.Collapser.from(key, i).observe(); CommandStreamTest.Collapser.from(key, i).observe(); //same arg - should get a response from cache CommandStreamTest.Collapser.from(key, i).observe(); //same arg - should get a response from cache } try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertEquals(HystrixEventType.Collapser.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.Collapser.values().length]; expected[HystrixEventType.Collapser.BATCH_EXECUTED.ordinal()] = 1; expected[HystrixEventType.Collapser.ADDED_TO_BATCH.ordinal()] = 3; expected[HystrixEventType.Collapser.RESPONSE_FROM_CACHE.ordinal()] = 6; System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertArrayEquals(expected, stream.getLatest()); } //by doing a take(30), we expect all values to stay in the stream, as cumulative counters never age out of window @Test public void testCollapsedAndResponseFromCacheAgeOutOfCumulativeWindow() { HystrixCollapserKey key = HystrixCollapserKey.Factory.asKey("CumulativeCollapser-D"); stream = CumulativeCollapserEventCounterStream.getInstance(key, 10, 100); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(30).subscribe(getSubscriber(latch)); for (int i = 0; i < 3; i++) { CommandStreamTest.Collapser.from(key, i).observe(); CommandStreamTest.Collapser.from(key, i).observe(); //same arg - should get a response from cache CommandStreamTest.Collapser.from(key, i).observe(); //same arg - should get a response from cache } try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertEquals(HystrixEventType.Collapser.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.Collapser.values().length]; expected[HystrixEventType.Collapser.BATCH_EXECUTED.ordinal()] = 1; expected[HystrixEventType.Collapser.ADDED_TO_BATCH.ordinal()] = 3; expected[HystrixEventType.Collapser.RESPONSE_FROM_CACHE.ordinal()] = 6; System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertArrayEquals(expected, stream.getLatest()); } }
4,604
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/RollingCommandLatencyDistributionStreamTest.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.metric.CachedValuesHistogram; 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 RollingCommandLatencyDistributionStreamTest extends CommandStreamTest { RollingCommandLatencyDistributionStream stream; HystrixRequestContext context; static HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("CommandLatency"); @Before public void setUp() { context = HystrixRequestContext.initializeContext(); } @After public void tearDown() { stream.unsubscribe(); context.shutdown(); RollingCommandLatencyDistributionStream.reset(); } @Test public void testEmptyStreamProducesEmptyDistributions() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Latency-A"); stream = RollingCommandLatencyDistributionStream.getInstance(key, 10, 100); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(10).subscribe(new Subscriber<CachedValuesHistogram>() { @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Throwable e) { fail(e.getMessage()); } @Override public void onNext(CachedValuesHistogram distribution) { System.out.println("OnNext @ " + System.currentTimeMillis()); assertEquals(0, distribution.getTotalCount()); } }); //no writes try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertEquals(0, stream.getLatest().getTotalCount()); } private void assertBetween(int expectedLow, int expectedHigh, int value) { assertTrue("value too low (" + value + "), expected low = " + expectedLow, expectedLow <= value); assertTrue("value too high (" + value + "), expected high = " + expectedHigh, expectedHigh >= value); } @Test public void testSingleBucketGetsStored() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Latency-B"); stream = RollingCommandLatencyDistributionStream.getInstance(key, 10, 100); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(10).subscribe(new Subscriber<CachedValuesHistogram>() { @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Throwable e) { fail(e.getMessage()); } @Override public void onNext(CachedValuesHistogram distribution) { System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Received distribution with count : " + distribution.getTotalCount() + " and mean : " + distribution.getMean()); if (distribution.getTotalCount() == 1) { assertBetween(10, 50, (int) distribution.getMean()); } else if (distribution.getTotalCount() == 2) { assertBetween(300, 400, (int) distribution.getMean()); } } }); Command cmd1 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 10); Command cmd2 = Command.from(groupKey, key, HystrixEventType.TIMEOUT); //latency = 600 cmd1.observe(); cmd2.observe(); try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertBetween(150, 400, stream.getLatestMean()); assertBetween(10, 50, stream.getLatestPercentile(0.0)); assertBetween(300, 800, stream.getLatestPercentile(100.0)); } /* * The following event types should not have their latency measured: * THREAD_POOL_REJECTED * SEMAPHORE_REJECTED * SHORT_CIRCUITED * RESPONSE_FROM_CACHE * * Newly measured (as of 1.5) * BAD_REQUEST * FAILURE * TIMEOUT */ @Test public void testSingleBucketWithMultipleEventTypes() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Latency-C"); stream = RollingCommandLatencyDistributionStream.getInstance(key, 10, 100); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(10).subscribe(new Subscriber<CachedValuesHistogram>() { @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Throwable e) { fail(e.getMessage()); } @Override public void onNext(CachedValuesHistogram distribution) { System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Received distribution with count : " + distribution.getTotalCount() + " and mean : " + distribution.getMean()); if (distribution.getTotalCount() < 4 && distribution.getTotalCount() > 0) { //buckets before timeout latency registers assertBetween(10, 50, (int) distribution.getMean()); } else if (distribution.getTotalCount() == 4){ assertBetween(150, 250, (int) distribution.getMean()); //now timeout latency of 600ms is there } } }); Command cmd1 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 10); Command cmd2 = Command.from(groupKey, key, HystrixEventType.TIMEOUT); //latency = 600 Command cmd3 = Command.from(groupKey, key, HystrixEventType.FAILURE, 30); Command cmd4 = Command.from(groupKey, key, HystrixEventType.BAD_REQUEST, 40); cmd1.observe(); cmd2.observe(); cmd3.observe(); cmd4.observe(); try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertBetween(150, 350, stream.getLatestMean()); //now timeout latency of 600ms is there assertBetween(10, 40, stream.getLatestPercentile(0.0)); assertBetween(600, 800, stream.getLatestPercentile(100.0)); } @Test public void testShortCircuitedCommandDoesNotGetLatencyTracked() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Latency-D"); stream = RollingCommandLatencyDistributionStream.getInstance(key, 10, 100); stream.startCachingStreamValuesIfUnstarted(); //3 failures is enough to trigger short-circuit. execute those, then wait for bucket to roll //next command should be a short-circuit List<Command> commands = new ArrayList<Command>(); for (int i = 0; i < 3; i++) { commands.add(Command.from(groupKey, key, HystrixEventType.FAILURE, 0)); } final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(10).subscribe(new Subscriber<CachedValuesHistogram>() { @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Throwable e) { fail(e.getMessage()); } @Override public void onNext(CachedValuesHistogram distribution) { System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Received distribution with count : " + distribution.getTotalCount() + " and mean : " + distribution.getMean()); assertBetween(0, 30, (int) distribution.getMean()); } }); for (Command cmd: commands) { cmd.observe(); } Command shortCircuit = Command.from(groupKey, key, HystrixEventType.SUCCESS); try { Thread.sleep(200); shortCircuit.observe(); } catch (InterruptedException ie) { fail(ie.getMessage()); } try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertEquals(3, stream.getLatest().getTotalCount()); assertBetween(0, 30, stream.getLatestMean()); System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertTrue(shortCircuit.isResponseShortCircuited()); } @Test public void testThreadPoolRejectedCommandDoesNotGetLatencyTracked() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Latency-E"); stream = RollingCommandLatencyDistributionStream.getInstance(key, 10, 100); stream.startCachingStreamValuesIfUnstarted(); //10 commands with latency should occupy the entire threadpool. execute those, then wait for bucket to roll //next command should be a thread-pool rejection List<Command> commands = new ArrayList<Command>(); for (int i = 0; i < 10; i++) { commands.add(Command.from(groupKey, key, HystrixEventType.SUCCESS, 200)); } final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(10).subscribe(new Subscriber<CachedValuesHistogram>() { @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Throwable e) { fail(e.getMessage()); } @Override public void onNext(CachedValuesHistogram distribution) { System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Received distribution with count : " + distribution.getTotalCount() + " and mean : " + distribution.getMean()); // if (distribution.getTotalCount() > 0) { // assertBetween(200, 250, (int) distribution.getMean()); // } } }); for (Command cmd: commands) { cmd.observe(); } Command threadPoolRejected = Command.from(groupKey, key, HystrixEventType.SUCCESS); try { Thread.sleep(40); threadPoolRejected.observe(); } catch (InterruptedException ie) { fail(ie.getMessage()); } try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertEquals(10, stream.getLatest().getTotalCount()); assertBetween(200, 250, stream.getLatestMean()); System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertTrue(threadPoolRejected.isResponseThreadPoolRejected()); } @Test public void testSemaphoreRejectedCommandDoesNotGetLatencyTracked() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Latency-F"); stream = RollingCommandLatencyDistributionStream.getInstance(key, 10, 100); stream.startCachingStreamValuesIfUnstarted(); //10 commands with latency should occupy all semaphores. execute those, then wait for bucket to roll //next command should be a semaphore rejection List<Command> commands = new ArrayList<Command>(); for (int i = 0; i < 10; i++) { commands.add(Command.from(groupKey, key, HystrixEventType.SUCCESS, 200, HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE)); } final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(10).subscribe(new Subscriber<CachedValuesHistogram>() { @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Throwable e) { fail(e.getMessage()); } @Override public void onNext(CachedValuesHistogram distribution) { System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Received distribution with count : " + distribution.getTotalCount() + " and mean : " + distribution.getMean()); if (distribution.getTotalCount() > 0) { assertBetween(200, 250, (int) distribution.getMean()); } } }); for (final Command cmd: commands) { //since these are blocking calls on the caller thread, we need a new caller thread for each command to actually get the desired concurrency new Thread(new HystrixContextRunnable(new Runnable() { @Override public void run() { cmd.observe(); } })).start(); } Command semaphoreRejected = Command.from(groupKey, key, HystrixEventType.SUCCESS); try { Thread.sleep(40); semaphoreRejected.observe(); } catch (InterruptedException ie) { fail(ie.getMessage()); } try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertEquals(10, stream.getLatest().getTotalCount()); assertBetween(200, 250, stream.getLatestMean()); System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertTrue(semaphoreRejected.isResponseSemaphoreRejected()); } @Test public void testResponseFromCacheDoesNotGetLatencyTracked() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Latency-G"); stream = RollingCommandLatencyDistributionStream.getInstance(key, 10, 100); stream.startCachingStreamValuesIfUnstarted(); //should get 1 SUCCESS and 1 RESPONSE_FROM_CACHE List<Command> commands = Command.getCommandsWithResponseFromCache(groupKey, key); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(10).subscribe(new Subscriber<CachedValuesHistogram>() { @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Throwable e) { fail(e.getMessage()); } @Override public void onNext(CachedValuesHistogram distribution) { System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Received distribution with count : " + distribution.getTotalCount() + " and mean : " + distribution.getMean()); assertTrue(distribution.getTotalCount() <= 1); } }); for (Command cmd: commands) { cmd.observe(); } try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertEquals(1, stream.getLatest().getTotalCount()); assertBetween(0, 30, stream.getLatestMean()); System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); } @Test public void testMultipleBucketsBothGetStored() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Latency-H"); stream = RollingCommandLatencyDistributionStream.getInstance(key, 10, 100); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(10).subscribe(new Subscriber<CachedValuesHistogram>() { @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Throwable e) { fail(e.getMessage()); } @Override public void onNext(CachedValuesHistogram distribution) { System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Received distribution with count : " + distribution.getTotalCount() + " and mean : " + distribution.getMean()); if (distribution.getTotalCount() == 2) { assertBetween(55, 90, (int) distribution.getMean()); } if (distribution.getTotalCount() == 5) { assertEquals(60, 90, (long) distribution.getMean()); } } }); Command cmd1 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 10); Command cmd2 = Command.from(groupKey, key, HystrixEventType.FAILURE, 100); cmd1.observe(); cmd2.observe(); try { Thread.sleep(500); } catch (InterruptedException ie) { fail("Interrupted ex"); } Command cmd3 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 60); Command cmd4 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 60); Command cmd5 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 70); cmd3.observe(); cmd4.observe(); cmd5.observe(); try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertBetween(55, 90, stream.getLatestMean()); assertBetween(10, 50, stream.getLatestPercentile(0.0)); assertBetween(100, 150, stream.getLatestPercentile(100.0)); } /** * The extra takes on the stream should give enough time for all of the measured latencies to age out */ @Test public void testMultipleBucketsBothGetStoredAndThenAgeOut() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Latency-I"); stream = RollingCommandLatencyDistributionStream.getInstance(key, 10, 100); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(30).subscribe(new Subscriber<CachedValuesHistogram>() { @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Throwable e) { fail(e.getMessage()); } @Override public void onNext(CachedValuesHistogram distribution) { System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Received distribution with count : " + distribution.getTotalCount() + " and mean : " + distribution.getMean()); if (distribution.getTotalCount() == 2) { assertBetween(55, 90, (int) distribution.getMean()); } if (distribution.getTotalCount() == 5) { assertEquals(60, 90, (long) distribution.getMean()); } } }); Command cmd1 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 10); Command cmd2 = Command.from(groupKey, key, HystrixEventType.FAILURE, 100); cmd1.observe(); cmd2.observe(); try { Thread.sleep(500); } catch (InterruptedException ie) { fail("Interrupted ex"); } Command cmd3 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 60); Command cmd4 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 60); Command cmd5 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 70); cmd3.observe(); cmd4.observe(); cmd5.observe(); try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertEquals(0, stream.getLatest().getTotalCount()); } }
4,605
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/RollingCommandEventCounterStreamTest.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.HystrixCommandMetrics; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.HystrixEventType; import com.netflix.hystrix.HystrixRequestLog; 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 RollingCommandEventCounterStreamTest extends CommandStreamTest { HystrixRequestContext context; RollingCommandEventCounterStream stream; static HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("RollingCommandCounter"); 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() + " : " + bucketToString(eventCounts)); } }; } @Before public void setUp() { context = HystrixRequestContext.initializeContext(); } @After public void tearDown() { context.shutdown(); stream.unsubscribe(); RollingCommandEventCounterStream.reset(); } @Test public void testEmptyStreamProducesZeros() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-RollingCounter-A"); stream = RollingCommandEventCounterStream.getInstance(key, 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"); } System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertEquals(HystrixEventType.values().length, stream.getLatest().length); assertFalse(hasData(stream.getLatest())); } @Test public void testSingleSuccess() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-RollingCounter-B"); stream = RollingCommandEventCounterStream.getInstance(key, 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(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.SUCCESS.ordinal()] = 1; System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertArrayEquals(expected, stream.getLatest()); } @Test public void testSingleFailure() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-RollingCounter-C"); stream = RollingCommandEventCounterStream.getInstance(key, 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(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.FAILURE.ordinal()] = 1; expected[HystrixEventType.FALLBACK_SUCCESS.ordinal()] = 1; System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertArrayEquals(expected, stream.getLatest()); } @Test public void testSingleTimeout() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-RollingCounter-D"); stream = RollingCommandEventCounterStream.getInstance(key, 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(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.TIMEOUT.ordinal()] = 1; expected[HystrixEventType.FALLBACK_SUCCESS.ordinal()] = 1; System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertArrayEquals(expected, stream.getLatest()); } @Test public void testSingleBadRequest() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-RollingCounter-E"); stream = RollingCommandEventCounterStream.getInstance(key, 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(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.BAD_REQUEST.ordinal()] = 1; expected[HystrixEventType.EXCEPTION_THROWN.ordinal()] = 1; System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertArrayEquals(expected, stream.getLatest()); } @Test public void testRequestFromCache() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-RollingCounter-F"); stream = RollingCommandEventCounterStream.getInstance(key, 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()); assertEquals(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.SUCCESS.ordinal()] = 1; expected[HystrixEventType.RESPONSE_FROM_CACHE.ordinal()] = 2; System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertArrayEquals(expected, stream.getLatest()); } @Test public void testShortCircuited() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-RollingCounter-G"); stream = RollingCommandEventCounterStream.getInstance(key, 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 then 5 FALLBACK_SUCCESSes 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()); assertEquals(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.FAILURE.ordinal()] = 3; expected[HystrixEventType.SHORT_CIRCUITED.ordinal()] = 2; expected[HystrixEventType.FALLBACK_SUCCESS.ordinal()] = 5; System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertArrayEquals(expected, stream.getLatest()); } @Test public void testSemaphoreRejected() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-RollingCounter-H"); stream = RollingCommandEventCounterStream.getInstance(key, 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<CommandStreamTest.Command> saturators = new ArrayList<CommandStreamTest.Command>(); for (int i = 0; i < 10; i++) { saturators.add(CommandStreamTest.Command.from(groupKey, key, HystrixEventType.SUCCESS, 200, 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(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.isResponseSemaphoreRejected()); assertTrue(rejected2.isResponseSemaphoreRejected()); assertEquals(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.SUCCESS.ordinal()] = 10; expected[HystrixEventType.SEMAPHORE_REJECTED.ordinal()] = 2; expected[HystrixEventType.FALLBACK_SUCCESS.ordinal()] = 2; System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertArrayEquals(expected, stream.getLatest()); } @Test public void testThreadPoolRejected() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-RollingCounter-I"); stream = RollingCommandEventCounterStream.getInstance(key, 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, 200)); } 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()); assertEquals(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.SUCCESS.ordinal()] = 10; expected[HystrixEventType.THREAD_POOL_REJECTED.ordinal()] = 2; expected[HystrixEventType.FALLBACK_SUCCESS.ordinal()] = 2; assertArrayEquals(expected, stream.getLatest()); } @Test public void testFallbackFailure() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-RollingCounter-J"); stream = RollingCommandEventCounterStream.getInstance(key, 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(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.FAILURE.ordinal()] = 1; expected[HystrixEventType.FALLBACK_FAILURE.ordinal()] = 1; expected[HystrixEventType.EXCEPTION_THROWN.ordinal()] = 1; System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertArrayEquals(expected, stream.getLatest()); } @Test public void testFallbackMissing() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-RollingCounter-K"); stream = RollingCommandEventCounterStream.getInstance(key, 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(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.FAILURE.ordinal()] = 1; expected[HystrixEventType.FALLBACK_MISSING.ordinal()] = 1; expected[HystrixEventType.EXCEPTION_THROWN.ordinal()] = 1; assertArrayEquals(expected, stream.getLatest()); } @Test public void testFallbackRejection() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-RollingCounter-L"); stream = RollingCommandEventCounterStream.getInstance(key, 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"); } assertEquals(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.FAILURE.ordinal()] = 7; expected[HystrixEventType.FALLBACK_SUCCESS.ordinal()] = 5; expected[HystrixEventType.FALLBACK_REJECTION.ordinal()] = 2; expected[HystrixEventType.EXCEPTION_THROWN.ordinal()] = 2; System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertArrayEquals(expected, stream.getLatest()); } @Test public void testCollapsed() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("BatchCommand"); stream = RollingCommandEventCounterStream.getInstance(key, 10, 100); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(10).subscribe(getSubscriber(latch)); for (int i = 0; i < 3; i++) { CommandStreamTest.Collapser.from(i).observe(); } try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertEquals(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.SUCCESS.ordinal()] = 1; expected[HystrixEventType.COLLAPSED.ordinal()] = 3; System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertArrayEquals(expected, stream.getLatest()); } @Test public void testMultipleEventsOverTimeGetStoredAndAgeOut() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-RollingCounter-M"); stream = RollingCommandEventCounterStream.getInstance(key, 10, 100); stream.startCachingStreamValuesIfUnstarted(); //by doing a take(30), we ensure that all rolling counts go back to 0 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"); } assertEquals(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertArrayEquals(expected, stream.getLatest()); } }
4,606
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/HealthCountsStreamTest.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.HystrixCommand; 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.HystrixRequestLog; 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.Observable; import rx.Subscriber; import rx.Subscription; import rx.functions.Action0; import rx.functions.Func2; import rx.schedulers.Schedulers; import java.util.ArrayList; import java.util.List; 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.*; public class HealthCountsStreamTest extends CommandStreamTest { HystrixRequestContext context; HealthCountsStream stream; static HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("HealthCounts"); private static Subscriber<HystrixCommandMetrics.HealthCounts> getSubscriber(final CountDownLatch latch) { return new Subscriber<HystrixCommandMetrics.HealthCounts>() { @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Throwable e) { fail(e.getMessage()); } @Override public void onNext(HystrixCommandMetrics.HealthCounts healthCounts) { System.out.println("OnNext @ " + System.currentTimeMillis() + " : " + healthCounts); } }; } @Before public void setUp() { context = HystrixRequestContext.initializeContext(); } @After public void tearDown() { context.shutdown(); stream.unsubscribe(); RollingCommandEventCounterStream.reset(); } @Test public void testEmptyStreamProducesZeros() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Health-A"); stream = HealthCountsStream.getInstance(key, 10, 100); 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"); } System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertEquals(0L, stream.getLatest().getErrorCount()); assertEquals(0L, stream.getLatest().getTotalRequests()); } @Test public void testSingleSuccess() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Health-B"); stream = HealthCountsStream.getInstance(key, 10, 100); 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"); } System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertEquals(0L, stream.getLatest().getErrorCount()); assertEquals(1L, stream.getLatest().getTotalRequests()); } @Test public void testSingleFailure() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Health-C"); stream = HealthCountsStream.getInstance(key, 10, 100); 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"); } System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertEquals(1L, stream.getLatest().getErrorCount()); assertEquals(1L, stream.getLatest().getTotalRequests()); } @Test public void testSingleTimeout() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Health-D"); stream = HealthCountsStream.getInstance(key, 10, 100); 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"); } System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertEquals(1L, stream.getLatest().getErrorCount()); assertEquals(1L, stream.getLatest().getTotalRequests()); } @Test public void testSingleBadRequest() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Health-E"); stream = HealthCountsStream.getInstance(key, 10, 100); 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"); } System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertEquals(0L, stream.getLatest().getErrorCount()); assertEquals(0L, stream.getLatest().getTotalRequests()); } @Test public void testRequestFromCache() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Health-F"); stream = HealthCountsStream.getInstance(key, 10, 100); 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()); assertEquals(0L, stream.getLatest().getErrorCount()); assertEquals(1L, stream.getLatest().getTotalRequests()); //responses from cache should not show up here } @Test public void testShortCircuited() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Health-G"); stream = HealthCountsStream.getInstance(key, 10, 100); 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 then 5 FALLBACK_SUCCESSes 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(500); } catch (InterruptedException ie) { fail(ie.getMessage()); } shortCircuit1.observe(); shortCircuit2.observe(); try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertTrue(shortCircuit1.isResponseShortCircuited()); assertTrue(shortCircuit2.isResponseShortCircuited()); System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); //should only see failures here, not SHORT-CIRCUITS assertEquals(3L, stream.getLatest().getErrorCount()); assertEquals(3L, stream.getLatest().getTotalRequests()); } @Test public void testSemaphoreRejected() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Health-H"); stream = HealthCountsStream.getInstance(key, 10, 100); 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, 400, 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(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.isResponseSemaphoreRejected()); assertTrue(rejected2.isResponseSemaphoreRejected()); assertEquals(2L, stream.getLatest().getErrorCount()); assertEquals(12L, stream.getLatest().getTotalRequests()); } @Test public void testThreadPoolRejected() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Health-I"); stream = HealthCountsStream.getInstance(key, 10, 100); 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, 400)); } 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()); assertEquals(2L, stream.getLatest().getErrorCount()); assertEquals(12L, stream.getLatest().getTotalRequests()); } @Test public void testFallbackFailure() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Health-J"); stream = HealthCountsStream.getInstance(key, 10, 100); 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"); } System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertEquals(1L, stream.getLatest().getErrorCount()); assertEquals(1L, stream.getLatest().getTotalRequests()); } @Test public void testFallbackMissing() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Health-K"); stream = HealthCountsStream.getInstance(key, 10, 100); 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(1L, stream.getLatest().getErrorCount()); assertEquals(1L, stream.getLatest().getTotalRequests()); } @Test public void testFallbackRejection() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Health-L"); stream = HealthCountsStream.getInstance(key, 10, 100); 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"); } System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertEquals(7L, stream.getLatest().getErrorCount()); assertEquals(7L, stream.getLatest().getTotalRequests()); } @Test public void testMultipleEventsOverTimeGetStoredAndAgeOut() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Health-M"); stream = HealthCountsStream.getInstance(key, 10, 100); //by doing a take(30), we ensure that all rolling counts go back to 0 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"); } System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertEquals(0L, stream.getLatest().getErrorCount()); assertEquals(0L, stream.getLatest().getTotalRequests()); } @Test public void testSharedSourceStream() throws InterruptedException { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Health-N"); stream = HealthCountsStream.getInstance(key, 10, 100); final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean allEqual = new AtomicBoolean(false); Observable<HystrixCommandMetrics.HealthCounts> o1 = stream .observe() .take(10) .observeOn(Schedulers.computation()); Observable<HystrixCommandMetrics.HealthCounts> o2 = stream .observe() .take(10) .observeOn(Schedulers.computation()); Observable<Boolean> zipped = Observable.zip(o1, o2, new Func2<HystrixCommandMetrics.HealthCounts, HystrixCommandMetrics.HealthCounts, Boolean>() { @Override public Boolean call(HystrixCommandMetrics.HealthCounts healthCounts, HystrixCommandMetrics.HealthCounts healthCounts2) { return healthCounts == healthCounts2; //we want object equality } }); Observable < Boolean > reduced = zipped.reduce(true, new Func2<Boolean, Boolean, Boolean>() { @Override public Boolean call(Boolean a, Boolean b) { return a && b; } }); reduced.subscribe(new Subscriber<Boolean>() { @Override public void onCompleted() { System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Reduced OnCompleted"); latch.countDown(); } @Override public void onError(Throwable e) { System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Reduced OnError : " + e); e.printStackTrace(); latch.countDown(); } @Override public void onNext(Boolean b) { System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " Reduced OnNext : " + b); allEqual.set(b); } }); for (int i = 0; i < 10; i++) { HystrixCommand<Integer> cmd = CommandStreamTest.Command.from(groupKey, key, HystrixEventType.SUCCESS, 20); cmd.execute(); } assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); assertTrue(allEqual.get()); //we should be getting the same object from both streams. this ensures that multiple subscribers don't induce extra work } @Test public void testTwoSubscribersOneUnsubscribes() throws Exception { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-Health-O"); stream = HealthCountsStream.getInstance(key, 10, 100); final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); final AtomicInteger healthCounts1 = new AtomicInteger(0); final AtomicInteger healthCounts2 = new AtomicInteger(0); Subscription s1 = stream .observe() .take(10) .observeOn(Schedulers.computation()) .doOnUnsubscribe(new Action0() { @Override public void call() { latch1.countDown(); } }) .subscribe(new Subscriber<HystrixCommandMetrics.HealthCounts>() { @Override public void onCompleted() { System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Health 1 OnCompleted"); latch1.countDown(); } @Override public void onError(Throwable e) { System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Health 1 OnError : " + e); latch1.countDown(); } @Override public void onNext(HystrixCommandMetrics.HealthCounts healthCounts) { System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Health 1 OnNext : " + healthCounts); healthCounts1.incrementAndGet(); } }); Subscription s2 = stream .observe() .take(10) .observeOn(Schedulers.computation()) .doOnUnsubscribe(new Action0() { @Override public void call() { latch2.countDown(); } }) .subscribe(new Subscriber<HystrixCommandMetrics.HealthCounts>() { @Override public void onCompleted() { System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Health 2 OnCompleted"); latch2.countDown(); } @Override public void onError(Throwable e) { System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Health 2 OnError : " + e); latch2.countDown(); } @Override public void onNext(HystrixCommandMetrics.HealthCounts healthCounts) { System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Health 2 OnNext : " + healthCounts + " : " + healthCounts2.get()); healthCounts2.incrementAndGet(); } }); //execute 5 commands, then unsubscribe from first stream. then execute the rest for (int i = 0; i < 10; i++) { HystrixCommand<Integer> cmd = CommandStreamTest.Command.from(groupKey, key, HystrixEventType.SUCCESS, 20); cmd.execute(); if (i == 5) { s1.unsubscribe(); } } assertTrue(stream.isSourceCurrentlySubscribed()); //only 1/2 subscriptions has been cancelled assertTrue(latch1.await(10000, TimeUnit.MILLISECONDS)); assertTrue(latch2.await(10000, TimeUnit.MILLISECONDS)); System.out.println("s1 got : " + healthCounts1.get() + ", s2 got : " + healthCounts2.get()); assertTrue("s1 got data", healthCounts1.get() > 0); assertTrue("s2 got data", healthCounts2.get() > 0); assertTrue("s1 got less data than s2", healthCounts2.get() > healthCounts1.get()); } }
4,607
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/CumulativeCommandEventCounterStreamTest.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.HystrixCommandMetrics; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.HystrixEventType; import com.netflix.hystrix.HystrixRequestLog; 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 rx.Subscription; import rx.functions.Action0; 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 CumulativeCommandEventCounterStreamTest extends CommandStreamTest { HystrixRequestContext context; CumulativeCommandEventCounterStream stream; private static HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("CumulativeCommandCounter"); 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() + " : " + bucketToString(eventCounts)); } }; } @Before public void setUp() { context = HystrixRequestContext.initializeContext(); } @After public void tearDown() { context.shutdown(); stream.unsubscribe(); CumulativeCommandEventCounterStream.reset(); } @Test public void testEmptyStreamProducesZeros() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-CumulativeCounter-A"); stream = CumulativeCommandEventCounterStream.getInstance(key, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).subscribe(getSubscriber(latch)); //no writes try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertEquals(HystrixEventType.values().length, stream.getLatest().length); assertFalse(hasData(stream.getLatest())); } @Test public void testSingleSuccess() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-CumulativeCounter-B"); stream = CumulativeCommandEventCounterStream.getInstance(key, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).subscribe(getSubscriber(latch)); Command cmd = Command.from(groupKey, key, HystrixEventType.SUCCESS, 20); cmd.observe(); try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertEquals(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.SUCCESS.ordinal()] = 1; assertArrayEquals(expected, stream.getLatest()); } @Test public void testSingleFailure() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-CumulativeCounter-C"); stream = CumulativeCommandEventCounterStream.getInstance(key, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).subscribe(getSubscriber(latch)); Command cmd = Command.from(groupKey, key, HystrixEventType.FAILURE, 20); cmd.observe(); try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertEquals(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.FAILURE.ordinal()] = 1; expected[HystrixEventType.FALLBACK_SUCCESS.ordinal()] = 1; assertArrayEquals(expected, stream.getLatest()); } @Test public void testSingleTimeout() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-CumulativeCounter-D"); stream = CumulativeCommandEventCounterStream.getInstance(key, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).subscribe(getSubscriber(latch)); Command cmd = Command.from(groupKey, key, HystrixEventType.TIMEOUT); cmd.observe(); try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertEquals(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.TIMEOUT.ordinal()] = 1; expected[HystrixEventType.FALLBACK_SUCCESS.ordinal()] = 1; assertArrayEquals(expected, stream.getLatest()); } @Test public void testSingleBadRequest() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-CumulativeCounter-E"); stream = CumulativeCommandEventCounterStream.getInstance(key, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).subscribe(getSubscriber(latch)); Command cmd = Command.from(groupKey, key, HystrixEventType.BAD_REQUEST); cmd.observe(); try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertEquals(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.BAD_REQUEST.ordinal()] = 1; expected[HystrixEventType.EXCEPTION_THROWN.ordinal()] = 1; assertArrayEquals(expected, stream.getLatest()); } @Test public void testRequestFromCache() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-CumulativeCounter-F"); stream = CumulativeCommandEventCounterStream.getInstance(key, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).subscribe(getSubscriber(latch)); Command cmd1 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 20); Command cmd2 = Command.from(groupKey, key, HystrixEventType.RESPONSE_FROM_CACHE); Command cmd3 = 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()); assertEquals(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.SUCCESS.ordinal()] = 1; expected[HystrixEventType.RESPONSE_FROM_CACHE.ordinal()] = 2; assertArrayEquals(expected, stream.getLatest()); } @Test public void testShortCircuited() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-CumulativeCounter-G"); stream = CumulativeCommandEventCounterStream.getInstance(key, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).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 then 5 FALLBACK_SUCCESSes Command failure1 = Command.from(groupKey, key, HystrixEventType.FAILURE, 20); Command failure2 = Command.from(groupKey, key, HystrixEventType.FAILURE, 20); Command failure3 = Command.from(groupKey, key, HystrixEventType.FAILURE, 20); Command shortCircuit1 = Command.from(groupKey, key, HystrixEventType.SUCCESS); Command shortCircuit2 = Command.from(groupKey, key, HystrixEventType.SUCCESS); failure1.observe(); failure2.observe(); failure3.observe(); try { Thread.sleep(500); } 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()); assertEquals(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.FAILURE.ordinal()] = 3; expected[HystrixEventType.SHORT_CIRCUITED.ordinal()] = 2; expected[HystrixEventType.FALLBACK_SUCCESS.ordinal()] = 5; assertArrayEquals(expected, stream.getLatest()); } @Test public void testSemaphoreRejected() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-CumulativeCounter-H"); stream = CumulativeCommandEventCounterStream.getInstance(key, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).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(Command.from(groupKey, key, HystrixEventType.SUCCESS, 500, HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE)); } Command rejected1 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 0, HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE); Command rejected2 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 0, HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE); for (final Command saturator : saturators) { new Thread(new HystrixContextRunnable(new Runnable() { @Override public void run() { saturator.observe(); } })).start(); } 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.isResponseSemaphoreRejected()); assertTrue(rejected2.isResponseSemaphoreRejected()); assertEquals(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.SUCCESS.ordinal()] = 10; expected[HystrixEventType.SEMAPHORE_REJECTED.ordinal()] = 2; expected[HystrixEventType.FALLBACK_SUCCESS.ordinal()] = 2; assertArrayEquals(expected, stream.getLatest()); } @Test public void testThreadPoolRejected() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-CumulativeCounter-I"); stream = CumulativeCommandEventCounterStream.getInstance(key, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).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<Command> saturators = new ArrayList<Command>(); for (int i = 0; i < 10; i++) { saturators.add(Command.from(groupKey, key, HystrixEventType.SUCCESS, 500)); } Command rejected1 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 0); Command rejected2 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 0); for (final 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()); assertEquals(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.SUCCESS.ordinal()] = 10; expected[HystrixEventType.THREAD_POOL_REJECTED.ordinal()] = 2; expected[HystrixEventType.FALLBACK_SUCCESS.ordinal()] = 2; assertArrayEquals(expected, stream.getLatest()); } @Test public void testFallbackFailure() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-CumulativeCounter-J"); stream = CumulativeCommandEventCounterStream.getInstance(key, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).subscribe(getSubscriber(latch)); Command cmd = 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(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.FAILURE.ordinal()] = 1; expected[HystrixEventType.FALLBACK_FAILURE.ordinal()] = 1; expected[HystrixEventType.EXCEPTION_THROWN.ordinal()] = 1; assertArrayEquals(expected, stream.getLatest()); } @Test public void testFallbackMissing() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-CumulativeCounter-K"); stream = CumulativeCommandEventCounterStream.getInstance(key, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).subscribe(getSubscriber(latch)); Command cmd = 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(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.FAILURE.ordinal()] = 1; expected[HystrixEventType.FALLBACK_MISSING.ordinal()] = 1; expected[HystrixEventType.EXCEPTION_THROWN.ordinal()] = 1; assertArrayEquals(expected, stream.getLatest()); } @Test public void testFallbackRejection() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-CumulativeCounter-L"); stream = CumulativeCommandEventCounterStream.getInstance(key, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).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<Command> fallbackSaturators = new ArrayList<Command>(); for (int i = 0; i < 5; i++) { fallbackSaturators.add(Command.from(groupKey, key, HystrixEventType.FAILURE, 20, HystrixEventType.FALLBACK_SUCCESS, 400)); } Command rejection1 = Command.from(groupKey, key, HystrixEventType.FAILURE, 20, HystrixEventType.FALLBACK_SUCCESS, 0); Command rejection2 = Command.from(groupKey, key, HystrixEventType.FAILURE, 20, HystrixEventType.FALLBACK_SUCCESS, 0); for (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"); } assertEquals(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.FAILURE.ordinal()] = 7; expected[HystrixEventType.FALLBACK_SUCCESS.ordinal()] = 5; expected[HystrixEventType.FALLBACK_REJECTION.ordinal()] = 2; expected[HystrixEventType.EXCEPTION_THROWN.ordinal()] = 2; assertArrayEquals(expected, stream.getLatest()); } @Test public void testCancelled() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-CumulativeCounter-M"); stream = CumulativeCommandEventCounterStream.getInstance(key, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).subscribe(getSubscriber(latch)); Command toCancel = Command.from(groupKey, key, HystrixEventType.SUCCESS, 500); System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : about to observe and subscribe"); Subscription s = toCancel.observe(). doOnUnsubscribe(new Action0() { @Override public void call() { System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : UnSubscribe from command.observe()"); } }). subscribe(new Subscriber<Integer>() { @Override public void onCompleted() { System.out.println("Command OnCompleted"); } @Override public void onError(Throwable e) { System.out.println("Command OnError : " + e); } @Override public void onNext(Integer i) { System.out.println("Command OnNext : " + i); } }); System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : about to unsubscribe"); s.unsubscribe(); try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertEquals(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.CANCELLED.ordinal()] = 1; assertArrayEquals(expected, stream.getLatest()); } @Test public void testCollapsed() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("BatchCommand"); stream = CumulativeCommandEventCounterStream.getInstance(key, 10, 500); stream.startCachingStreamValuesIfUnstarted(); final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(5).subscribe(getSubscriber(latch)); for (int i = 0; i < 3; i++) { CommandStreamTest.Collapser.from(i).observe(); } try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertEquals(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.SUCCESS.ordinal()] = 1; expected[HystrixEventType.COLLAPSED.ordinal()] = 3; System.out.println("ReqLog : " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); assertArrayEquals(expected, stream.getLatest()); } @Test public void testMultipleEventsOverTimeGetStoredAndNeverAgeOut() { HystrixCommandKey key = HystrixCommandKey.Factory.asKey("CMD-CumulativeCounter-N"); stream = CumulativeCommandEventCounterStream.getInstance(key, 10, 100); stream.startCachingStreamValuesIfUnstarted(); //by doing a take(30), we ensure that no rolling out of window takes place final CountDownLatch latch = new CountDownLatch(1); stream.observe().take(30).subscribe(getSubscriber(latch)); Command cmd1 = Command.from(groupKey, key, HystrixEventType.SUCCESS, 20); Command cmd2 = Command.from(groupKey, key, HystrixEventType.FAILURE, 10); cmd1.observe(); cmd2.observe(); try { assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); } catch (InterruptedException ex) { fail("Interrupted ex"); } assertEquals(HystrixEventType.values().length, stream.getLatest().length); long[] expected = new long[HystrixEventType.values().length]; expected[HystrixEventType.SUCCESS.ordinal()] = 1; expected[HystrixEventType.FAILURE.ordinal()] = 1; expected[HystrixEventType.FALLBACK_SUCCESS.ordinal()] = 1; assertArrayEquals(expected, stream.getLatest()); } }
4,608
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/HystrixDashboardStreamTest.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.hystrix.junit.HystrixRequestContextRule; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandMetrics; 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 HystrixDashboardStreamTest extends CommandStreamTest { @Rule public HystrixRequestContextRule ctx = new HystrixRequestContextRule(); HystrixDashboardStream stream; private final static HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("Dashboard"); private final static HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey("DashboardCommand"); @Before public void init() { stream = HystrixDashboardStream.getNonSingletonInstanceOnlyUsedInUnitTests(10); } @Test public void testStreamHasData() throws Exception { final AtomicBoolean commandShowsUp = 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<HystrixDashboardStream.DashboardData>() { @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(HystrixDashboardStream.DashboardData dashboardData) { System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Received data with : " + dashboardData.commandMetrics.size() + " commands"); for (HystrixCommandMetrics metrics : dashboardData.commandMetrics) { if (metrics.getCommandKey().equals(commandKey)) { commandShowsUp.set(true); } } } }); assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); assertTrue(commandShowsUp.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<HystrixDashboardStream.DashboardData>() { @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(HystrixDashboardStream.DashboardData dashboardData) { System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 1 OnNext : " + dashboardData); payloads1.incrementAndGet(); } }); Subscription s2 = stream .observe() .take(100) .doOnUnsubscribe(new Action0() { @Override public void call() { latch2.countDown(); } }) .subscribe(new Subscriber<HystrixDashboardStream.DashboardData>() { @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(HystrixDashboardStream.DashboardData dashboardData) { System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 2 OnNext : " + dashboardData); 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(10) .doOnUnsubscribe(new Action0() { @Override public void call() { latch1.countDown(); } }) .subscribe(new Subscriber<HystrixDashboardStream.DashboardData>() { @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(HystrixDashboardStream.DashboardData dashboardData) { System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 1 OnNext : " + dashboardData); payloads1.incrementAndGet(); } }); Subscription s2 = stream .observe() .take(10) .doOnUnsubscribe(new Action0() { @Override public void call() { latch2.countDown(); } }) .subscribe(new Subscriber<HystrixDashboardStream.DashboardData>() { @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(HystrixDashboardStream.DashboardData dashboardData) { System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " : Dashboard 2 OnNext : " + dashboardData); payloads2.incrementAndGet(); } }); //execute half the commands, then unsubscribe from both streams, 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 == 25) { 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<HystrixDashboardStream.DashboardData> fast = stream .observe() .observeOn(Schedulers.newThread()); Observable<HystrixDashboardStream.DashboardData> slow = stream .observe() .observeOn(Schedulers.newThread()) .map(new Func1<HystrixDashboardStream.DashboardData, HystrixDashboardStream.DashboardData>() { @Override public HystrixDashboardStream.DashboardData call(HystrixDashboardStream.DashboardData n) { try { Thread.sleep(100); return n; } catch (InterruptedException ex) { return n; } } }); Observable<Boolean> checkZippedEqual = Observable.zip(fast, slow, new Func2<HystrixDashboardStream.DashboardData, HystrixDashboardStream.DashboardData, Boolean>() { @Override public Boolean call(HystrixDashboardStream.DashboardData payload, HystrixDashboardStream.DashboardData 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,609
0
Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/strategy/HystrixPluginsTest.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.strategy; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.ServiceConfigurationError; import java.util.Vector; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentLinkedQueue; import org.junit.After; import org.junit.Test; import org.slf4j.Logger; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.strategy.HystrixPlugins.LoggerSupplier; import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier; import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook; import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisher; import com.netflix.hystrix.strategy.properties.HystrixDynamicProperties; import com.netflix.hystrix.strategy.properties.HystrixDynamicPropertiesSystemProperties; import com.netflix.hystrix.strategy.properties.HystrixDynamicProperty; import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy; public class HystrixPluginsTest { @After public void reset() { //HystrixPlugins.reset(); dynamicPropertyEvents.clear(); System.clearProperty("hystrix.plugin.HystrixDynamicProperties.implementation"); } private static ConcurrentLinkedQueue<String> dynamicPropertyEvents = new ConcurrentLinkedQueue<String>(); @Test public void testDynamicProperties() throws Exception { fakeServiceLoaderResource = "FAKE_META_INF_SERVICES/com.netflix.hystrix.strategy.properties.HystrixDynamicProperties"; HystrixPlugins plugins = setupMockServiceLoader(); HystrixDynamicProperties properties = plugins.getDynamicProperties(); plugins.getCommandExecutionHook(); plugins.getPropertiesStrategy(); assertTrue(properties instanceof MockHystrixDynamicPropertiesTest); assertEvents( "[serviceloader: META-INF/services/com.netflix.hystrix.strategy.properties.HystrixDynamicProperties" + ", debug: [Created HystrixDynamicProperties instance by loading from ServiceLoader. Using class: {}, com.netflix.hystrix.strategy.HystrixPluginsTest.MockHystrixDynamicPropertiesTest]" + ", property: hystrix.plugin.HystrixCommandExecutionHook.implementation" + ", serviceloader: META-INF/services/com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook" + ", property: hystrix.plugin.HystrixPropertiesStrategy.implementation" + ", serviceloader: META-INF/services/com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy]"); } void assertEvents(String expect) throws Exception { List<String> keys = getEvents(); String actual = keys.toString(); if (! actual.equals(expect)) { javaPrintList(System.out, keys); } assertEquals(expect, actual); } static List<String> getEvents() { return new ArrayList<String>(dynamicPropertyEvents); } static void javaPrintList(Appendable a, Iterable<String> list) throws IOException { boolean first = true; for (String o : list) { if (first) { a.append("\"["); first = false; } else { a.append("\""); a.append("\n+ \", "); } a.append(o); } a.append("]\""); } @Test(expected=ServiceConfigurationError.class) public void testDynamicPropertiesFailure() throws Exception { /* * James Bond: Do you expect me to talk? * Auric Goldfinger: No, Mr. Bond, I expect you to die! */ fakeServiceLoaderResource = "FAKE_META_INF_SERVICES/com.netflix.hystrix.strategy.properties.HystrixDynamicPropertiesFail"; HystrixPlugins plugins = setupMockServiceLoader(); plugins.getDynamicProperties(); } @Test public void testDynamicSystemProperties() throws Exception { //On the off chance this is the first test lets not screw up all the other tests HystrixPlugins.getInstance(); System.setProperty("hystrix.plugin.HystrixDynamicProperties.implementation", "com.netflix.hystrix.strategy.properties.HystrixDynamicPropertiesSystemProperties"); HystrixPlugins plugins = setupMockServiceLoader(); assertTrue(plugins.getDynamicProperties() instanceof HystrixDynamicPropertiesSystemProperties); HystrixDynamicProperties p = plugins.getDynamicProperties(); //Some minimum testing of system properties wrapper //this probably should be in its own test class. assertTrue(p.getBoolean("USE_DEFAULT", true).get()); assertEquals("string", p.getString("USE_DEFAULT", "string").get()); assertEquals(1L, p.getLong("USE_DEFAULT", 1L).get().longValue()); assertEquals(1, p.getInteger("USE_DEFAULT", 1).get().intValue()); assertNotNull(p.getString("path.separator", null).get()); assertEvents("[debug: [Created HystrixDynamicProperties instance from System property named \"hystrix.plugin.HystrixDynamicProperties.implementation\". Using class: {}, com.netflix.hystrix.strategy.properties.HystrixDynamicPropertiesSystemProperties]]"); System.clearProperty("hystrix.plugin.HystrixDynamicProperties.implementation"); } static String fakeServiceLoaderResource = "FAKE_META_INF_SERVICES/com.netflix.hystrix.strategy.properties.HystrixDynamicProperties"; private HystrixPlugins setupMockServiceLoader() throws Exception { final ClassLoader realLoader = HystrixPlugins.class.getClassLoader(); ClassLoader loader = new WrappedClassLoader(realLoader) { @Override public Enumeration<URL> getResources(String name) throws IOException { dynamicPropertyEvents.add("serviceloader: " + name); final Enumeration<URL> r; if (name.endsWith("META-INF/services/com.netflix.hystrix.strategy.properties.HystrixDynamicProperties")) { Vector<URL> vs = new Vector<URL>(); URL u = super.getResource(fakeServiceLoaderResource); vs.add(u); return vs.elements(); } else { r = super.getResources(name); } return r; } }; final Logger mockLogger = (Logger) Proxy.newProxyInstance(realLoader, new Class<?>[] {Logger.class}, new MockLoggerInvocationHandler()); return HystrixPlugins.create(loader, new LoggerSupplier() { @Override public Logger getLogger() { return mockLogger; } }); } static class MockLoggerInvocationHandler implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { dynamicPropertyEvents.offer(method.getName() + ": " + asList(args)); return null; } } static class WrappedClassLoader extends ClassLoader { final ClassLoader delegate; public WrappedClassLoader(ClassLoader delegate) { super(); this.delegate = delegate; } public Class<?> loadClass(String name) throws ClassNotFoundException { return delegate.loadClass(name); } public URL getResource(String name) { return delegate.getResource(name); } public Enumeration<URL> getResources(String name) throws IOException { return delegate.getResources(name); } public InputStream getResourceAsStream(String name) { return delegate.getResourceAsStream(name); } public void setDefaultAssertionStatus(boolean enabled) { delegate.setDefaultAssertionStatus(enabled); } public void setPackageAssertionStatus(String packageName, boolean enabled) { delegate.setPackageAssertionStatus(packageName, enabled); } public void setClassAssertionStatus(String className, boolean enabled) { delegate.setClassAssertionStatus(className, enabled); } public void clearAssertionStatus() { delegate.clearAssertionStatus(); } } private static class NoOpProperty<T> implements HystrixDynamicProperty<T> { @Override public T get() { return null; } @Override public void addCallback(Runnable callback) { } @Override public String getName() { return "NOP"; } } public static class MockHystrixDynamicPropertiesTest implements HystrixDynamicProperties { @Override public HystrixDynamicProperty<String> getString(String name, String fallback) { dynamicPropertyEvents.offer("property: " + name); return new NoOpProperty<String>(); } @Override public HystrixDynamicProperty<Integer> getInteger(String name, Integer fallback) { dynamicPropertyEvents.offer("property: " + name); return new NoOpProperty<Integer>(); } @Override public HystrixDynamicProperty<Long> getLong(String name, Long fallback) { dynamicPropertyEvents.offer("property: " + name); return new NoOpProperty<Long>(); } @Override public HystrixDynamicProperty<Boolean> getBoolean(String name, Boolean fallback) { dynamicPropertyEvents.offer("property: " + name); return new NoOpProperty<Boolean>(); } } /* @Test public void testCommandExecutionHookDefaultImpl() { HystrixCommandExecutionHook impl = HystrixPlugins.getInstance().getCommandExecutionHook(); assertTrue(impl instanceof HystrixCommandExecutionHookDefault); } @Test public void testCommandExecutionHookViaRegisterMethod() { HystrixPlugins.getInstance().registerCommandExecutionHook(new HystrixCommandExecutionHookTestImpl()); HystrixCommandExecutionHook impl = HystrixPlugins.getInstance().getCommandExecutionHook(); assertTrue(impl instanceof HystrixCommandExecutionHookTestImpl); }*/ public static class HystrixCommandExecutionHookTestImpl extends HystrixCommandExecutionHook { } /*@Test public void testEventNotifierDefaultImpl() { HystrixEventNotifier impl = HystrixPlugins.getInstance().getEventNotifier(); assertTrue(impl instanceof HystrixEventNotifierDefault); } @Test public void testEventNotifierViaRegisterMethod() { HystrixPlugins.getInstance().registerEventNotifier(new HystrixEventNotifierTestImpl()); HystrixEventNotifier impl = HystrixPlugins.getInstance().getEventNotifier(); assertTrue(impl instanceof HystrixEventNotifierTestImpl); } @Test public void testEventNotifierViaProperty() { try { String fullClass = HystrixEventNotifierTestImpl.class.getName(); System.setProperty("hystrix.plugin.HystrixEventNotifier.implementation", fullClass); HystrixEventNotifier impl = HystrixPlugins.getInstance().getEventNotifier(); assertTrue(impl instanceof HystrixEventNotifierTestImpl); } finally { System.clearProperty("hystrix.plugin.HystrixEventNotifier.implementation"); } }*/ // inside UnitTest so it is stripped from Javadocs public static class HystrixEventNotifierTestImpl extends HystrixEventNotifier { // just use defaults } /*@Test public void testConcurrencyStrategyDefaultImpl() { HystrixConcurrencyStrategy impl = HystrixPlugins.getInstance().getConcurrencyStrategy(); assertTrue(impl instanceof HystrixConcurrencyStrategyDefault); } @Test public void testConcurrencyStrategyViaRegisterMethod() { HystrixPlugins.getInstance().registerConcurrencyStrategy(new HystrixConcurrencyStrategyTestImpl()); HystrixConcurrencyStrategy impl = HystrixPlugins.getInstance().getConcurrencyStrategy(); assertTrue(impl instanceof HystrixConcurrencyStrategyTestImpl); } @Test public void testConcurrencyStrategyViaProperty() { try { String fullClass = HystrixConcurrencyStrategyTestImpl.class.getName(); System.setProperty("hystrix.plugin.HystrixConcurrencyStrategy.implementation", fullClass); HystrixConcurrencyStrategy impl = HystrixPlugins.getInstance().getConcurrencyStrategy(); assertTrue(impl instanceof HystrixConcurrencyStrategyTestImpl); } finally { System.clearProperty("hystrix.plugin.HystrixConcurrencyStrategy.implementation"); } }*/ // inside UnitTest so it is stripped from Javadocs public static class HystrixConcurrencyStrategyTestImpl extends HystrixConcurrencyStrategy { // just use defaults } /*@Test public void testMetricsPublisherDefaultImpl() { HystrixMetricsPublisher impl = HystrixPlugins.getInstance().getMetricsPublisher(); assertTrue(impl instanceof HystrixMetricsPublisherDefault); } @Test public void testMetricsPublisherViaRegisterMethod() { HystrixPlugins.getInstance().registerMetricsPublisher(new HystrixMetricsPublisherTestImpl()); HystrixMetricsPublisher impl = HystrixPlugins.getInstance().getMetricsPublisher(); assertTrue(impl instanceof HystrixMetricsPublisherTestImpl); } @Test public void testMetricsPublisherViaProperty() { try { String fullClass = HystrixMetricsPublisherTestImpl.class.getName(); System.setProperty("hystrix.plugin.HystrixMetricsPublisher.implementation", fullClass); HystrixMetricsPublisher impl = HystrixPlugins.getInstance().getMetricsPublisher(); assertTrue(impl instanceof HystrixMetricsPublisherTestImpl); } finally { System.clearProperty("hystrix.plugin.HystrixMetricsPublisher.implementation"); } }*/ // inside UnitTest so it is stripped from Javadocs public static class HystrixMetricsPublisherTestImpl extends HystrixMetricsPublisher { // just use defaults } /*@Test public void testPropertiesStrategyDefaultImpl() { HystrixPropertiesStrategy impl = HystrixPlugins.getInstance().getPropertiesStrategy(); assertTrue(impl instanceof HystrixPropertiesStrategyDefault); } @Test public void testPropertiesStrategyViaRegisterMethod() { HystrixPlugins.getInstance().registerPropertiesStrategy(new HystrixPropertiesStrategyTestImpl()); HystrixPropertiesStrategy impl = HystrixPlugins.getInstance().getPropertiesStrategy(); assertTrue(impl instanceof HystrixPropertiesStrategyTestImpl); } @Test public void testPropertiesStrategyViaProperty() { try { String fullClass = HystrixPropertiesStrategyTestImpl.class.getName(); System.setProperty("hystrix.plugin.HystrixPropertiesStrategy.implementation", fullClass); HystrixPropertiesStrategy impl = HystrixPlugins.getInstance().getPropertiesStrategy(); assertTrue(impl instanceof HystrixPropertiesStrategyTestImpl); } finally { System.clearProperty("hystrix.plugin.HystrixPropertiesStrategy.implementation"); } }*/ // inside UnitTest so it is stripped from Javadocs public static class HystrixPropertiesStrategyTestImpl extends HystrixPropertiesStrategy { // just use defaults } /*@Test public void testRequestContextViaPluginInTimeout() { HystrixPlugins.getInstance().registerConcurrencyStrategy(new HystrixConcurrencyStrategy() { @Override public <T> Callable<T> wrapCallable(final Callable<T> callable) { return new RequestIdCallable<T>(callable); } }); HystrixRequestContext context = HystrixRequestContext.initializeContext(); testRequestIdThreadLocal.set("foobar"); final AtomicReference<String> valueInTimeout = new AtomicReference<String>(); new DummyCommand().toObservable() .doOnError(new Action1<Throwable>() { @Override public void call(Throwable throwable) { System.out.println("initialized = " + HystrixRequestContext.isCurrentThreadInitialized()); System.out.println("requestId (timeout) = " + testRequestIdThreadLocal.get()); valueInTimeout.set(testRequestIdThreadLocal.get()); } }) .materialize() .toBlocking().single(); context.shutdown(); Hystrix.reset(); assertEquals("foobar", valueInTimeout.get()); }*/ private static class RequestIdCallable<T> implements Callable<T> { private final Callable<T> callable; private final String requestId; public RequestIdCallable(Callable<T> callable) { this.callable = callable; this.requestId = testRequestIdThreadLocal.get(); } @Override public T call() throws Exception { String original = testRequestIdThreadLocal.get(); testRequestIdThreadLocal.set(requestId); try { return callable.call(); } finally { testRequestIdThreadLocal.set(original); } } } private static final ThreadLocal<String> testRequestIdThreadLocal = new ThreadLocal<String>(); public static class DummyCommand extends HystrixCommand<Void> { public DummyCommand() { super(HystrixCommandGroupKey.Factory.asKey("Dummy")); } @Override protected Void run() throws Exception { System.out.println("requestId (run) = " + testRequestIdThreadLocal.get()); Thread.sleep(2000); return null; } } }
4,610
0
Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/strategy
Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/strategy/metrics/HystrixMetricsPublisherFactoryTest.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.strategy.metrics; import static junit.framework.Assert.assertNotSame; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicInteger; import com.netflix.hystrix.strategy.HystrixPlugins; import org.junit.Before; import org.junit.Test; 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.HystrixThreadPoolKey; import com.netflix.hystrix.HystrixThreadPoolMetrics; import com.netflix.hystrix.HystrixThreadPoolProperties; public class HystrixMetricsPublisherFactoryTest { @Before public void reset() { HystrixPlugins.reset(); } /** * Assert that we only call a publisher once for a given Command or ThreadPool key. */ @Test public void testSingleInitializePerKey() { final TestHystrixMetricsPublisher publisher = new TestHystrixMetricsPublisher(); HystrixPlugins.getInstance().registerMetricsPublisher(publisher); final HystrixMetricsPublisherFactory factory = new HystrixMetricsPublisherFactory(); ArrayList<Thread> threads = new ArrayList<Thread>(); for (int i = 0; i < 20; i++) { threads.add(new Thread(new Runnable() { @Override public void run() { factory.getPublisherForCommand(TestCommandKey.TEST_A, null, null, null, null); factory.getPublisherForCommand(TestCommandKey.TEST_B, null, null, null, null); factory.getPublisherForThreadPool(TestThreadPoolKey.TEST_A, null, null); } })); } // start them for (Thread t : threads) { t.start(); } // wait for them to finish for (Thread t : threads) { try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } } // we should see 2 commands and 1 threadPool publisher created assertEquals(2, publisher.commandCounter.get()); assertEquals(1, publisher.threadCounter.get()); } @Test public void testMetricsPublisherReset() { // precondition: HystrixMetricsPublisherFactory class is not loaded. Calling HystrixPlugins.reset() here should be good enough to run this with other tests. // set first custom publisher HystrixCommandKey key = HystrixCommandKey.Factory.asKey("key"); HystrixMetricsPublisherCommand firstCommand = new HystrixMetricsPublisherCommandDefault(key, null, null, null, null); HystrixMetricsPublisher firstPublisher = new CustomPublisher(firstCommand); HystrixPlugins.getInstance().registerMetricsPublisher(firstPublisher); // ensure that first custom publisher is used HystrixMetricsPublisherCommand cmd = HystrixMetricsPublisherFactory.createOrRetrievePublisherForCommand(key, null, null, null, null); assertSame(firstCommand, cmd); // reset, then change to second custom publisher HystrixPlugins.reset(); HystrixMetricsPublisherCommand secondCommand = new HystrixMetricsPublisherCommandDefault(key, null, null, null, null); HystrixMetricsPublisher secondPublisher = new CustomPublisher(secondCommand); HystrixPlugins.getInstance().registerMetricsPublisher(secondPublisher); // ensure that second custom publisher is used cmd = HystrixMetricsPublisherFactory.createOrRetrievePublisherForCommand(key, null, null, null, null); assertNotSame(firstCommand, cmd); assertSame(secondCommand, cmd); } private static class TestHystrixMetricsPublisher extends HystrixMetricsPublisher { AtomicInteger commandCounter = new AtomicInteger(); AtomicInteger threadCounter = new AtomicInteger(); @Override public HystrixMetricsPublisherCommand getMetricsPublisherForCommand(HystrixCommandKey commandKey, HystrixCommandGroupKey commandOwner, HystrixCommandMetrics metrics, HystrixCircuitBreaker circuitBreaker, HystrixCommandProperties properties) { return new HystrixMetricsPublisherCommand() { @Override public void initialize() { commandCounter.incrementAndGet(); } }; } @Override public HystrixMetricsPublisherThreadPool getMetricsPublisherForThreadPool(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolMetrics metrics, HystrixThreadPoolProperties properties) { return new HystrixMetricsPublisherThreadPool() { @Override public void initialize() { threadCounter.incrementAndGet(); } }; } } private static enum TestCommandKey implements HystrixCommandKey { TEST_A, TEST_B } private static enum TestThreadPoolKey implements HystrixThreadPoolKey { TEST_A, TEST_B } static class CustomPublisher extends HystrixMetricsPublisher{ private HystrixMetricsPublisherCommand commandToReturn; public CustomPublisher(HystrixMetricsPublisherCommand commandToReturn){ this.commandToReturn = commandToReturn; } @Override public HystrixMetricsPublisherCommand getMetricsPublisherForCommand(HystrixCommandKey commandKey, HystrixCommandGroupKey commandGroupKey, HystrixCommandMetrics metrics, HystrixCircuitBreaker circuitBreaker, HystrixCommandProperties properties) { return commandToReturn; } } }
4,611
0
Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/strategy
Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/strategy/concurrency/HystrixContextSchedulerTest.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.strategy.concurrency; import static org.junit.Assert.assertTrue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.Test; import rx.Scheduler; import rx.functions.Action0; import rx.schedulers.Schedulers; public class HystrixContextSchedulerTest { @Test(timeout = 2500) public void testUnsubscribeWrappedScheduler() throws InterruptedException { Scheduler s = Schedulers.newThread(); final AtomicBoolean interrupted = new AtomicBoolean(); final CountDownLatch start = new CountDownLatch(1); final CountDownLatch end = new CountDownLatch(1); HystrixContextScheduler hcs = new HystrixContextScheduler(s); 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(); assertTrue(interrupted.get()); } finally { w.unsubscribe(); } } }
4,612
0
Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/strategy
Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/strategy/concurrency/HystrixConcurrencyStrategyTest.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.strategy.concurrency; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.lang.IllegalStateException; import java.util.concurrent.atomic.AtomicBoolean; import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; import org.junit.After; import org.junit.Before; import org.junit.Test; import rx.functions.Action1; import rx.functions.Func1; import com.netflix.config.ConfigurationManager; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.HystrixRequestLog; public class HystrixConcurrencyStrategyTest { @Before public void prepareForTest() { /* we must call this to simulate a new request lifecycle running and clearing caches */ HystrixRequestContext.initializeContext(); } @After public void cleanup() { shutdownContextIfExists(); // force properties to be clean as well ConfigurationManager.getConfigInstance().clear(); } /** * If the RequestContext does not get transferred across threads correctly this blows up. * No specific assertions are necessary. */ @Test public void testRequestContextPropagatesAcrossObserveOnPool() { new SimpleCommand().execute(); new SimpleCommand().observe().map(new Func1<String, String>() { @Override public String call(String s) { System.out.println("Map => Commands: " + HystrixRequestLog.getCurrentRequest().getAllExecutedCommands()); return s; } }).toBlocking().forEach(new Action1<String>() { @Override public void call(String s) { System.out.println("Result [" + s + "] => Commands: " + HystrixRequestLog.getCurrentRequest().getAllExecutedCommands()); } }); } private static class SimpleCommand extends HystrixCommand<String> { public SimpleCommand() { super(HystrixCommandGroupKey.Factory.asKey("SimpleCommand")); } @Override protected String run() throws Exception { if (HystrixRequestContext.isCurrentThreadInitialized()) { System.out.println("Executing => Commands: " + HystrixRequestLog.getCurrentRequest().getAllExecutedCommands()); } return "Hello"; } } @Test public void testThreadContextOnTimeout() { final AtomicBoolean isInitialized = new AtomicBoolean(); new TimeoutCommand().toObservable() .doOnError(new Action1<Throwable>() { @Override public void call(Throwable throwable) { isInitialized.set(HystrixRequestContext.isCurrentThreadInitialized()); } }) .materialize() .toBlocking().single(); System.out.println("initialized = " + HystrixRequestContext.isCurrentThreadInitialized()); System.out.println("initialized inside onError = " + isInitialized.get()); assertEquals(true, isInitialized.get()); } @Test public void testNoRequestContextOnSimpleConcurencyStrategyWithoutException() throws Exception { shutdownContextIfExists(); ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.requestLog.enabled", "false"); new SimpleCommand().execute(); assertTrue("We are able to run the simple command without a context initialization error.", true); } private void shutdownContextIfExists() { // instead of storing the reference from initialize we'll just get the current state and shutdown if (HystrixRequestContext.getContextForCurrentThread() != null) { // it could have been set NULL by the test HystrixRequestContext.getContextForCurrentThread().shutdown(); } } private static class DummyHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy {} public static class TimeoutCommand extends HystrixCommand<Void> { static final HystrixCommand.Setter properties = HystrixCommand.Setter .withGroupKey(HystrixCommandGroupKey.Factory.asKey("TimeoutTest")) .andCommandPropertiesDefaults(HystrixCommandProperties.Setter() .withExecutionTimeoutInMilliseconds(50)); public TimeoutCommand() { super(properties); } @Override protected Void run() throws Exception { Thread.sleep(500); return null; } } }
4,613
0
Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/strategy
Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/strategy/properties/HystrixPropertyTest.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.strategy.properties; import static org.junit.Assert.assertEquals; import org.junit.Test; import com.netflix.hystrix.strategy.properties.HystrixProperty.Factory; public class HystrixPropertyTest { @Test public void testNested1() { HystrixProperty<String> a = Factory.asProperty("a"); assertEquals("a", a.get()); HystrixProperty<String> aWithDefault = Factory.asProperty(a, "b"); assertEquals("a", aWithDefault.get()); } @Test public void testNested2() { HystrixProperty<String> nullValue = Factory.nullProperty(); HystrixProperty<String> withDefault = Factory.asProperty(nullValue, "b"); assertEquals("b", withDefault.get()); } @Test public void testNested3() { HystrixProperty<String> nullValue = Factory.nullProperty(); HystrixProperty<String> a = Factory.asProperty(nullValue, "a"); HystrixProperty<String> withDefault = Factory.asProperty(a, "b"); assertEquals("a", withDefault.get()); } @Test public void testNested4() { HystrixProperty<String> nullValue = Factory.nullProperty(); HystrixProperty<String> a = Factory.asProperty(nullValue, null); HystrixProperty<String> withDefault = Factory.asProperty(a, "b"); assertEquals("b", withDefault.get()); } @Test public void testNested5() { HystrixProperty<String> nullValue = Factory.nullProperty(); HystrixProperty<String> a = Factory.asProperty(nullValue, null); @SuppressWarnings("unchecked") HystrixProperty<String> withDefault = Factory.asProperty(a, Factory.asProperty("b")); assertEquals("b", withDefault.get()); } @Test public void testSeries1() { HystrixProperty<String> nullValue = Factory.nullProperty(); HystrixProperty<String> a = Factory.asProperty(nullValue, null); @SuppressWarnings("unchecked") HystrixProperty<String> withDefault = Factory.asProperty(a, nullValue, nullValue, Factory.asProperty("b")); assertEquals("b", withDefault.get()); } @Test public void testSeries2() { HystrixProperty<String> nullValue = Factory.nullProperty(); HystrixProperty<String> a = Factory.asProperty(nullValue, null); @SuppressWarnings("unchecked") HystrixProperty<String> withDefault = Factory.asProperty(a, nullValue, Factory.asProperty("b"), nullValue, Factory.asProperty("c")); assertEquals("b", withDefault.get()); } }
4,614
0
Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/strategy
Create_ds/Hystrix/hystrix-core/src/test/java/com/netflix/hystrix/strategy/properties/HystrixPropertiesChainedArchaiusPropertyTest.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.strategy.properties; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.concurrent.atomic.AtomicInteger; import org.junit.After; import org.junit.Test; import com.netflix.config.ConfigurationManager; import com.netflix.hystrix.strategy.properties.HystrixPropertiesChainedArchaiusProperty.DynamicBooleanProperty; import com.netflix.hystrix.strategy.properties.HystrixPropertiesChainedArchaiusProperty.DynamicIntegerProperty; import com.netflix.hystrix.strategy.properties.HystrixPropertiesChainedArchaiusProperty.DynamicStringProperty; import com.netflix.hystrix.strategy.properties.HystrixPropertiesChainedArchaiusProperty.IntegerProperty; import com.netflix.hystrix.strategy.properties.HystrixPropertiesChainedArchaiusProperty.StringProperty; public class HystrixPropertiesChainedArchaiusPropertyTest { @After public void cleanUp() { // Tests which use ConfigurationManager.getConfigInstance() will leave the singleton in an initialize state, // this will leave the singleton in a reasonable state between tests. ConfigurationManager.getConfigInstance().clear(); } @Test public void testString() throws Exception { DynamicStringProperty pString = new DynamicStringProperty("defaultString", "default-default"); HystrixPropertiesChainedArchaiusProperty.StringProperty fString = new HystrixPropertiesChainedArchaiusProperty.StringProperty("overrideString", pString); assertTrue("default-default".equals(fString.get())); ConfigurationManager.getConfigInstance().setProperty("defaultString", "default"); assertTrue("default".equals(fString.get())); ConfigurationManager.getConfigInstance().setProperty("overrideString", "override"); assertTrue("override".equals(fString.get())); ConfigurationManager.getConfigInstance().clearProperty("overrideString"); assertTrue("default".equals(fString.get())); ConfigurationManager.getConfigInstance().clearProperty("defaultString"); assertTrue("default-default".equals(fString.get())); } @Test public void testInteger() throws Exception { DynamicIntegerProperty pInt = new DynamicIntegerProperty("defaultInt", -1); HystrixPropertiesChainedArchaiusProperty.IntegerProperty fInt = new HystrixPropertiesChainedArchaiusProperty.IntegerProperty("overrideInt", pInt); assertTrue(-1 == fInt.get()); ConfigurationManager.getConfigInstance().setProperty("defaultInt", 10); assertTrue(10 == fInt.get()); ConfigurationManager.getConfigInstance().setProperty("overrideInt", 11); assertTrue(11 == fInt.get()); ConfigurationManager.getConfigInstance().clearProperty("overrideInt"); assertTrue(10 == fInt.get()); ConfigurationManager.getConfigInstance().clearProperty("defaultInt"); assertTrue(-1 == fInt.get()); } @Test public void testBoolean() throws Exception { DynamicBooleanProperty pBoolean = new DynamicBooleanProperty("defaultBoolean", true); HystrixPropertiesChainedArchaiusProperty.BooleanProperty fBoolean = new HystrixPropertiesChainedArchaiusProperty.BooleanProperty("overrideBoolean", pBoolean); System.out.println("pBoolean: " + pBoolean.get()); System.out.println("fBoolean: " + fBoolean.get()); assertTrue(fBoolean.get()); ConfigurationManager.getConfigInstance().setProperty("defaultBoolean", Boolean.FALSE); System.out.println("pBoolean: " + pBoolean.get()); System.out.println("fBoolean: " + fBoolean.get()); assertFalse(fBoolean.get()); ConfigurationManager.getConfigInstance().setProperty("overrideBoolean", Boolean.TRUE); assertTrue(fBoolean.get()); ConfigurationManager.getConfigInstance().clearProperty("overrideBoolean"); assertFalse(fBoolean.get()); ConfigurationManager.getConfigInstance().clearProperty("defaultBoolean"); assertTrue(fBoolean.get()); } @Test public void testChainingString() throws Exception { DynamicStringProperty node1 = new DynamicStringProperty("node1", "v1"); StringProperty node2 = new HystrixPropertiesChainedArchaiusProperty.StringProperty("node2", node1); HystrixPropertiesChainedArchaiusProperty.StringProperty node3 = new HystrixPropertiesChainedArchaiusProperty.StringProperty("node3", node2); assertTrue("" + node3.get(), "v1".equals(node3.get())); ConfigurationManager.getConfigInstance().setProperty("node1", "v11"); assertTrue("v11".equals(node3.get())); ConfigurationManager.getConfigInstance().setProperty("node2", "v22"); assertTrue("v22".equals(node3.get())); ConfigurationManager.getConfigInstance().clearProperty("node1"); assertTrue("v22".equals(node3.get())); ConfigurationManager.getConfigInstance().setProperty("node3", "v33"); assertTrue("v33".equals(node3.get())); ConfigurationManager.getConfigInstance().clearProperty("node2"); assertTrue("v33".equals(node3.get())); ConfigurationManager.getConfigInstance().setProperty("node2", "v222"); assertTrue("v33".equals(node3.get())); ConfigurationManager.getConfigInstance().clearProperty("node3"); assertTrue("v222".equals(node3.get())); ConfigurationManager.getConfigInstance().clearProperty("node2"); assertTrue("v1".equals(node3.get())); ConfigurationManager.getConfigInstance().setProperty("node2", "v2222"); assertTrue("v2222".equals(node3.get())); } @Test public void testChainingInteger() throws Exception { DynamicIntegerProperty node1 = new DynamicIntegerProperty("node1", 1); IntegerProperty node2 = new HystrixPropertiesChainedArchaiusProperty.IntegerProperty("node2", node1); HystrixPropertiesChainedArchaiusProperty.IntegerProperty node3 = new HystrixPropertiesChainedArchaiusProperty.IntegerProperty("node3", node2); assertTrue("" + node3.get(), 1 == node3.get()); ConfigurationManager.getConfigInstance().setProperty("node1", 11); assertTrue(11 == node3.get()); ConfigurationManager.getConfigInstance().setProperty("node2", 22); assertTrue(22 == node3.get()); ConfigurationManager.getConfigInstance().clearProperty("node1"); assertTrue(22 == node3.get()); ConfigurationManager.getConfigInstance().setProperty("node3", 33); assertTrue(33 == node3.get()); ConfigurationManager.getConfigInstance().clearProperty("node2"); assertTrue(33 == node3.get()); ConfigurationManager.getConfigInstance().setProperty("node2", 222); assertTrue(33 == node3.get()); ConfigurationManager.getConfigInstance().clearProperty("node3"); assertTrue(222 == node3.get()); ConfigurationManager.getConfigInstance().clearProperty("node2"); assertTrue(1 == node3.get()); ConfigurationManager.getConfigInstance().setProperty("node2", 2222); assertTrue(2222 == node3.get()); } @Test public void testAddCallback() throws Exception { final DynamicStringProperty node1 = new DynamicStringProperty("n1", "n1"); final HystrixPropertiesChainedArchaiusProperty.StringProperty node2 = new HystrixPropertiesChainedArchaiusProperty.StringProperty("n2", node1); final AtomicInteger callbackCount = new AtomicInteger(0); node2.addCallback(new Runnable() { @Override public void run() { callbackCount.incrementAndGet(); } }); assertTrue(0 == callbackCount.get()); assertTrue("n1".equals(node2.get())); assertTrue(0 == callbackCount.get()); ConfigurationManager.getConfigInstance().setProperty("n1", "n11"); assertTrue("n11".equals(node2.get())); assertTrue(0 == callbackCount.get()); ConfigurationManager.getConfigInstance().setProperty("n2", "n22"); assertTrue("n22".equals(node2.get())); assertTrue(1 == callbackCount.get()); ConfigurationManager.getConfigInstance().clearProperty("n1"); assertTrue("n22".equals(node2.get())); assertTrue(1 == callbackCount.get()); ConfigurationManager.getConfigInstance().setProperty("n2", "n222"); assertTrue("n222".equals(node2.get())); assertTrue(2 == callbackCount.get()); ConfigurationManager.getConfigInstance().clearProperty("n2"); assertTrue("n1".equals(node2.get())); assertTrue(3 == callbackCount.get()); } }
4,615
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixCommandGroupKey.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; import com.netflix.hystrix.util.InternMap; /** * A group name for a {@link HystrixCommand}. This is used for grouping together commands such as for reporting, alerting, dashboards or team/library ownership. * <p> * By default this will be used to define the {@link HystrixThreadPoolKey} unless a separate one is defined. * <p> * This interface is intended to work natively with Enums so that implementing code can have an enum with the owners that implements this interface. */ public interface HystrixCommandGroupKey extends HystrixKey { class Factory { private Factory() { } // used to intern instances so we don't keep re-creating them millions of times for the same key private static final InternMap<String, HystrixCommandGroupDefault> intern = new InternMap<String, HystrixCommandGroupDefault>( new InternMap.ValueConstructor<String, HystrixCommandGroupDefault>() { @Override public HystrixCommandGroupDefault create(String key) { return new HystrixCommandGroupDefault(key); } }); /** * Retrieve (or create) an interned HystrixCommandGroup instance for a given name. * * @param name command group name * @return HystrixCommandGroup instance that is interned (cached) so a given name will always retrieve the same instance. */ public static HystrixCommandGroupKey asKey(String name) { return intern.interned(name); } private static class HystrixCommandGroupDefault extends HystrixKey.HystrixKeyDefault implements HystrixCommandGroupKey { public HystrixCommandGroupDefault(String name) { super(name); } } /* package-private */ static int getGroupCount() { return intern.size(); } } }
4,616
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixCollapser.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; import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy; import com.netflix.hystrix.collapser.CollapserTimer; import com.netflix.hystrix.collapser.HystrixCollapserBridge; import com.netflix.hystrix.collapser.RealCollapserTimer; import com.netflix.hystrix.collapser.RequestCollapser; import com.netflix.hystrix.collapser.RequestCollapserFactory; import com.netflix.hystrix.exception.HystrixRuntimeException; import com.netflix.hystrix.strategy.HystrixPlugins; import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherFactory; import com.netflix.hystrix.strategy.properties.HystrixPropertiesFactory; import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Scheduler; import rx.Subscription; import rx.functions.Action0; import rx.functions.Action1; import rx.functions.Func0; import rx.schedulers.Schedulers; import rx.subjects.ReplaySubject; import java.util.Collection; import java.util.Collections; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Future; /** * Collapse multiple requests into a single {@link HystrixCommand} execution based on a time window and optionally a max batch size. * <p> * This allows an object model to have multiple calls to the command that execute/queue many times in a short period (milliseconds) and have them all get batched into a single backend call. * <p> * Typically the time window is something like 10ms give or take. * <p> * NOTE: Do NOT retain any state within instances of this class. * <p> * It must be stateless or else it will be non-deterministic because most instances are discarded while some are retained and become the * "collapsers" for all the ones that are discarded. * * @param <BatchReturnType> * The type returned from the {@link HystrixCommand} that will be invoked on batch executions. * @param <ResponseType> * The type returned from this command. * @param <RequestArgumentType> * The type of the request argument. If multiple arguments are needed, wrap them in another object or a Tuple. */ public abstract class HystrixCollapser<BatchReturnType, ResponseType, RequestArgumentType> implements HystrixExecutable<ResponseType>, HystrixObservable<ResponseType> { static final Logger logger = LoggerFactory.getLogger(HystrixCollapser.class); private final RequestCollapserFactory<BatchReturnType, ResponseType, RequestArgumentType> collapserFactory; private final HystrixRequestCache requestCache; private final HystrixCollapserBridge<BatchReturnType, ResponseType, RequestArgumentType> collapserInstanceWrapper; private final HystrixCollapserMetrics metrics; /** * The scope of request collapsing. * <ul> * <li>REQUEST: Requests within the scope of a {@link HystrixRequestContext} will be collapsed. * <p> * Typically this means that requests within a single user-request (ie. HTTP request) are collapsed. No interaction with other user requests. 1 queue per user request. * </li> * <li>GLOBAL: Requests from any thread (ie. all HTTP requests) within the JVM will be collapsed. 1 queue for entire app.</li> * </ul> */ public static enum Scope implements RequestCollapserFactory.Scope { REQUEST, GLOBAL } /** * Collapser with default {@link HystrixCollapserKey} derived from the implementing class name and scoped to {@link Scope#REQUEST} and default configuration. */ protected HystrixCollapser() { this(Setter.withCollapserKey(null).andScope(Scope.REQUEST)); } /** * Collapser scoped to {@link Scope#REQUEST} and default configuration. * * @param collapserKey * {@link HystrixCollapserKey} that identifies this collapser and provides the key used for retrieving properties, request caches, publishing metrics etc. */ protected HystrixCollapser(HystrixCollapserKey collapserKey) { this(Setter.withCollapserKey(collapserKey).andScope(Scope.REQUEST)); } /** * Construct a {@link HystrixCollapser} with defined {@link Setter} that allows * injecting property and strategy overrides and other optional arguments. * <p> * Null values will result in the default being used. * * @param setter * Fluent interface for constructor arguments */ protected HystrixCollapser(Setter setter) { this(setter.collapserKey, setter.scope, new RealCollapserTimer(), setter.propertiesSetter, null); } /* package for tests */ HystrixCollapser(HystrixCollapserKey collapserKey, Scope scope, CollapserTimer timer, HystrixCollapserProperties.Setter propertiesBuilder) { this(collapserKey, scope, timer, propertiesBuilder, null); } /* package for tests */ HystrixCollapser(HystrixCollapserKey collapserKey, Scope scope, CollapserTimer timer, HystrixCollapserProperties.Setter propertiesBuilder, HystrixCollapserMetrics metrics) { if (collapserKey == null || collapserKey.name().trim().equals("")) { String defaultKeyName = getDefaultNameFromClass(getClass()); collapserKey = HystrixCollapserKey.Factory.asKey(defaultKeyName); } HystrixCollapserProperties properties = HystrixPropertiesFactory.getCollapserProperties(collapserKey, propertiesBuilder); this.collapserFactory = new RequestCollapserFactory<BatchReturnType, ResponseType, RequestArgumentType>(collapserKey, scope, timer, properties); this.requestCache = HystrixRequestCache.getInstance(collapserKey, HystrixPlugins.getInstance().getConcurrencyStrategy()); if (metrics == null) { this.metrics = HystrixCollapserMetrics.getInstance(collapserKey, properties); } else { this.metrics = metrics; } final HystrixCollapser<BatchReturnType, ResponseType, RequestArgumentType> self = this; /* strategy: HystrixMetricsPublisherCollapser */ HystrixMetricsPublisherFactory.createOrRetrievePublisherForCollapser(collapserKey, this.metrics, properties); /** * Used to pass public method invocation to the underlying implementation in a separate package while leaving the methods 'protected' in this class. */ collapserInstanceWrapper = new HystrixCollapserBridge<BatchReturnType, ResponseType, RequestArgumentType>() { @Override public Collection<Collection<CollapsedRequest<ResponseType, RequestArgumentType>>> shardRequests(Collection<CollapsedRequest<ResponseType, RequestArgumentType>> requests) { Collection<Collection<CollapsedRequest<ResponseType, RequestArgumentType>>> shards = self.shardRequests(requests); self.metrics.markShards(shards.size()); return shards; } @Override public Observable<BatchReturnType> createObservableCommand(Collection<CollapsedRequest<ResponseType, RequestArgumentType>> requests) { final HystrixCommand<BatchReturnType> command = self.createCommand(requests); command.markAsCollapsedCommand(this.getCollapserKey(), requests.size()); self.metrics.markBatch(requests.size()); return command.toObservable(); } @Override public Observable<Void> mapResponseToRequests(Observable<BatchReturnType> batchResponse, final Collection<CollapsedRequest<ResponseType, RequestArgumentType>> requests) { return batchResponse.single().doOnNext(new Action1<BatchReturnType>() { @Override public void call(BatchReturnType batchReturnType) { // this is a blocking call in HystrixCollapser self.mapResponseToRequests(batchReturnType, requests); } }).ignoreElements().cast(Void.class); } @Override public HystrixCollapserKey getCollapserKey() { return self.getCollapserKey(); } }; } private HystrixCollapserProperties getProperties() { return collapserFactory.getProperties(); } /** * Key of the {@link HystrixCollapser} used for properties, metrics, caches, reporting etc. * * @return {@link HystrixCollapserKey} identifying this {@link HystrixCollapser} instance */ public HystrixCollapserKey getCollapserKey() { return collapserFactory.getCollapserKey(); } /** * Scope of collapsing. * <p> * <ul> * <li>REQUEST: Requests within the scope of a {@link HystrixRequestContext} will be collapsed. * <p> * Typically this means that requests within a single user-request (ie. HTTP request) are collapsed. No interaction with other user requests. 1 queue per user request. * </li> * <li>GLOBAL: Requests from any thread (ie. all HTTP requests) within the JVM will be collapsed. 1 queue for entire app.</li> * </ul> * <p> * Default: {@link Scope#REQUEST} (defined via constructor) * * @return {@link Scope} that collapsing should be performed within. */ public Scope getScope() { return Scope.valueOf(collapserFactory.getScope().name()); } /** * Return the {@link HystrixCollapserMetrics} for this collapser * @return {@link HystrixCollapserMetrics} for this collapser */ public HystrixCollapserMetrics getMetrics() { return metrics; } /** * The request arguments to be passed to the {@link HystrixCommand}. * <p> * Typically this means to take the argument(s) provided to the constructor and return it here. * <p> * If there are multiple arguments that need to be bundled, create a single object to contain them, or use a Tuple. * * @return RequestArgumentType */ public abstract RequestArgumentType getRequestArgument(); /** * Factory method to create a new {@link HystrixCommand}{@code <BatchReturnType>} command object each time a batch needs to be executed. * <p> * Do not return the same instance each time. Return a new instance on each invocation. * <p> * Process the 'requests' argument into the arguments the command object needs to perform its work. * <p> * If a batch or requests needs to be split (sharded) into multiple commands, see {@link #shardRequests} <p> * IMPLEMENTATION NOTE: Be fast (ie. <1ms) in this method otherwise it can block the Timer from executing subsequent batches. Do not do any processing beyond constructing the command and returning * it. * * @param requests * {@code Collection<CollapsedRequest<ResponseType, RequestArgumentType>>} containing {@link CollapsedRequest} objects containing the arguments of each request collapsed in this batch. * @return {@link HystrixCommand}{@code <BatchReturnType>} which when executed will retrieve results for the batch of arguments as found in the Collection of {@link CollapsedRequest} objects */ protected abstract HystrixCommand<BatchReturnType> createCommand(Collection<CollapsedRequest<ResponseType, RequestArgumentType>> requests); /** * Override to split (shard) a batch of requests into multiple batches that will each call <code>createCommand</code> separately. * <p> * The purpose of this is to allow collapsing to work for services that have sharded backends and batch executions that need to be shard-aware. * <p> * For example, a batch of 100 requests could be split into 4 different batches sharded on name (ie. a-g, h-n, o-t, u-z) that each result in a separate {@link HystrixCommand} being created and * executed for them. * <p> * By default this method does nothing to the Collection and is a pass-thru. * * @param requests * {@code Collection<CollapsedRequest<ResponseType, RequestArgumentType>>} containing {@link CollapsedRequest} objects containing the arguments of each request collapsed in this batch. * @return Collection of {@code Collection<CollapsedRequest<ResponseType, RequestArgumentType>>} objects sharded according to business rules. * <p>The CollapsedRequest instances should not be modified or wrapped as the CollapsedRequest instance object contains state information needed to complete the execution. */ protected Collection<Collection<CollapsedRequest<ResponseType, RequestArgumentType>>> shardRequests(Collection<CollapsedRequest<ResponseType, RequestArgumentType>> requests) { return Collections.singletonList(requests); } /** * Executed after the {@link HystrixCommand}{@code <BatchReturnType>} command created by {@link #createCommand} finishes processing (unless it fails) for mapping the {@code <BatchReturnType>} to * the list of {@code CollapsedRequest<ResponseType, RequestArgumentType>} objects. * <p> * IMPORTANT IMPLEMENTATION DETAIL => The expected contract (responsibilities) of this method implementation is: * <p> * <ul> * <li>ALL {@link CollapsedRequest} objects must have either a response or exception set on them even if the response is NULL * otherwise the user thread waiting on the response will think a response was never received and will either block indefinitely or timeout while waiting.</li> * <ul> * <li>Setting a response is done via {@link CollapsedRequest#setResponse(Object)}</li> * <li>Setting an exception is done via {@link CollapsedRequest#setException(Exception)}</li> * </ul> * </ul> * <p> * Common code when {@code <BatchReturnType>} is {@code List<ResponseType>} is: * <p> * * <pre> * int count = 0; * for ({@code CollapsedRequest<ResponseType, RequestArgumentType>} request : requests) { * &nbsp;&nbsp;&nbsp;&nbsp; request.setResponse(batchResponse.get(count++)); * } * </pre> * * For example if the types were {@code <List<String>, String, String>}: * <p> * * <pre> * int count = 0; * for ({@code CollapsedRequest<String, String>} request : requests) { * &nbsp;&nbsp;&nbsp;&nbsp; request.setResponse(batchResponse.get(count++)); * } * </pre> * * @param batchResponse * The {@code <BatchReturnType>} returned from the {@link HystrixCommand}{@code <BatchReturnType>} command created by {@link #createCommand}. * <p> * * @param requests * {@code Collection<CollapsedRequest<ResponseType, RequestArgumentType>>} containing {@link CollapsedRequest} objects containing the arguments of each request collapsed in this batch. * <p> * The {@link CollapsedRequest#setResponse(Object)} or {@link CollapsedRequest#setException(Exception)} must be called on each {@link CollapsedRequest} in the Collection. */ protected abstract void mapResponseToRequests(BatchReturnType batchResponse, Collection<CollapsedRequest<ResponseType, RequestArgumentType>> requests); /** * Used for asynchronous execution with a callback by subscribing to the {@link Observable}. * <p> * This eagerly starts execution the same as {@link #queue()} and {@link #execute()}. * A lazy {@link Observable} can be obtained from {@link #toObservable()}. * <p> * <b>Callback Scheduling</b> * <p> * <ul> * <li>When using {@link ExecutionIsolationStrategy#THREAD} this defaults to using {@link Schedulers#computation()} for callbacks.</li> * <li>When using {@link ExecutionIsolationStrategy#SEMAPHORE} this defaults to using {@link Schedulers#immediate()} for callbacks.</li> * </ul> * Use {@link #toObservable(rx.Scheduler)} to schedule the callback differently. * <p> * See https://github.com/Netflix/RxJava/wiki for more information. * * @return {@code Observable<R>} that executes and calls back with the result of of {@link HystrixCommand}{@code <BatchReturnType>} execution after passing through {@link #mapResponseToRequests} * to transform the {@code <BatchReturnType>} into {@code <ResponseType>} */ public Observable<ResponseType> observe() { // use a ReplaySubject to buffer the eagerly subscribed-to Observable ReplaySubject<ResponseType> subject = ReplaySubject.create(); // eagerly kick off subscription final Subscription underlyingSubscription = toObservable().subscribe(subject); // return the subject that can be subscribed to later while the execution has already started return subject.doOnUnsubscribe(new Action0() { @Override public void call() { underlyingSubscription.unsubscribe(); } }); } /** * A lazy {@link Observable} that will execute when subscribed to. * <p> * <b>Callback Scheduling</b> * <p> * <ul> * <li>When using {@link ExecutionIsolationStrategy#THREAD} this defaults to using {@link Schedulers#computation()} for callbacks.</li> * <li>When using {@link ExecutionIsolationStrategy#SEMAPHORE} this defaults to using {@link Schedulers#immediate()} for callbacks.</li> * </ul> * <p> * See https://github.com/Netflix/RxJava/wiki for more information. * * @return {@code Observable<R>} that lazily executes and calls back with the result of of {@link HystrixCommand}{@code <BatchReturnType>} execution after passing through * {@link #mapResponseToRequests} to transform the {@code <BatchReturnType>} into {@code <ResponseType>} */ public Observable<ResponseType> toObservable() { // when we callback with the data we want to do the work // on a separate thread than the one giving us the callback return toObservable(Schedulers.computation()); } /** * A lazy {@link Observable} that will execute when subscribed to. * <p> * See https://github.com/Netflix/RxJava/wiki for more information. * * @param observeOn * The {@link Scheduler} to execute callbacks on. * @return {@code Observable<R>} that lazily executes and calls back with the result of of {@link HystrixCommand}{@code <BatchReturnType>} execution after passing through * {@link #mapResponseToRequests} to transform the {@code <BatchReturnType>} into {@code <ResponseType>} */ public Observable<ResponseType> toObservable(Scheduler observeOn) { return Observable.defer(new Func0<Observable<ResponseType>>() { @Override public Observable<ResponseType> call() { final boolean isRequestCacheEnabled = getProperties().requestCacheEnabled().get(); final String cacheKey = getCacheKey(); /* try from cache first */ if (isRequestCacheEnabled) { HystrixCachedObservable<ResponseType> fromCache = requestCache.get(cacheKey); if (fromCache != null) { metrics.markResponseFromCache(); return fromCache.toObservable(); } } RequestCollapser<BatchReturnType, ResponseType, RequestArgumentType> requestCollapser = collapserFactory.getRequestCollapser(collapserInstanceWrapper); Observable<ResponseType> response = requestCollapser.submitRequest(getRequestArgument()); if (isRequestCacheEnabled && cacheKey != null) { HystrixCachedObservable<ResponseType> toCache = HystrixCachedObservable.from(response); HystrixCachedObservable<ResponseType> fromCache = requestCache.putIfAbsent(cacheKey, toCache); if (fromCache == null) { return toCache.toObservable(); } else { toCache.unsubscribe(); return fromCache.toObservable(); } } return response; } }); } /** * Used for synchronous execution. * <p> * If {@link Scope#REQUEST} is being used then synchronous execution will only result in collapsing if other threads are running within the same scope. * * @return ResponseType * Result of {@link HystrixCommand}{@code <BatchReturnType>} execution after passing through {@link #mapResponseToRequests} to transform the {@code <BatchReturnType>} into * {@code <ResponseType>} * @throws HystrixRuntimeException * if an error occurs and a fallback cannot be retrieved */ public ResponseType execute() { try { return queue().get(); } catch (Throwable e) { if (e instanceof HystrixRuntimeException) { throw (HystrixRuntimeException) e; } // if we have an exception we know about we'll throw it directly without the threading wrapper exception if (e.getCause() instanceof HystrixRuntimeException) { throw (HystrixRuntimeException) e.getCause(); } // we don't know what kind of exception this is so create a generic message and throw a new HystrixRuntimeException String message = getClass().getSimpleName() + " HystrixCollapser failed while executing."; logger.debug(message, e); // debug only since we're throwing the exception and someone higher will do something with it //TODO should this be made a HystrixRuntimeException? throw new RuntimeException(message, e); } } /** * Used for asynchronous execution. * <p> * This will queue up the command and return a Future to get the result once it completes. * * @return ResponseType * Result of {@link HystrixCommand}{@code <BatchReturnType>} execution after passing through {@link #mapResponseToRequests} to transform the {@code <BatchReturnType>} into * {@code <ResponseType>} * @throws HystrixRuntimeException * within an <code>ExecutionException.getCause()</code> (thrown by {@link Future#get}) if an error occurs and a fallback cannot be retrieved */ public Future<ResponseType> queue() { return toObservable() .toBlocking() .toFuture(); } /** * Key to be used for request caching. * <p> * By default this returns null which means "do not cache". * <p> * To enable caching override this method and return a string key uniquely representing the state of a command instance. * <p> * If multiple command instances in the same request scope match keys then only the first will be executed and all others returned from cache. * * @return String cacheKey or null if not to cache */ protected String getCacheKey() { return null; } /** * Clears all state. If new requests come in instances will be recreated and metrics started from scratch. */ /* package */static void reset() { RequestCollapserFactory.reset(); } private static String getDefaultNameFromClass(@SuppressWarnings("rawtypes") Class<? extends HystrixCollapser> cls) { String fromCache = defaultNameCache.get(cls); if (fromCache != null) { return fromCache; } // generate the default // default HystrixCommandKey to use if the method is not overridden String name = cls.getSimpleName(); if (name.equals("")) { // we don't have a SimpleName (anonymous inner class) so use the full class name name = cls.getName(); name = name.substring(name.lastIndexOf('.') + 1, name.length()); } defaultNameCache.put(cls, name); return name; } /** * A request argument RequestArgumentType that was collapsed for batch processing and needs a response ResponseType set on it by the <code>executeBatch</code> implementation. */ public interface CollapsedRequest<ResponseType, RequestArgumentType> { /** * The request argument passed into the {@link HystrixCollapser} instance constructor which was then collapsed. * * @return RequestArgumentType */ RequestArgumentType getArgument(); /** * This corresponds in a OnNext(Response); OnCompleted pair of emissions. It represents a single-value usecase. * * @throws IllegalStateException * if called more than once or after setException/setComplete. * @param response * ResponseType */ void setResponse(ResponseType response); /** * When invoked, any Observer will be OnNexted this value * @throws IllegalStateException * if called after setException/setResponse/setComplete. * @param response */ void emitResponse(ResponseType response); /** * When set, any Observer will be OnErrored this exception * * @param exception exception to set on response * @throws IllegalStateException * if called more than once or after setResponse/setComplete. */ void setException(Exception exception); /** * When set, any Observer will have an OnCompleted emitted. * The intent is to use if after a series of emitResponses * * Note that, unlike the other 3 methods above, this method does not throw an IllegalStateException. * This allows Hystrix-core to unilaterally call it without knowing the internal state. */ void setComplete(); } /** * Fluent interface for arguments to the {@link HystrixCollapser} constructor. * <p> * The required arguments are set via the 'with' factory method and optional arguments via the 'and' chained methods. * <p> * Example: * <pre> {@code * Setter.withCollapserKey(HystrixCollapserKey.Factory.asKey("CollapserName")) .andScope(Scope.REQUEST); * } </pre> * * @NotThreadSafe */ public static class Setter { private final HystrixCollapserKey collapserKey; private Scope scope = Scope.REQUEST; // default if nothing is set private HystrixCollapserProperties.Setter propertiesSetter; private Setter(HystrixCollapserKey collapserKey) { this.collapserKey = collapserKey; } /** * Setter factory method containing required values. * <p> * All optional arguments can be set via the chained methods. * * @param collapserKey * {@link HystrixCollapserKey} that identifies this collapser and provides the key used for retrieving properties, request caches, publishing metrics etc. * @return Setter for fluent interface via method chaining */ public static Setter withCollapserKey(HystrixCollapserKey collapserKey) { return new Setter(collapserKey); } /** * {@link Scope} defining what scope the collapsing should occur within * * @param scope * * @return Setter for fluent interface via method chaining */ public Setter andScope(Scope scope) { this.scope = scope; return this; } /** * @param propertiesSetter * {@link HystrixCollapserProperties.Setter} that allows instance specific property overrides (which can then be overridden by dynamic properties, see * {@link HystrixPropertiesStrategy} for * information on order of precedence). * <p> * Will use defaults if left NULL. * @return Setter for fluent interface via method chaining */ public Setter andCollapserPropertiesDefaults(HystrixCollapserProperties.Setter propertiesSetter) { this.propertiesSetter = propertiesSetter; return this; } } // this is a micro-optimization but saves about 1-2microseconds (on 2011 MacBook Pro) // on the repetitive string processing that will occur on the same classes over and over again @SuppressWarnings("rawtypes") private static ConcurrentHashMap<Class<? extends HystrixCollapser>, String> defaultNameCache = new ConcurrentHashMap<Class<? extends HystrixCollapser>, String>(); }
4,617
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixThreadPoolProperties.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; import static com.netflix.hystrix.strategy.properties.HystrixPropertiesChainedProperty.forBoolean; import static com.netflix.hystrix.strategy.properties.HystrixPropertiesChainedProperty.forInteger; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy; import com.netflix.hystrix.strategy.properties.HystrixProperty; import com.netflix.hystrix.util.HystrixRollingNumber; /** * Properties for instances of {@link HystrixThreadPool}. * <p> * Default implementation of methods uses Archaius (https://github.com/Netflix/archaius) * * Note a change in behavior in 1.5.7. Prior to that version, the configuration for 'coreSize' was used to control * both coreSize and maximumSize. This is a fixed-size threadpool that can never give up an unused thread. In 1.5.7+, * the values can diverge, and if you set coreSize < maximumSize, threads can be given up (subject to the keep-alive * time) * * It is OK to leave maximumSize unset using any version of Hystrix. If you do, then maximum size will default to * core size and you'll have a fixed-size threadpool. * * If you accidentally set maximumSize < coreSize, then maximum will be raised to coreSize * (this prioritizes keeping extra threads around rather than inducing threadpool rejections) */ public abstract class HystrixThreadPoolProperties { /* defaults */ static int default_coreSize = 10; // core size of thread pool static int default_maximumSize = 10; // maximum size of thread pool static int default_keepAliveTimeMinutes = 1; // minutes to keep a thread alive static int default_maxQueueSize = -1; // size of queue (this can't be dynamically changed so we use 'queueSizeRejectionThreshold' to artificially limit and reject) // -1 turns it off and makes us use SynchronousQueue static boolean default_allow_maximum_size_to_diverge_from_core_size = false; //should the maximumSize config value get read and used in configuring the threadPool //turning this on should be a conscious decision by the user, so we default it to false static int default_queueSizeRejectionThreshold = 5; // number of items in queue static int default_threadPoolRollingNumberStatisticalWindow = 10000; // milliseconds for rolling number static int default_threadPoolRollingNumberStatisticalWindowBuckets = 10; // number of buckets in rolling number (10 1-second buckets) private final HystrixProperty<Integer> corePoolSize; private final HystrixProperty<Integer> maximumPoolSize; private final HystrixProperty<Integer> keepAliveTime; private final HystrixProperty<Integer> maxQueueSize; private final HystrixProperty<Integer> queueSizeRejectionThreshold; private final HystrixProperty<Boolean> allowMaximumSizeToDivergeFromCoreSize; private final HystrixProperty<Integer> threadPoolRollingNumberStatisticalWindowInMilliseconds; private final HystrixProperty<Integer> threadPoolRollingNumberStatisticalWindowBuckets; protected HystrixThreadPoolProperties(HystrixThreadPoolKey key) { this(key, new Setter(), "hystrix"); } protected HystrixThreadPoolProperties(HystrixThreadPoolKey key, Setter builder) { this(key, builder, "hystrix"); } protected HystrixThreadPoolProperties(HystrixThreadPoolKey key, Setter builder, String propertyPrefix) { this.allowMaximumSizeToDivergeFromCoreSize = getProperty(propertyPrefix, key, "allowMaximumSizeToDivergeFromCoreSize", builder.getAllowMaximumSizeToDivergeFromCoreSize(), default_allow_maximum_size_to_diverge_from_core_size); this.corePoolSize = getProperty(propertyPrefix, key, "coreSize", builder.getCoreSize(), default_coreSize); //this object always contains a reference to the configuration value for the maximumSize of the threadpool //it only gets applied if allowMaximumSizeToDivergeFromCoreSize is true this.maximumPoolSize = getProperty(propertyPrefix, key, "maximumSize", builder.getMaximumSize(), default_maximumSize); this.keepAliveTime = getProperty(propertyPrefix, key, "keepAliveTimeMinutes", builder.getKeepAliveTimeMinutes(), default_keepAliveTimeMinutes); this.maxQueueSize = getProperty(propertyPrefix, key, "maxQueueSize", builder.getMaxQueueSize(), default_maxQueueSize); this.queueSizeRejectionThreshold = getProperty(propertyPrefix, key, "queueSizeRejectionThreshold", builder.getQueueSizeRejectionThreshold(), default_queueSizeRejectionThreshold); this.threadPoolRollingNumberStatisticalWindowInMilliseconds = getProperty(propertyPrefix, key, "metrics.rollingStats.timeInMilliseconds", builder.getMetricsRollingStatisticalWindowInMilliseconds(), default_threadPoolRollingNumberStatisticalWindow); this.threadPoolRollingNumberStatisticalWindowBuckets = getProperty(propertyPrefix, key, "metrics.rollingStats.numBuckets", builder.getMetricsRollingStatisticalWindowBuckets(), default_threadPoolRollingNumberStatisticalWindowBuckets); } private static HystrixProperty<Integer> getProperty(String propertyPrefix, HystrixThreadPoolKey key, String instanceProperty, Integer builderOverrideValue, Integer defaultValue) { return forInteger() .add(propertyPrefix + ".threadpool." + key.name() + "." + instanceProperty, builderOverrideValue) .add(propertyPrefix + ".threadpool.default." + instanceProperty, defaultValue) .build(); } private static HystrixProperty<Boolean> getProperty(String propertyPrefix, HystrixThreadPoolKey key, String instanceProperty, Boolean builderOverrideValue, Boolean defaultValue) { return forBoolean() .add(propertyPrefix + ".threadpool." + key.name() + "." + instanceProperty, builderOverrideValue) .add(propertyPrefix + ".threadpool.default." + instanceProperty, defaultValue) .build(); } /** * Core thread-pool size that gets passed to {@link ThreadPoolExecutor#setCorePoolSize(int)} * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> coreSize() { return corePoolSize; } /** * Maximum thread-pool size configured for threadpool. May conflict with other config, so if you need the * actual value that gets passed to {@link ThreadPoolExecutor#setMaximumPoolSize(int)}, use {@link #actualMaximumSize()} * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> maximumSize() { return maximumPoolSize; } /** * Given all of the thread pool configuration, what is the actual maximumSize applied to the thread pool * via {@link ThreadPoolExecutor#setMaximumPoolSize(int)} * * Cases: * 1) allowMaximumSizeToDivergeFromCoreSize == false: maximumSize is set to coreSize * 2) allowMaximumSizeToDivergeFromCoreSize == true, maximumSize >= coreSize: thread pool has different core/max sizes, so return the configured max * 3) allowMaximumSizeToDivergeFromCoreSize == true, maximumSize < coreSize: threadpool incorrectly configured, use coreSize for max size * @return actually configured maximum size of threadpool */ public Integer actualMaximumSize() { final int coreSize = coreSize().get(); final int maximumSize = maximumSize().get(); if (getAllowMaximumSizeToDivergeFromCoreSize().get()) { if (coreSize > maximumSize) { return coreSize; } else { return maximumSize; } } else { return coreSize; } } /** * Keep-alive time in minutes that gets passed to {@link ThreadPoolExecutor#setKeepAliveTime(long, TimeUnit)} * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> keepAliveTimeMinutes() { return keepAliveTime; } /** * Max queue size that gets passed to {@link BlockingQueue} in {@link HystrixConcurrencyStrategy#getBlockingQueue(int)} * * This should only affect the instantiation of a threadpool - it is not eliglible to change a queue size on the fly. * For that, use {@link #queueSizeRejectionThreshold()}. * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> maxQueueSize() { return maxQueueSize; } /** * Queue size rejection threshold is an artificial "max" size at which rejections will occur even if {@link #maxQueueSize} has not been reached. This is done because the {@link #maxQueueSize} of a * {@link BlockingQueue} can not be dynamically changed and we want to support dynamically changing the queue size that affects rejections. * <p> * This is used by {@link HystrixCommand} when queuing a thread for execution. * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> queueSizeRejectionThreshold() { return queueSizeRejectionThreshold; } public HystrixProperty<Boolean> getAllowMaximumSizeToDivergeFromCoreSize() { return allowMaximumSizeToDivergeFromCoreSize; } /** * Duration of statistical rolling window in milliseconds. This is passed into {@link HystrixRollingNumber} inside each {@link HystrixThreadPoolMetrics} instance. * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> metricsRollingStatisticalWindowInMilliseconds() { return threadPoolRollingNumberStatisticalWindowInMilliseconds; } /** * Number of buckets the rolling statistical window is broken into. This is passed into {@link HystrixRollingNumber} inside each {@link HystrixThreadPoolMetrics} instance. * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> metricsRollingStatisticalWindowBuckets() { return threadPoolRollingNumberStatisticalWindowBuckets; } /** * Factory method to retrieve the default Setter. */ public static Setter Setter() { return new Setter(); } /** * Factory method to retrieve the default Setter. * Groovy has a bug (GROOVY-6286) which does not allow method names and inner classes to have the same name * This method fixes Issue #967 and allows Groovy consumers to choose this method and not trigger the bug */ public static Setter defaultSetter() { return Setter(); } /** * Fluent interface that allows chained setting of properties that can be passed into a {@link HystrixThreadPool} via a {@link HystrixCommand} constructor to inject instance specific property * overrides. * <p> * See {@link HystrixPropertiesStrategy} for more information on order of precedence. * <p> * Example: * <p> * <pre> {@code * HystrixThreadPoolProperties.Setter() * .withCoreSize(10) * .withQueueSizeRejectionThreshold(10); * } </pre> * * @NotThreadSafe */ public static class Setter { private Integer coreSize = null; private Integer maximumSize = null; private Integer keepAliveTimeMinutes = null; private Integer maxQueueSize = null; private Integer queueSizeRejectionThreshold = null; private Boolean allowMaximumSizeToDivergeFromCoreSize = null; private Integer rollingStatisticalWindowInMilliseconds = null; private Integer rollingStatisticalWindowBuckets = null; private Setter() { } public Integer getCoreSize() { return coreSize; } public Integer getMaximumSize() { return maximumSize; } public Integer getKeepAliveTimeMinutes() { return keepAliveTimeMinutes; } public Integer getMaxQueueSize() { return maxQueueSize; } public Integer getQueueSizeRejectionThreshold() { return queueSizeRejectionThreshold; } public Boolean getAllowMaximumSizeToDivergeFromCoreSize() { return allowMaximumSizeToDivergeFromCoreSize; } public Integer getMetricsRollingStatisticalWindowInMilliseconds() { return rollingStatisticalWindowInMilliseconds; } public Integer getMetricsRollingStatisticalWindowBuckets() { return rollingStatisticalWindowBuckets; } public Setter withCoreSize(int value) { this.coreSize = value; return this; } public Setter withMaximumSize(int value) { this.maximumSize = value; return this; } public Setter withKeepAliveTimeMinutes(int value) { this.keepAliveTimeMinutes = value; return this; } public Setter withMaxQueueSize(int value) { this.maxQueueSize = value; return this; } public Setter withQueueSizeRejectionThreshold(int value) { this.queueSizeRejectionThreshold = value; return this; } public Setter withAllowMaximumSizeToDivergeFromCoreSize(boolean value) { this.allowMaximumSizeToDivergeFromCoreSize = value; return this; } public Setter withMetricsRollingStatisticalWindowInMilliseconds(int value) { this.rollingStatisticalWindowInMilliseconds = value; return this; } public Setter withMetricsRollingStatisticalWindowBuckets(int value) { this.rollingStatisticalWindowBuckets = value; return this; } } }
4,618
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixObservableCommand.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; import rx.Observable; import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy; import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook; import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy; import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier; /** * Used to wrap code that will execute potentially risky functionality (typically meaning a service call over the network) * with fault and latency tolerance, statistics and performance metrics capture, circuit breaker and bulkhead functionality. * This command should be used for a purely non-blocking call pattern. The caller of this command will be subscribed to the Observable<R> returned by the run() method. * * @param <R> * the return type * * @ThreadSafe */ public abstract class HystrixObservableCommand<R> extends AbstractCommand<R> implements HystrixObservable<R>, HystrixInvokableInfo<R> { /** * Construct a {@link HystrixObservableCommand} with defined {@link HystrixCommandGroupKey}. * <p> * The {@link HystrixCommandKey} will be derived from the implementing class name. * * @param group * {@link HystrixCommandGroupKey} used to group together multiple {@link HystrixObservableCommand} objects. * <p> * The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interace with, * common business purpose etc. */ protected HystrixObservableCommand(HystrixCommandGroupKey group) { // use 'null' to specify use the default this(new Setter(group)); } /** * * Overridden to true so that all onNext emissions are captured * * @return if onNext events should be reported on * This affects {@link HystrixRequestLog}, and {@link HystrixEventNotifier} currently. Metrics/Hooks later */ @Override protected boolean shouldOutputOnNextEvents() { return true; } @Override protected String getFallbackMethodName() { return "resumeWithFallback"; } @Override protected boolean isFallbackUserDefined() { Boolean containsFromMap = commandContainsFallback.get(commandKey); if (containsFromMap != null) { return containsFromMap; } else { Boolean toInsertIntoMap; try { getClass().getDeclaredMethod("resumeWithFallback"); toInsertIntoMap = true; } catch (NoSuchMethodException nsme) { toInsertIntoMap = false; } commandContainsFallback.put(commandKey, toInsertIntoMap); return toInsertIntoMap; } } @Override protected boolean commandIsScalar() { return false; } /** * Construct a {@link HystrixObservableCommand} with defined {@link Setter} that allows injecting property and strategy overrides and other optional arguments. * <p> * NOTE: The {@link HystrixCommandKey} is used to associate a {@link HystrixObservableCommand} with {@link HystrixCircuitBreaker}, {@link HystrixCommandMetrics} and other objects. * <p> * Do not create multiple {@link HystrixObservableCommand} implementations with the same {@link HystrixCommandKey} but different injected default properties as the first instantiated will win. * <p> * Properties passed in via {@link Setter#andCommandPropertiesDefaults} are cached for the given {@link HystrixCommandKey} for the life of the JVM * or until {@link Hystrix#reset()} is called. Dynamic properties allow runtime changes. Read more on the <a href="https://github.com/Netflix/Hystrix/wiki/Configuration">Hystrix Wiki</a>. * * @param setter * Fluent interface for constructor arguments */ protected HystrixObservableCommand(Setter setter) { // use 'null' to specify use the default this(setter.groupKey, setter.commandKey, setter.threadPoolKey, null, null, setter.commandPropertiesDefaults, setter.threadPoolPropertiesDefaults, null, null, null, null, null); } /** * Allow constructing a {@link HystrixObservableCommand} with injection of most aspects of its functionality. * <p> * Some of these never have a legitimate reason for injection except in unit testing. * <p> * Most of the args will revert to a valid default if 'null' is passed in. */ HystrixObservableCommand(HystrixCommandGroupKey group, HystrixCommandKey key, HystrixThreadPoolKey threadPoolKey, HystrixCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, HystrixCommandProperties.Setter commandPropertiesDefaults, HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults, HystrixCommandMetrics metrics, TryableSemaphore fallbackSemaphore, TryableSemaphore executionSemaphore, HystrixPropertiesStrategy propertiesStrategy, HystrixCommandExecutionHook executionHook) { super(group, key, threadPoolKey, circuitBreaker, threadPool, commandPropertiesDefaults, threadPoolPropertiesDefaults, metrics, fallbackSemaphore, executionSemaphore, propertiesStrategy, executionHook); } /** * Fluent interface for arguments to the {@link HystrixObservableCommand} constructor. * <p> * The required arguments are set via the 'with' factory method and optional arguments via the 'and' chained methods. * <p> * Example: * <pre> {@code * Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("GroupName")) .andCommandKey(HystrixCommandKey.Factory.asKey("CommandName")) .andEventNotifier(notifier); * } </pre> * * @NotThreadSafe */ final public static class Setter { protected final HystrixCommandGroupKey groupKey; protected HystrixCommandKey commandKey; protected HystrixThreadPoolKey threadPoolKey; protected HystrixCommandProperties.Setter commandPropertiesDefaults; protected HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults; /** * Setter factory method containing required values. * <p> * All optional arguments can be set via the chained methods. * * @param groupKey * {@link HystrixCommandGroupKey} used to group together multiple {@link HystrixObservableCommand} objects. * <p> * The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interace * with, * common business purpose etc. */ protected Setter(HystrixCommandGroupKey groupKey) { this.groupKey = groupKey; // default to using SEMAPHORE for ObservableCommand commandPropertiesDefaults = setDefaults(HystrixCommandProperties.Setter()); } /** * Setter factory method with required values. * <p> * All optional arguments can be set via the chained methods. * * @param groupKey * {@link HystrixCommandGroupKey} used to group together multiple {@link HystrixObservableCommand} objects. * <p> * The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interace * with, * common business purpose etc. */ public static Setter withGroupKey(HystrixCommandGroupKey groupKey) { return new Setter(groupKey); } /** * @param commandKey * {@link HystrixCommandKey} used to identify a {@link HystrixObservableCommand} instance for statistics, circuit-breaker, properties, etc. * <p> * By default this will be derived from the instance class name. * <p> * NOTE: Every unique {@link HystrixCommandKey} will result in new instances of {@link HystrixCircuitBreaker}, {@link HystrixCommandMetrics} and {@link HystrixCommandProperties}. * Thus, * the number of variants should be kept to a finite and reasonable number to avoid high-memory usage or memory leacks. * <p> * Hundreds of keys is fine, tens of thousands is probably not. * @return Setter for fluent interface via method chaining */ public Setter andCommandKey(HystrixCommandKey commandKey) { this.commandKey = commandKey; return this; } /** * Optional * * @param commandPropertiesDefaults * {@link HystrixCommandProperties.Setter} with property overrides for this specific instance of {@link HystrixObservableCommand}. * <p> * See the {@link HystrixPropertiesStrategy} JavaDocs for more information on properties and order of precedence. * @return Setter for fluent interface via method chaining */ public Setter andCommandPropertiesDefaults(HystrixCommandProperties.Setter commandPropertiesDefaults) { this.commandPropertiesDefaults = setDefaults(commandPropertiesDefaults); return this; } private HystrixCommandProperties.Setter setDefaults(HystrixCommandProperties.Setter commandPropertiesDefaults) { if (commandPropertiesDefaults.getExecutionIsolationStrategy() == null) { // default to using SEMAPHORE for ObservableCommand if the user didn't set it commandPropertiesDefaults.withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE); } return commandPropertiesDefaults; } } /** * Implement this method with code to be executed when {@link #observe()} or {@link #toObservable()} are invoked. * * @return R response type */ protected abstract Observable<R> construct(); /** * If {@link #observe()} or {@link #toObservable()} fails in any way then this method will be invoked to provide an opportunity to return a fallback response. * <p> * This should do work that does not require network transport to produce. * <p> * In other words, this should be a static or cached result that can immediately be returned upon failure. * <p> * If network traffic is wanted for fallback (such as going to MemCache) then the fallback implementation should invoke another {@link HystrixObservableCommand} instance that protects against * that network * access and possibly has another level of fallback that does not involve network access. * <p> * DEFAULT BEHAVIOR: It throws UnsupportedOperationException. * * @return R or UnsupportedOperationException if not implemented */ protected Observable<R> resumeWithFallback() { return Observable.error(new UnsupportedOperationException("No fallback available.")); } @Override final protected Observable<R> getExecutionObservable() { return construct(); } @Override final protected Observable<R> getFallbackObservable() { return resumeWithFallback(); } }
4,619
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixExecutable.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; import java.util.concurrent.Future; import rx.Observable; import rx.schedulers.Schedulers; import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy; import com.netflix.hystrix.exception.HystrixBadRequestException; import com.netflix.hystrix.exception.HystrixRuntimeException; /** * Common interface for executables ({@link HystrixCommand} and {@link HystrixCollapser}) so client code can treat them the same and combine in typed collections if desired. * * @param <R> */ public interface HystrixExecutable<R> extends HystrixInvokable<R> { /** * Used for synchronous execution of command. * * @return R * Result of {@link HystrixCommand} execution * @throws HystrixRuntimeException * if an error occurs and a fallback cannot be retrieved * @throws HystrixBadRequestException * if the {@link HystrixCommand} instance considers request arguments to be invalid and needs to throw an error that does not represent a system failure */ public R execute(); /** * Used for asynchronous execution of command. * <p> * This will queue up the command on the thread pool and return an {@link Future} to get the result once it completes. * <p> * NOTE: If configured to not run in a separate thread, this will have the same effect as {@link #execute()} and will block. * <p> * We don't throw an exception in that case but just flip to synchronous execution so code doesn't need to change in order to switch a circuit from running a separate thread to the calling thread. * * @return {@code Future<R>} Result of {@link HystrixCommand} execution * @throws HystrixRuntimeException * if an error occurs and a fallback cannot be retrieved * @throws HystrixBadRequestException * if the {@link HystrixCommand} instance considers request arguments to be invalid and needs to throw an error that does not represent a system failure */ public Future<R> queue(); /** * Used for asynchronous execution of command with a callback by subscribing to the {@link Observable}. * <p> * This eagerly starts execution of the command the same as {@link #queue()} and {@link #execute()}. * A lazy {@link Observable} can be obtained from {@link HystrixCommand#toObservable()} or {@link HystrixCollapser#toObservable()}. * <p> * <b>Callback Scheduling</b> * <p> * <ul> * <li>When using {@link ExecutionIsolationStrategy#THREAD} this defaults to using {@link Schedulers#computation()} for callbacks.</li> * <li>When using {@link ExecutionIsolationStrategy#SEMAPHORE} this defaults to using {@link Schedulers#immediate()} for callbacks.</li> * </ul> * <p> * See https://github.com/Netflix/RxJava/wiki for more information. * * @return {@code Observable<R>} that executes and calls back with the result of the command execution or a fallback if the command fails for any reason. * @throws HystrixRuntimeException * if a fallback does not exist * <p> * <ul> * <li>via {@code Observer#onError} if a failure occurs</li> * <li>or immediately if the command can not be queued (such as short-circuited, thread-pool/semaphore rejected)</li> * </ul> * @throws HystrixBadRequestException * via {@code Observer#onError} if invalid arguments or state were used representing a user failure, not a system failure * @throws IllegalStateException * if invoked more than once */ public Observable<R> observe(); }
4,620
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixCollapserProperties.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; import static com.netflix.hystrix.strategy.properties.HystrixPropertiesChainedProperty.forBoolean; import static com.netflix.hystrix.strategy.properties.HystrixPropertiesChainedProperty.forInteger; import static com.netflix.hystrix.strategy.properties.HystrixPropertiesChainedProperty.forString; import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy; import com.netflix.hystrix.strategy.properties.HystrixProperty; import com.netflix.hystrix.util.HystrixRollingNumber; import com.netflix.hystrix.util.HystrixRollingPercentile; /** * Properties for instances of {@link HystrixCollapser}. * <p> * Default implementation of methods uses Archaius (https://github.com/Netflix/archaius) */ public abstract class HystrixCollapserProperties { /* defaults */ private static final Integer default_maxRequestsInBatch = Integer.MAX_VALUE; private static final Integer default_timerDelayInMilliseconds = 10; private static final Boolean default_requestCacheEnabled = true; /* package */ static final Integer default_metricsRollingStatisticalWindow = 10000;// default => statisticalWindow: 10000 = 10 seconds (and default of 10 buckets so each bucket is 1 second) private static final Integer default_metricsRollingStatisticalWindowBuckets = 10;// default => statisticalWindowBuckets: 10 = 10 buckets in a 10 second window so each bucket is 1 second private static final Boolean default_metricsRollingPercentileEnabled = true; private static final Integer default_metricsRollingPercentileWindow = 60000; // default to 1 minute for RollingPercentile private static final Integer default_metricsRollingPercentileWindowBuckets = 6; // default to 6 buckets (10 seconds each in 60 second window) private static final Integer default_metricsRollingPercentileBucketSize = 100; // default to 100 values max per bucket private final HystrixProperty<Integer> maxRequestsInBatch; private final HystrixProperty<Integer> timerDelayInMilliseconds; private final HystrixProperty<Boolean> requestCacheEnabled; private final HystrixProperty<Integer> metricsRollingStatisticalWindowInMilliseconds; // milliseconds back that will be tracked private final HystrixProperty<Integer> metricsRollingStatisticalWindowBuckets; // number of buckets in the statisticalWindow private final HystrixProperty<Boolean> metricsRollingPercentileEnabled; // Whether monitoring should be enabled private final HystrixProperty<Integer> metricsRollingPercentileWindowInMilliseconds; // number of milliseconds that will be tracked in RollingPercentile private final HystrixProperty<Integer> metricsRollingPercentileWindowBuckets; // number of buckets percentileWindow will be divided into private final HystrixProperty<Integer> metricsRollingPercentileBucketSize; // how many values will be stored in each percentileWindowBucket protected HystrixCollapserProperties(HystrixCollapserKey collapserKey) { this(collapserKey, new Setter(), "hystrix"); } protected HystrixCollapserProperties(HystrixCollapserKey collapserKey, Setter builder) { this(collapserKey, builder, "hystrix"); } protected HystrixCollapserProperties(HystrixCollapserKey key, Setter builder, String propertyPrefix) { this.maxRequestsInBatch = getProperty(propertyPrefix, key, "maxRequestsInBatch", builder.getMaxRequestsInBatch(), default_maxRequestsInBatch); this.timerDelayInMilliseconds = getProperty(propertyPrefix, key, "timerDelayInMilliseconds", builder.getTimerDelayInMilliseconds(), default_timerDelayInMilliseconds); this.requestCacheEnabled = getProperty(propertyPrefix, key, "requestCache.enabled", builder.getRequestCacheEnabled(), default_requestCacheEnabled); this.metricsRollingStatisticalWindowInMilliseconds = getProperty(propertyPrefix, key, "metrics.rollingStats.timeInMilliseconds", builder.getMetricsRollingStatisticalWindowInMilliseconds(), default_metricsRollingStatisticalWindow); this.metricsRollingStatisticalWindowBuckets = getProperty(propertyPrefix, key, "metrics.rollingStats.numBuckets", builder.getMetricsRollingStatisticalWindowBuckets(), default_metricsRollingStatisticalWindowBuckets); this.metricsRollingPercentileEnabled = getProperty(propertyPrefix, key, "metrics.rollingPercentile.enabled", builder.getMetricsRollingPercentileEnabled(), default_metricsRollingPercentileEnabled); this.metricsRollingPercentileWindowInMilliseconds = getProperty(propertyPrefix, key, "metrics.rollingPercentile.timeInMilliseconds", builder.getMetricsRollingPercentileWindowInMilliseconds(), default_metricsRollingPercentileWindow); this.metricsRollingPercentileWindowBuckets = getProperty(propertyPrefix, key, "metrics.rollingPercentile.numBuckets", builder.getMetricsRollingPercentileWindowBuckets(), default_metricsRollingPercentileWindowBuckets); this.metricsRollingPercentileBucketSize = getProperty(propertyPrefix, key, "metrics.rollingPercentile.bucketSize", builder.getMetricsRollingPercentileBucketSize(), default_metricsRollingPercentileBucketSize); } private static HystrixProperty<Integer> getProperty(String propertyPrefix, HystrixCollapserKey key, String instanceProperty, Integer builderOverrideValue, Integer defaultValue) { return forInteger() .add(propertyPrefix + ".collapser." + key.name() + "." + instanceProperty, builderOverrideValue) .add(propertyPrefix + ".collapser.default." + instanceProperty, defaultValue) .build(); } private static HystrixProperty<Boolean> getProperty(String propertyPrefix, HystrixCollapserKey key, String instanceProperty, Boolean builderOverrideValue, Boolean defaultValue) { return forBoolean() .add(propertyPrefix + ".collapser." + key.name() + "." + instanceProperty, builderOverrideValue) .add(propertyPrefix + ".collapser.default." + instanceProperty, defaultValue) .build(); } /** * Whether request caching is enabled for {@link HystrixCollapser#execute} and {@link HystrixCollapser#queue} invocations. * * Deprecated as of 1.4.0-RC7 in favor of requestCacheEnabled() (to match {@link HystrixCommandProperties#requestCacheEnabled()} * * @return {@code HystrixProperty<Boolean>} */ @Deprecated public HystrixProperty<Boolean> requestCachingEnabled() { return requestCacheEnabled; } /** * Whether request caching is enabled for {@link HystrixCollapser#execute} and {@link HystrixCollapser#queue} invocations. * * @return {@code HystrixProperty<Boolean>} */ public HystrixProperty<Boolean> requestCacheEnabled() { return requestCacheEnabled; } /** * The maximum number of requests allowed in a batch before triggering a batch execution. * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> maxRequestsInBatch() { return maxRequestsInBatch; } /** * The number of milliseconds between batch executions (unless {@link #maxRequestsInBatch} is hit which will cause a batch to execute early. * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> timerDelayInMilliseconds() { return timerDelayInMilliseconds; } /** * Duration of statistical rolling window in milliseconds. This is passed into {@link HystrixRollingNumber} inside {@link HystrixCommandMetrics}. * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> metricsRollingStatisticalWindowInMilliseconds() { return metricsRollingStatisticalWindowInMilliseconds; } /** * Number of buckets the rolling statistical window is broken into. This is passed into {@link HystrixRollingNumber} inside {@link HystrixCollapserMetrics}. * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> metricsRollingStatisticalWindowBuckets() { return metricsRollingStatisticalWindowBuckets; } /** * Whether percentile metrics should be captured using {@link HystrixRollingPercentile} inside {@link HystrixCollapserMetrics}. * * @return {@code HystrixProperty<Boolean>} */ public HystrixProperty<Boolean> metricsRollingPercentileEnabled() { return metricsRollingPercentileEnabled; } /** * Duration of percentile rolling window in milliseconds. This is passed into {@link HystrixRollingPercentile} inside {@link HystrixCollapserMetrics}. * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> metricsRollingPercentileWindowInMilliseconds() { return metricsRollingPercentileWindowInMilliseconds; } /** * Number of buckets the rolling percentile window is broken into. This is passed into {@link HystrixRollingPercentile} inside {@link HystrixCollapserMetrics}. * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> metricsRollingPercentileWindowBuckets() { return metricsRollingPercentileWindowBuckets; } /** * Maximum number of values stored in each bucket of the rolling percentile. This is passed into {@link HystrixRollingPercentile} inside {@link HystrixCollapserMetrics}. * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> metricsRollingPercentileBucketSize() { return metricsRollingPercentileBucketSize; } /** * Factory method to retrieve the default Setter. */ public static Setter Setter() { return new Setter(); } /** * Factory method to retrieve the default Setter. * Groovy has a bug (GROOVY-6286) which does not allow method names and inner classes to have the same name * This method fixes Issue #967 and allows Groovy consumers to choose this method and not trigger the bug */ public static Setter defaultSetter() { return Setter(); } /** * Fluent interface that allows chained setting of properties that can be passed into a {@link HystrixCollapser} constructor to inject instance specific property overrides. * <p> * See {@link HystrixPropertiesStrategy} for more information on order of precedence. * <p> * Example: * <p> * <pre> {@code * HystrixCollapserProperties.Setter() * .setMaxRequestsInBatch(100) * .setTimerDelayInMilliseconds(10); * } </pre> * * @NotThreadSafe */ public static class Setter { @Deprecated private Boolean collapsingEnabled = null; private Integer maxRequestsInBatch = null; private Integer timerDelayInMilliseconds = null; private Boolean requestCacheEnabled = null; private Integer metricsRollingStatisticalWindowInMilliseconds = null; private Integer metricsRollingStatisticalWindowBuckets = null; private Integer metricsRollingPercentileBucketSize = null; private Boolean metricsRollingPercentileEnabled = null; private Integer metricsRollingPercentileWindowInMilliseconds = null; private Integer metricsRollingPercentileWindowBuckets = null; private Setter() { } /** * Deprecated because the collapsingEnabled setting doesn't do anything. */ @Deprecated public Boolean getCollapsingEnabled() { return collapsingEnabled; } public Integer getMaxRequestsInBatch() { return maxRequestsInBatch; } public Integer getTimerDelayInMilliseconds() { return timerDelayInMilliseconds; } public Boolean getRequestCacheEnabled() { return requestCacheEnabled; } public Integer getMetricsRollingStatisticalWindowInMilliseconds() { return metricsRollingStatisticalWindowInMilliseconds; } public Integer getMetricsRollingStatisticalWindowBuckets() { return metricsRollingStatisticalWindowBuckets; } public Integer getMetricsRollingPercentileBucketSize() { return metricsRollingPercentileBucketSize; } public Boolean getMetricsRollingPercentileEnabled() { return metricsRollingPercentileEnabled; } public Integer getMetricsRollingPercentileWindowInMilliseconds() { return metricsRollingPercentileWindowInMilliseconds; } public Integer getMetricsRollingPercentileWindowBuckets() { return metricsRollingPercentileWindowBuckets; } /** * Deprecated because the collapsingEnabled setting doesn't do anything. */ @Deprecated public Setter withCollapsingEnabled(boolean value) { this.collapsingEnabled = value; return this; } public Setter withMaxRequestsInBatch(int value) { this.maxRequestsInBatch = value; return this; } public Setter withTimerDelayInMilliseconds(int value) { this.timerDelayInMilliseconds = value; return this; } public Setter withRequestCacheEnabled(boolean value) { this.requestCacheEnabled = value; return this; } public Setter withMetricsRollingStatisticalWindowInMilliseconds(int value) { this.metricsRollingStatisticalWindowInMilliseconds = value; return this; } public Setter withMetricsRollingStatisticalWindowBuckets(int value) { this.metricsRollingStatisticalWindowBuckets = value; return this; } public Setter withMetricsRollingPercentileBucketSize(int value) { this.metricsRollingPercentileBucketSize = value; return this; } public Setter withMetricsRollingPercentileEnabled(boolean value) { this.metricsRollingPercentileEnabled = value; return this; } public Setter withMetricsRollingPercentileWindowInMilliseconds(int value) { this.metricsRollingPercentileWindowInMilliseconds = value; return this; } public Setter withMetricsRollingPercentileWindowBuckets(int value) { this.metricsRollingPercentileWindowBuckets = value; return this; } /** * Base properties for unit testing. */ /* package */static Setter getUnitTestPropertiesBuilder() { return new Setter() .withMaxRequestsInBatch(Integer.MAX_VALUE) .withTimerDelayInMilliseconds(10) .withRequestCacheEnabled(true); } /** * 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 collapser properties builder * @return HystrixCollapserProperties */ /* package */static HystrixCollapserProperties asMock(final Setter builder) { return new HystrixCollapserProperties(TestHystrixCollapserKey.TEST) { @Override public HystrixProperty<Boolean> requestCachingEnabled() { return HystrixProperty.Factory.asProperty(builder.requestCacheEnabled); } @Override public HystrixProperty<Integer> maxRequestsInBatch() { return HystrixProperty.Factory.asProperty(builder.maxRequestsInBatch); } @Override public HystrixProperty<Integer> timerDelayInMilliseconds() { return HystrixProperty.Factory.asProperty(builder.timerDelayInMilliseconds); } }; } private static enum TestHystrixCollapserKey implements HystrixCollapserKey { TEST } } }
4,621
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/AbstractCommand.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; import com.netflix.hystrix.HystrixCircuitBreaker.NoOpCircuitBreaker; import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy; import com.netflix.hystrix.exception.ExceptionNotWrappedByHystrix; import com.netflix.hystrix.exception.HystrixBadRequestException; import com.netflix.hystrix.exception.HystrixRuntimeException; import com.netflix.hystrix.exception.HystrixRuntimeException.FailureType; import com.netflix.hystrix.exception.HystrixTimeoutException; import com.netflix.hystrix.strategy.HystrixPlugins; import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; import com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable; import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier; import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook; import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherFactory; import com.netflix.hystrix.strategy.properties.HystrixPropertiesFactory; import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy; import com.netflix.hystrix.strategy.properties.HystrixProperty; import com.netflix.hystrix.util.HystrixTimer; import com.netflix.hystrix.util.HystrixTimer.TimerListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Notification; import rx.Observable; import rx.Observable.Operator; import rx.Subscriber; import rx.Subscription; import rx.functions.Action0; import rx.functions.Action1; import rx.functions.Func0; import rx.functions.Func1; import rx.subjects.ReplaySubject; import rx.subscriptions.CompositeSubscription; import java.lang.ref.Reference; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; /* package */abstract class AbstractCommand<R> implements HystrixInvokableInfo<R>, HystrixObservable<R> { private static final Logger logger = LoggerFactory.getLogger(AbstractCommand.class); protected final HystrixCircuitBreaker circuitBreaker; protected final HystrixThreadPool threadPool; protected final HystrixThreadPoolKey threadPoolKey; protected final HystrixCommandProperties properties; protected enum TimedOutStatus { NOT_EXECUTED, COMPLETED, TIMED_OUT } protected enum CommandState { NOT_STARTED, OBSERVABLE_CHAIN_CREATED, USER_CODE_EXECUTED, UNSUBSCRIBED, TERMINAL } protected enum ThreadState { NOT_USING_THREAD, STARTED, UNSUBSCRIBED, TERMINAL } protected final HystrixCommandMetrics metrics; protected final HystrixCommandKey commandKey; protected final HystrixCommandGroupKey commandGroup; /** * Plugin implementations */ protected final HystrixEventNotifier eventNotifier; protected final HystrixConcurrencyStrategy concurrencyStrategy; protected final HystrixCommandExecutionHook executionHook; /* FALLBACK Semaphore */ protected final TryableSemaphore fallbackSemaphoreOverride; /* each circuit has a semaphore to restrict concurrent fallback execution */ protected static final ConcurrentHashMap<String, TryableSemaphore> fallbackSemaphorePerCircuit = new ConcurrentHashMap<String, TryableSemaphore>(); /* END FALLBACK Semaphore */ /* EXECUTION Semaphore */ protected final TryableSemaphore executionSemaphoreOverride; /* each circuit has a semaphore to restrict concurrent fallback execution */ protected static final ConcurrentHashMap<String, TryableSemaphore> executionSemaphorePerCircuit = new ConcurrentHashMap<String, TryableSemaphore>(); /* END EXECUTION Semaphore */ protected final AtomicReference<Reference<TimerListener>> timeoutTimer = new AtomicReference<Reference<TimerListener>>(); protected AtomicReference<CommandState> commandState = new AtomicReference<CommandState>(CommandState.NOT_STARTED); protected AtomicReference<ThreadState> threadState = new AtomicReference<ThreadState>(ThreadState.NOT_USING_THREAD); /* * {@link ExecutionResult} refers to what happened as the user-provided code ran. If request-caching is used, * then multiple command instances will have a reference to the same {@link ExecutionResult}. So all values there * should be the same, even in the presence of request-caching. * * If some values are not properly shareable, then they belong on the command instance, so they are not visible to * other commands. * * Examples: RESPONSE_FROM_CACHE, CANCELLED HystrixEventTypes */ protected volatile ExecutionResult executionResult = ExecutionResult.EMPTY; //state on shared execution protected volatile boolean isResponseFromCache = false; protected volatile ExecutionResult executionResultAtTimeOfCancellation; protected volatile long commandStartTimestamp = -1L; /* If this command executed and timed-out */ protected final AtomicReference<TimedOutStatus> isCommandTimedOut = new AtomicReference<TimedOutStatus>(TimedOutStatus.NOT_EXECUTED); protected volatile Action0 endCurrentThreadExecutingCommand; /** * Instance of RequestCache logic */ protected final HystrixRequestCache requestCache; protected final HystrixRequestLog currentRequestLog; // this is a micro-optimization but saves about 1-2microseconds (on 2011 MacBook Pro) // on the repetitive string processing that will occur on the same classes over and over again private static ConcurrentHashMap<Class<?>, String> defaultNameCache = new ConcurrentHashMap<Class<?>, String>(); protected static ConcurrentHashMap<HystrixCommandKey, Boolean> commandContainsFallback = new ConcurrentHashMap<HystrixCommandKey, Boolean>(); /* package */static String getDefaultNameFromClass(Class<?> cls) { String fromCache = defaultNameCache.get(cls); if (fromCache != null) { return fromCache; } // generate the default // default HystrixCommandKey to use if the method is not overridden String name = cls.getSimpleName(); if (name.equals("")) { // we don't have a SimpleName (anonymous inner class) so use the full class name name = cls.getName(); name = name.substring(name.lastIndexOf('.') + 1, name.length()); } defaultNameCache.put(cls, name); return name; } protected AbstractCommand(HystrixCommandGroupKey group, HystrixCommandKey key, HystrixThreadPoolKey threadPoolKey, HystrixCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, HystrixCommandProperties.Setter commandPropertiesDefaults, HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults, HystrixCommandMetrics metrics, TryableSemaphore fallbackSemaphore, TryableSemaphore executionSemaphore, HystrixPropertiesStrategy propertiesStrategy, HystrixCommandExecutionHook executionHook) { this.commandGroup = initGroupKey(group); this.commandKey = initCommandKey(key, getClass()); this.properties = initCommandProperties(this.commandKey, propertiesStrategy, commandPropertiesDefaults); this.threadPoolKey = initThreadPoolKey(threadPoolKey, this.commandGroup, this.properties.executionIsolationThreadPoolKeyOverride().get()); this.metrics = initMetrics(metrics, this.commandGroup, this.threadPoolKey, this.commandKey, this.properties); this.circuitBreaker = initCircuitBreaker(this.properties.circuitBreakerEnabled().get(), circuitBreaker, this.commandGroup, this.commandKey, this.properties, this.metrics); this.threadPool = initThreadPool(threadPool, this.threadPoolKey, threadPoolPropertiesDefaults); //Strategies from plugins this.eventNotifier = HystrixPlugins.getInstance().getEventNotifier(); this.concurrencyStrategy = HystrixPlugins.getInstance().getConcurrencyStrategy(); HystrixMetricsPublisherFactory.createOrRetrievePublisherForCommand(this.commandKey, this.commandGroup, this.metrics, this.circuitBreaker, this.properties); this.executionHook = initExecutionHook(executionHook); this.requestCache = HystrixRequestCache.getInstance(this.commandKey, this.concurrencyStrategy); this.currentRequestLog = initRequestLog(this.properties.requestLogEnabled().get(), this.concurrencyStrategy); /* fallback semaphore override if applicable */ this.fallbackSemaphoreOverride = fallbackSemaphore; /* execution semaphore override if applicable */ this.executionSemaphoreOverride = executionSemaphore; } private static HystrixCommandGroupKey initGroupKey(final HystrixCommandGroupKey fromConstructor) { if (fromConstructor == null) { throw new IllegalStateException("HystrixCommandGroup can not be NULL"); } else { return fromConstructor; } } private static HystrixCommandKey initCommandKey(final HystrixCommandKey fromConstructor, Class<?> clazz) { if (fromConstructor == null || fromConstructor.name().trim().equals("")) { final String keyName = getDefaultNameFromClass(clazz); return HystrixCommandKey.Factory.asKey(keyName); } else { return fromConstructor; } } private static HystrixCommandProperties initCommandProperties(HystrixCommandKey commandKey, HystrixPropertiesStrategy propertiesStrategy, HystrixCommandProperties.Setter commandPropertiesDefaults) { if (propertiesStrategy == null) { return HystrixPropertiesFactory.getCommandProperties(commandKey, commandPropertiesDefaults); } else { // used for unit testing return propertiesStrategy.getCommandProperties(commandKey, commandPropertiesDefaults); } } /* * ThreadPoolKey * * This defines which thread-pool this command should run on. * * It uses the HystrixThreadPoolKey if provided, then defaults to use HystrixCommandGroup. * * It can then be overridden by a property if defined so it can be changed at runtime. */ private static HystrixThreadPoolKey initThreadPoolKey(HystrixThreadPoolKey threadPoolKey, HystrixCommandGroupKey groupKey, String threadPoolKeyOverride) { if (threadPoolKeyOverride == null) { // we don't have a property overriding the value so use either HystrixThreadPoolKey or HystrixCommandGroup if (threadPoolKey == null) { /* use HystrixCommandGroup if HystrixThreadPoolKey is null */ return HystrixThreadPoolKey.Factory.asKey(groupKey.name()); } else { return threadPoolKey; } } else { // we have a property defining the thread-pool so use it instead return HystrixThreadPoolKey.Factory.asKey(threadPoolKeyOverride); } } private static HystrixCommandMetrics initMetrics(HystrixCommandMetrics fromConstructor, HystrixCommandGroupKey groupKey, HystrixThreadPoolKey threadPoolKey, HystrixCommandKey commandKey, HystrixCommandProperties properties) { if (fromConstructor == null) { return HystrixCommandMetrics.getInstance(commandKey, groupKey, threadPoolKey, properties); } else { return fromConstructor; } } private static HystrixCircuitBreaker initCircuitBreaker(boolean enabled, HystrixCircuitBreaker fromConstructor, HystrixCommandGroupKey groupKey, HystrixCommandKey commandKey, HystrixCommandProperties properties, HystrixCommandMetrics metrics) { if (enabled) { if (fromConstructor == null) { // get the default implementation of HystrixCircuitBreaker return HystrixCircuitBreaker.Factory.getInstance(commandKey, groupKey, properties, metrics); } else { return fromConstructor; } } else { return new NoOpCircuitBreaker(); } } private static HystrixCommandExecutionHook initExecutionHook(HystrixCommandExecutionHook fromConstructor) { if (fromConstructor == null) { return new ExecutionHookDeprecationWrapper(HystrixPlugins.getInstance().getCommandExecutionHook()); } else { // used for unit testing if (fromConstructor instanceof ExecutionHookDeprecationWrapper) { return fromConstructor; } else { return new ExecutionHookDeprecationWrapper(fromConstructor); } } } private static HystrixThreadPool initThreadPool(HystrixThreadPool fromConstructor, HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults) { if (fromConstructor == null) { // get the default implementation of HystrixThreadPool return HystrixThreadPool.Factory.getInstance(threadPoolKey, threadPoolPropertiesDefaults); } else { return fromConstructor; } } private static HystrixRequestLog initRequestLog(boolean enabled, HystrixConcurrencyStrategy concurrencyStrategy) { if (enabled) { /* store reference to request log regardless of which thread later hits it */ return HystrixRequestLog.getCurrentRequest(concurrencyStrategy); } else { return null; } } /** * Allow the Collapser to mark this command instance as being used for a collapsed request and how many requests were collapsed. * * @param sizeOfBatch number of commands in request batch */ /* package */void markAsCollapsedCommand(HystrixCollapserKey collapserKey, int sizeOfBatch) { eventNotifier.markEvent(HystrixEventType.COLLAPSED, this.commandKey); executionResult = executionResult.markCollapsed(collapserKey, sizeOfBatch); } /** * Used for asynchronous execution of command with a callback by subscribing to the {@link Observable}. * <p> * This eagerly starts execution of the command the same as {@link HystrixCommand#queue()} and {@link HystrixCommand#execute()}. * <p> * A lazy {@link Observable} can be obtained from {@link #toObservable()}. * <p> * See https://github.com/Netflix/RxJava/wiki for more information. * * @return {@code Observable<R>} that executes and calls back with the result of command execution or a fallback if the command fails for any reason. * @throws HystrixRuntimeException * if a fallback does not exist * <p> * <ul> * <li>via {@code Observer#onError} if a failure occurs</li> * <li>or immediately if the command can not be queued (such as short-circuited, thread-pool/semaphore rejected)</li> * </ul> * @throws HystrixBadRequestException * via {@code Observer#onError} if invalid arguments or state were used representing a user failure, not a system failure * @throws IllegalStateException * if invoked more than once */ public Observable<R> observe() { // us a ReplaySubject to buffer the eagerly subscribed-to Observable ReplaySubject<R> subject = ReplaySubject.create(); // eagerly kick off subscription final Subscription sourceSubscription = toObservable().subscribe(subject); // return the subject that can be subscribed to later while the execution has already started return subject.doOnUnsubscribe(new Action0() { @Override public void call() { sourceSubscription.unsubscribe(); } }); } protected abstract Observable<R> getExecutionObservable(); protected abstract Observable<R> getFallbackObservable(); /** * Used for asynchronous execution of command with a callback by subscribing to the {@link Observable}. * <p> * This lazily starts execution of the command once the {@link Observable} is subscribed to. * <p> * An eager {@link Observable} can be obtained from {@link #observe()}. * <p> * See https://github.com/ReactiveX/RxJava/wiki for more information. * * @return {@code Observable<R>} that executes and calls back with the result of command execution or a fallback if the command fails for any reason. * @throws HystrixRuntimeException * if a fallback does not exist * <p> * <ul> * <li>via {@code Observer#onError} if a failure occurs</li> * <li>or immediately if the command can not be queued (such as short-circuited, thread-pool/semaphore rejected)</li> * </ul> * @throws HystrixBadRequestException * via {@code Observer#onError} if invalid arguments or state were used representing a user failure, not a system failure * @throws IllegalStateException * if invoked more than once */ public Observable<R> toObservable() { final AbstractCommand<R> _cmd = this; //doOnCompleted handler already did all of the SUCCESS work //doOnError handler already did all of the FAILURE/TIMEOUT/REJECTION/BAD_REQUEST work final Action0 terminateCommandCleanup = new Action0() { @Override public void call() { if (_cmd.commandState.compareAndSet(CommandState.OBSERVABLE_CHAIN_CREATED, CommandState.TERMINAL)) { handleCommandEnd(false); //user code never ran } else if (_cmd.commandState.compareAndSet(CommandState.USER_CODE_EXECUTED, CommandState.TERMINAL)) { handleCommandEnd(true); //user code did run } } }; //mark the command as CANCELLED and store the latency (in addition to standard cleanup) final Action0 unsubscribeCommandCleanup = new Action0() { @Override public void call() { circuitBreaker.markNonSuccess(); if (_cmd.commandState.compareAndSet(CommandState.OBSERVABLE_CHAIN_CREATED, CommandState.UNSUBSCRIBED)) { if (!_cmd.executionResult.containsTerminalEvent()) { _cmd.eventNotifier.markEvent(HystrixEventType.CANCELLED, _cmd.commandKey); try { executionHook.onUnsubscribe(_cmd); } catch (Throwable hookEx) { logger.warn("Error calling HystrixCommandExecutionHook.onUnsubscribe", hookEx); } _cmd.executionResultAtTimeOfCancellation = _cmd.executionResult .addEvent((int) (System.currentTimeMillis() - _cmd.commandStartTimestamp), HystrixEventType.CANCELLED); } handleCommandEnd(false); //user code never ran } else if (_cmd.commandState.compareAndSet(CommandState.USER_CODE_EXECUTED, CommandState.UNSUBSCRIBED)) { if (!_cmd.executionResult.containsTerminalEvent()) { _cmd.eventNotifier.markEvent(HystrixEventType.CANCELLED, _cmd.commandKey); try { executionHook.onUnsubscribe(_cmd); } catch (Throwable hookEx) { logger.warn("Error calling HystrixCommandExecutionHook.onUnsubscribe", hookEx); } _cmd.executionResultAtTimeOfCancellation = _cmd.executionResult .addEvent((int) (System.currentTimeMillis() - _cmd.commandStartTimestamp), HystrixEventType.CANCELLED); } handleCommandEnd(true); //user code did run } } }; final Func0<Observable<R>> applyHystrixSemantics = new Func0<Observable<R>>() { @Override public Observable<R> call() { if (commandState.get().equals(CommandState.UNSUBSCRIBED)) { return Observable.never(); } return applyHystrixSemantics(_cmd); } }; final Func1<R, R> wrapWithAllOnNextHooks = new Func1<R, R>() { @Override public R call(R r) { R afterFirstApplication = r; try { afterFirstApplication = executionHook.onComplete(_cmd, r); } catch (Throwable hookEx) { logger.warn("Error calling HystrixCommandExecutionHook.onComplete", hookEx); } try { return executionHook.onEmit(_cmd, afterFirstApplication); } catch (Throwable hookEx) { logger.warn("Error calling HystrixCommandExecutionHook.onEmit", hookEx); return afterFirstApplication; } } }; final Action0 fireOnCompletedHook = new Action0() { @Override public void call() { try { executionHook.onSuccess(_cmd); } catch (Throwable hookEx) { logger.warn("Error calling HystrixCommandExecutionHook.onSuccess", hookEx); } } }; return Observable.defer(new Func0<Observable<R>>() { @Override public Observable<R> call() { /* this is a stateful object so can only be used once */ if (!commandState.compareAndSet(CommandState.NOT_STARTED, CommandState.OBSERVABLE_CHAIN_CREATED)) { IllegalStateException ex = new IllegalStateException("This instance can only be executed once. Please instantiate a new instance."); //TODO make a new error type for this throw new HystrixRuntimeException(FailureType.BAD_REQUEST_EXCEPTION, _cmd.getClass(), getLogMessagePrefix() + " command executed multiple times - this is not permitted.", ex, null); } commandStartTimestamp = System.currentTimeMillis(); if (properties.requestLogEnabled().get()) { // log this command execution regardless of what happened if (currentRequestLog != null) { currentRequestLog.addExecutedCommand(_cmd); } } final boolean requestCacheEnabled = isRequestCachingEnabled(); final String cacheKey = getCacheKey(); /* try from cache first */ if (requestCacheEnabled) { HystrixCommandResponseFromCache<R> fromCache = (HystrixCommandResponseFromCache<R>) requestCache.get(cacheKey); if (fromCache != null) { isResponseFromCache = true; return handleRequestCacheHitAndEmitValues(fromCache, _cmd); } } Observable<R> hystrixObservable = Observable.defer(applyHystrixSemantics) .map(wrapWithAllOnNextHooks); Observable<R> afterCache; // put in cache if (requestCacheEnabled && cacheKey != null) { // wrap it for caching HystrixCachedObservable<R> toCache = HystrixCachedObservable.from(hystrixObservable, _cmd); HystrixCommandResponseFromCache<R> fromCache = (HystrixCommandResponseFromCache<R>) requestCache.putIfAbsent(cacheKey, toCache); if (fromCache != null) { // another thread beat us so we'll use the cached value instead toCache.unsubscribe(); isResponseFromCache = true; return handleRequestCacheHitAndEmitValues(fromCache, _cmd); } else { // we just created an ObservableCommand so we cast and return it afterCache = toCache.toObservable(); } } else { afterCache = hystrixObservable; } return afterCache .doOnTerminate(terminateCommandCleanup) // perform cleanup once (either on normal terminal state (this line), or unsubscribe (next line)) .doOnUnsubscribe(unsubscribeCommandCleanup) // perform cleanup once .doOnCompleted(fireOnCompletedHook); } }); } private Observable<R> applyHystrixSemantics(final AbstractCommand<R> _cmd) { // mark that we're starting execution on the ExecutionHook // if this hook throws an exception, then a fast-fail occurs with no fallback. No state is left inconsistent executionHook.onStart(_cmd); /* determine if we're allowed to execute */ if (circuitBreaker.attemptExecution()) { final TryableSemaphore executionSemaphore = getExecutionSemaphore(); final AtomicBoolean semaphoreHasBeenReleased = new AtomicBoolean(false); final Action0 singleSemaphoreRelease = new Action0() { @Override public void call() { if (semaphoreHasBeenReleased.compareAndSet(false, true)) { executionSemaphore.release(); } } }; final Action1<Throwable> markExceptionThrown = new Action1<Throwable>() { @Override public void call(Throwable t) { eventNotifier.markEvent(HystrixEventType.EXCEPTION_THROWN, commandKey); } }; if (executionSemaphore.tryAcquire()) { try { /* used to track userThreadExecutionTime */ executionResult = executionResult.setInvocationStartTime(System.currentTimeMillis()); return executeCommandAndObserve(_cmd) .doOnError(markExceptionThrown) .doOnTerminate(singleSemaphoreRelease) .doOnUnsubscribe(singleSemaphoreRelease); } catch (RuntimeException e) { return Observable.error(e); } } else { return handleSemaphoreRejectionViaFallback(); } } else { return handleShortCircuitViaFallback(); } } abstract protected boolean commandIsScalar(); /** * This decorates "Hystrix" functionality around the run() Observable. * * @return R */ private Observable<R> executeCommandAndObserve(final AbstractCommand<R> _cmd) { final HystrixRequestContext currentRequestContext = HystrixRequestContext.getContextForCurrentThread(); final Action1<R> markEmits = new Action1<R>() { @Override public void call(R r) { if (shouldOutputOnNextEvents()) { executionResult = executionResult.addEvent(HystrixEventType.EMIT); eventNotifier.markEvent(HystrixEventType.EMIT, commandKey); } if (commandIsScalar()) { long latency = System.currentTimeMillis() - executionResult.getStartTimestamp(); eventNotifier.markEvent(HystrixEventType.SUCCESS, commandKey); executionResult = executionResult.addEvent((int) latency, HystrixEventType.SUCCESS); eventNotifier.markCommandExecution(getCommandKey(), properties.executionIsolationStrategy().get(), (int) latency, executionResult.getOrderedList()); circuitBreaker.markSuccess(); } } }; final Action0 markOnCompleted = new Action0() { @Override public void call() { if (!commandIsScalar()) { long latency = System.currentTimeMillis() - executionResult.getStartTimestamp(); eventNotifier.markEvent(HystrixEventType.SUCCESS, commandKey); executionResult = executionResult.addEvent((int) latency, HystrixEventType.SUCCESS); eventNotifier.markCommandExecution(getCommandKey(), properties.executionIsolationStrategy().get(), (int) latency, executionResult.getOrderedList()); circuitBreaker.markSuccess(); } } }; final Func1<Throwable, Observable<R>> handleFallback = new Func1<Throwable, Observable<R>>() { @Override public Observable<R> call(Throwable t) { circuitBreaker.markNonSuccess(); Exception e = getExceptionFromThrowable(t); executionResult = executionResult.setExecutionException(e); if (e instanceof RejectedExecutionException) { return handleThreadPoolRejectionViaFallback(e); } else if (t instanceof HystrixTimeoutException) { return handleTimeoutViaFallback(); } else if (t instanceof HystrixBadRequestException) { return handleBadRequestByEmittingError(e); } else { /* * Treat HystrixBadRequestException from ExecutionHook like a plain HystrixBadRequestException. */ if (e instanceof HystrixBadRequestException) { eventNotifier.markEvent(HystrixEventType.BAD_REQUEST, commandKey); return Observable.error(e); } return handleFailureViaFallback(e); } } }; final Action1<Notification<? super R>> setRequestContext = new Action1<Notification<? super R>>() { @Override public void call(Notification<? super R> rNotification) { setRequestContextIfNeeded(currentRequestContext); } }; Observable<R> execution; if (properties.executionTimeoutEnabled().get()) { execution = executeCommandWithSpecifiedIsolation(_cmd) .lift(new HystrixObservableTimeoutOperator<R>(_cmd)); } else { execution = executeCommandWithSpecifiedIsolation(_cmd); } return execution.doOnNext(markEmits) .doOnCompleted(markOnCompleted) .onErrorResumeNext(handleFallback) .doOnEach(setRequestContext); } private Observable<R> executeCommandWithSpecifiedIsolation(final AbstractCommand<R> _cmd) { if (properties.executionIsolationStrategy().get() == ExecutionIsolationStrategy.THREAD) { // mark that we are executing in a thread (even if we end up being rejected we still were a THREAD execution and not SEMAPHORE) return Observable.defer(new Func0<Observable<R>>() { @Override public Observable<R> call() { executionResult = executionResult.setExecutionOccurred(); if (!commandState.compareAndSet(CommandState.OBSERVABLE_CHAIN_CREATED, CommandState.USER_CODE_EXECUTED)) { return Observable.error(new IllegalStateException("execution attempted while in state : " + commandState.get().name())); } metrics.markCommandStart(commandKey, threadPoolKey, ExecutionIsolationStrategy.THREAD); if (isCommandTimedOut.get() == TimedOutStatus.TIMED_OUT) { // the command timed out in the wrapping thread so we will return immediately // and not increment any of the counters below or other such logic return Observable.error(new RuntimeException("timed out before executing run()")); } if (threadState.compareAndSet(ThreadState.NOT_USING_THREAD, ThreadState.STARTED)) { //we have not been unsubscribed, so should proceed HystrixCounters.incrementGlobalConcurrentThreads(); threadPool.markThreadExecution(); // store the command that is being run endCurrentThreadExecutingCommand = Hystrix.startCurrentThreadExecutingCommand(getCommandKey()); executionResult = executionResult.setExecutedInThread(); /** * If any of these hooks throw an exception, then it appears as if the actual execution threw an error */ try { executionHook.onThreadStart(_cmd); executionHook.onRunStart(_cmd); executionHook.onExecutionStart(_cmd); return getUserExecutionObservable(_cmd); } catch (Throwable ex) { return Observable.error(ex); } } else { //command has already been unsubscribed, so return immediately return Observable.empty(); } } }).doOnTerminate(new Action0() { @Override public void call() { if (threadState.compareAndSet(ThreadState.STARTED, ThreadState.TERMINAL)) { handleThreadEnd(_cmd); } if (threadState.compareAndSet(ThreadState.NOT_USING_THREAD, ThreadState.TERMINAL)) { //if it was never started and received terminal, then no need to clean up (I don't think this is possible) } //if it was unsubscribed, then other cleanup handled it } }).doOnUnsubscribe(new Action0() { @Override public void call() { if (threadState.compareAndSet(ThreadState.STARTED, ThreadState.UNSUBSCRIBED)) { handleThreadEnd(_cmd); } if (threadState.compareAndSet(ThreadState.NOT_USING_THREAD, ThreadState.UNSUBSCRIBED)) { //if it was never started and was cancelled, then no need to clean up } //if it was terminal, then other cleanup handled it } }).subscribeOn(threadPool.getScheduler(new Func0<Boolean>() { @Override public Boolean call() { return properties.executionIsolationThreadInterruptOnTimeout().get() && _cmd.isCommandTimedOut.get() == TimedOutStatus.TIMED_OUT; } })); } else { return Observable.defer(new Func0<Observable<R>>() { @Override public Observable<R> call() { executionResult = executionResult.setExecutionOccurred(); if (!commandState.compareAndSet(CommandState.OBSERVABLE_CHAIN_CREATED, CommandState.USER_CODE_EXECUTED)) { return Observable.error(new IllegalStateException("execution attempted while in state : " + commandState.get().name())); } metrics.markCommandStart(commandKey, threadPoolKey, ExecutionIsolationStrategy.SEMAPHORE); // semaphore isolated // store the command that is being run endCurrentThreadExecutingCommand = Hystrix.startCurrentThreadExecutingCommand(getCommandKey()); try { executionHook.onRunStart(_cmd); executionHook.onExecutionStart(_cmd); return getUserExecutionObservable(_cmd); //the getUserExecutionObservable method already wraps sync exceptions, so this shouldn't throw } catch (Throwable ex) { //If the above hooks throw, then use that as the result of the run method return Observable.error(ex); } } }); } } /** * Execute <code>getFallback()</code> within protection of a semaphore that limits number of concurrent executions. * <p> * Fallback implementations shouldn't perform anything that can be blocking, but we protect against it anyways in case someone doesn't abide by the contract. * <p> * If something in the <code>getFallback()</code> implementation is latent (such as a network call) then the semaphore will cause us to start rejecting requests rather than allowing potentially * all threads to pile up and block. * * @return K * @throws UnsupportedOperationException * if getFallback() not implemented * @throws HystrixRuntimeException * if getFallback() fails (throws an Exception) or is rejected by the semaphore */ private Observable<R> getFallbackOrThrowException(final AbstractCommand<R> _cmd, final HystrixEventType eventType, final FailureType failureType, final String message, final Exception originalException) { final HystrixRequestContext requestContext = HystrixRequestContext.getContextForCurrentThread(); long latency = System.currentTimeMillis() - executionResult.getStartTimestamp(); // record the executionResult // do this before executing fallback so it can be queried from within getFallback (see See https://github.com/Netflix/Hystrix/pull/144) executionResult = executionResult.addEvent((int) latency, eventType); if (isUnrecoverable(originalException)) { logger.error("Unrecoverable Error for HystrixCommand so will throw HystrixRuntimeException and not apply fallback. ", originalException); /* executionHook for all errors */ Exception e = wrapWithOnErrorHook(failureType, originalException); return Observable.error(new HystrixRuntimeException(failureType, this.getClass(), getLogMessagePrefix() + " " + message + " and encountered unrecoverable error.", e, null)); } else { if (isRecoverableError(originalException)) { logger.warn("Recovered from java.lang.Error by serving Hystrix fallback", originalException); } if (properties.fallbackEnabled().get()) { /* fallback behavior is permitted so attempt */ final Action1<Notification<? super R>> setRequestContext = new Action1<Notification<? super R>>() { @Override public void call(Notification<? super R> rNotification) { setRequestContextIfNeeded(requestContext); } }; final Action1<R> markFallbackEmit = new Action1<R>() { @Override public void call(R r) { if (shouldOutputOnNextEvents()) { executionResult = executionResult.addEvent(HystrixEventType.FALLBACK_EMIT); eventNotifier.markEvent(HystrixEventType.FALLBACK_EMIT, commandKey); } } }; final Action0 markFallbackCompleted = new Action0() { @Override public void call() { long latency = System.currentTimeMillis() - executionResult.getStartTimestamp(); eventNotifier.markEvent(HystrixEventType.FALLBACK_SUCCESS, commandKey); executionResult = executionResult.addEvent((int) latency, HystrixEventType.FALLBACK_SUCCESS); } }; final Func1<Throwable, Observable<R>> handleFallbackError = new Func1<Throwable, Observable<R>>() { @Override public Observable<R> call(Throwable t) { /* executionHook for all errors */ Exception e = wrapWithOnErrorHook(failureType, originalException); Exception fe = getExceptionFromThrowable(t); long latency = System.currentTimeMillis() - executionResult.getStartTimestamp(); Exception toEmit; if (fe instanceof UnsupportedOperationException) { logger.debug("No fallback for HystrixCommand. ", fe); // debug only since we're throwing the exception and someone higher will do something with it eventNotifier.markEvent(HystrixEventType.FALLBACK_MISSING, commandKey); executionResult = executionResult.addEvent((int) latency, HystrixEventType.FALLBACK_MISSING); toEmit = new HystrixRuntimeException(failureType, _cmd.getClass(), getLogMessagePrefix() + " " + message + " and no fallback available.", e, fe); } else { logger.debug("HystrixCommand execution " + failureType.name() + " and fallback failed.", fe); eventNotifier.markEvent(HystrixEventType.FALLBACK_FAILURE, commandKey); executionResult = executionResult.addEvent((int) latency, HystrixEventType.FALLBACK_FAILURE); toEmit = new HystrixRuntimeException(failureType, _cmd.getClass(), getLogMessagePrefix() + " " + message + " and fallback failed.", e, fe); } // NOTE: we're suppressing fallback exception here if (shouldNotBeWrapped(originalException)) { return Observable.error(e); } return Observable.error(toEmit); } }; final TryableSemaphore fallbackSemaphore = getFallbackSemaphore(); final AtomicBoolean semaphoreHasBeenReleased = new AtomicBoolean(false); final Action0 singleSemaphoreRelease = new Action0() { @Override public void call() { if (semaphoreHasBeenReleased.compareAndSet(false, true)) { fallbackSemaphore.release(); } } }; Observable<R> fallbackExecutionChain; // acquire a permit if (fallbackSemaphore.tryAcquire()) { try { if (isFallbackUserDefined()) { executionHook.onFallbackStart(this); fallbackExecutionChain = getFallbackObservable(); } else { //same logic as above without the hook invocation fallbackExecutionChain = getFallbackObservable(); } } catch (Throwable ex) { //If hook or user-fallback throws, then use that as the result of the fallback lookup fallbackExecutionChain = Observable.error(ex); } return fallbackExecutionChain .doOnEach(setRequestContext) .lift(new FallbackHookApplication(_cmd)) .lift(new DeprecatedOnFallbackHookApplication(_cmd)) .doOnNext(markFallbackEmit) .doOnCompleted(markFallbackCompleted) .onErrorResumeNext(handleFallbackError) .doOnTerminate(singleSemaphoreRelease) .doOnUnsubscribe(singleSemaphoreRelease); } else { return handleFallbackRejectionByEmittingError(); } } else { return handleFallbackDisabledByEmittingError(originalException, failureType, message); } } } private Observable<R> getUserExecutionObservable(final AbstractCommand<R> _cmd) { Observable<R> userObservable; try { userObservable = getExecutionObservable(); } catch (Throwable ex) { // the run() method is a user provided implementation so can throw instead of using Observable.onError // so we catch it here and turn it into Observable.error userObservable = Observable.error(ex); } return userObservable .lift(new ExecutionHookApplication(_cmd)) .lift(new DeprecatedOnRunHookApplication(_cmd)); } private Observable<R> handleRequestCacheHitAndEmitValues(final HystrixCommandResponseFromCache<R> fromCache, final AbstractCommand<R> _cmd) { try { executionHook.onCacheHit(this); } catch (Throwable hookEx) { logger.warn("Error calling HystrixCommandExecutionHook.onCacheHit", hookEx); } return fromCache.toObservableWithStateCopiedInto(this) .doOnTerminate(new Action0() { @Override public void call() { if (commandState.compareAndSet(CommandState.OBSERVABLE_CHAIN_CREATED, CommandState.TERMINAL)) { cleanUpAfterResponseFromCache(false); //user code never ran } else if (commandState.compareAndSet(CommandState.USER_CODE_EXECUTED, CommandState.TERMINAL)) { cleanUpAfterResponseFromCache(true); //user code did run } } }) .doOnUnsubscribe(new Action0() { @Override public void call() { if (commandState.compareAndSet(CommandState.OBSERVABLE_CHAIN_CREATED, CommandState.UNSUBSCRIBED)) { cleanUpAfterResponseFromCache(false); //user code never ran } else if (commandState.compareAndSet(CommandState.USER_CODE_EXECUTED, CommandState.UNSUBSCRIBED)) { cleanUpAfterResponseFromCache(true); //user code did run } } }); } private void cleanUpAfterResponseFromCache(boolean commandExecutionStarted) { Reference<TimerListener> tl = timeoutTimer.get(); if (tl != null) { tl.clear(); } final long latency = System.currentTimeMillis() - commandStartTimestamp; executionResult = executionResult .addEvent(-1, HystrixEventType.RESPONSE_FROM_CACHE) .markUserThreadCompletion(latency) .setNotExecutedInThread(); ExecutionResult cacheOnlyForMetrics = ExecutionResult.from(HystrixEventType.RESPONSE_FROM_CACHE) .markUserThreadCompletion(latency); metrics.markCommandDone(cacheOnlyForMetrics, commandKey, threadPoolKey, commandExecutionStarted); eventNotifier.markEvent(HystrixEventType.RESPONSE_FROM_CACHE, commandKey); } private void handleCommandEnd(boolean commandExecutionStarted) { Reference<TimerListener> tl = timeoutTimer.get(); if (tl != null) { tl.clear(); } long userThreadLatency = System.currentTimeMillis() - commandStartTimestamp; executionResult = executionResult.markUserThreadCompletion((int) userThreadLatency); if (executionResultAtTimeOfCancellation == null) { metrics.markCommandDone(executionResult, commandKey, threadPoolKey, commandExecutionStarted); } else { metrics.markCommandDone(executionResultAtTimeOfCancellation, commandKey, threadPoolKey, commandExecutionStarted); } if (endCurrentThreadExecutingCommand != null) { endCurrentThreadExecutingCommand.call(); } } private Observable<R> handleSemaphoreRejectionViaFallback() { Exception semaphoreRejectionException = new RuntimeException("could not acquire a semaphore for execution"); executionResult = executionResult.setExecutionException(semaphoreRejectionException); eventNotifier.markEvent(HystrixEventType.SEMAPHORE_REJECTED, commandKey); logger.debug("HystrixCommand Execution Rejection by Semaphore."); // debug only since we're throwing the exception and someone higher will do something with it // retrieve a fallback or throw an exception if no fallback available return getFallbackOrThrowException(this, HystrixEventType.SEMAPHORE_REJECTED, FailureType.REJECTED_SEMAPHORE_EXECUTION, "could not acquire a semaphore for execution", semaphoreRejectionException); } private Observable<R> handleShortCircuitViaFallback() { // record that we are returning a short-circuited fallback eventNotifier.markEvent(HystrixEventType.SHORT_CIRCUITED, commandKey); // short-circuit and go directly to fallback (or throw an exception if no fallback implemented) Exception shortCircuitException = new RuntimeException("Hystrix circuit short-circuited and is OPEN"); executionResult = executionResult.setExecutionException(shortCircuitException); try { return getFallbackOrThrowException(this, HystrixEventType.SHORT_CIRCUITED, FailureType.SHORTCIRCUIT, "short-circuited", shortCircuitException); } catch (Exception e) { return Observable.error(e); } } private Observable<R> handleThreadPoolRejectionViaFallback(Exception underlying) { eventNotifier.markEvent(HystrixEventType.THREAD_POOL_REJECTED, commandKey); threadPool.markThreadRejection(); // use a fallback instead (or throw exception if not implemented) return getFallbackOrThrowException(this, HystrixEventType.THREAD_POOL_REJECTED, FailureType.REJECTED_THREAD_EXECUTION, "could not be queued for execution", underlying); } private Observable<R> handleTimeoutViaFallback() { return getFallbackOrThrowException(this, HystrixEventType.TIMEOUT, FailureType.TIMEOUT, "timed-out", new TimeoutException()); } private Observable<R> handleBadRequestByEmittingError(Exception underlying) { Exception toEmit = underlying; try { long executionLatency = System.currentTimeMillis() - executionResult.getStartTimestamp(); eventNotifier.markEvent(HystrixEventType.BAD_REQUEST, commandKey); executionResult = executionResult.addEvent((int) executionLatency, HystrixEventType.BAD_REQUEST); Exception decorated = executionHook.onError(this, FailureType.BAD_REQUEST_EXCEPTION, underlying); if (decorated instanceof HystrixBadRequestException) { toEmit = decorated; } else { logger.warn("ExecutionHook.onError returned an exception that was not an instance of HystrixBadRequestException so will be ignored.", decorated); } } catch (Exception hookEx) { logger.warn("Error calling HystrixCommandExecutionHook.onError", hookEx); } /* * HystrixBadRequestException is treated differently and allowed to propagate without any stats tracking or fallback logic */ return Observable.error(toEmit); } private Observable<R> handleFailureViaFallback(Exception underlying) { /** * All other error handling */ logger.debug("Error executing HystrixCommand.run(). Proceeding to fallback logic ...", underlying); // report failure eventNotifier.markEvent(HystrixEventType.FAILURE, commandKey); // record the exception executionResult = executionResult.setException(underlying); return getFallbackOrThrowException(this, HystrixEventType.FAILURE, FailureType.COMMAND_EXCEPTION, "failed", underlying); } private Observable<R> handleFallbackRejectionByEmittingError() { long latencyWithFallback = System.currentTimeMillis() - executionResult.getStartTimestamp(); eventNotifier.markEvent(HystrixEventType.FALLBACK_REJECTION, commandKey); executionResult = executionResult.addEvent((int) latencyWithFallback, HystrixEventType.FALLBACK_REJECTION); logger.debug("HystrixCommand Fallback Rejection."); // debug only since we're throwing the exception and someone higher will do something with it // if we couldn't acquire a permit, we "fail fast" by throwing an exception return Observable.error(new HystrixRuntimeException(FailureType.REJECTED_SEMAPHORE_FALLBACK, this.getClass(), getLogMessagePrefix() + " fallback execution rejected.", null, null)); } private Observable<R> handleFallbackDisabledByEmittingError(Exception underlying, FailureType failureType, String message) { /* fallback is disabled so throw HystrixRuntimeException */ logger.debug("Fallback disabled for HystrixCommand so will throw HystrixRuntimeException. ", underlying); // debug only since we're throwing the exception and someone higher will do something with it eventNotifier.markEvent(HystrixEventType.FALLBACK_DISABLED, commandKey); /* executionHook for all errors */ Exception wrapped = wrapWithOnErrorHook(failureType, underlying); return Observable.error(new HystrixRuntimeException(failureType, this.getClass(), getLogMessagePrefix() + " " + message + " and fallback disabled.", wrapped, null)); } protected boolean shouldNotBeWrapped(Throwable underlying) { return underlying instanceof ExceptionNotWrappedByHystrix; } /** * Returns true iff the t was caused by a java.lang.Error that is unrecoverable. Note: not all java.lang.Errors are unrecoverable. * @see <a href="https://github.com/Netflix/Hystrix/issues/713"></a> for more context * Solution taken from <a href="https://github.com/ReactiveX/RxJava/issues/748"></a> * * The specific set of Error that are considered unrecoverable are: * <ul> * <li>{@code StackOverflowError}</li> * <li>{@code VirtualMachineError}</li> * <li>{@code ThreadDeath}</li> * <li>{@code LinkageError}</li> * </ul> * * @param t throwable to check * @return true iff the t was caused by a java.lang.Error that is unrecoverable */ private boolean isUnrecoverable(Throwable t) { if (t != null && t.getCause() != null) { Throwable cause = t.getCause(); if (cause instanceof StackOverflowError) { return true; } else if (cause instanceof VirtualMachineError) { return true; } else if (cause instanceof ThreadDeath) { return true; } else if (cause instanceof LinkageError) { return true; } } return false; } private boolean isRecoverableError(Throwable t) { if (t != null && t.getCause() != null) { Throwable cause = t.getCause(); if (cause instanceof java.lang.Error) { return !isUnrecoverable(t); } } return false; } protected void handleThreadEnd(AbstractCommand<R> _cmd) { HystrixCounters.decrementGlobalConcurrentThreads(); threadPool.markThreadCompletion(); try { executionHook.onThreadComplete(_cmd); } catch (Throwable hookEx) { logger.warn("Error calling HystrixCommandExecutionHook.onThreadComplete", hookEx); } } /** * * @return if onNext events should be reported on * This affects {@link HystrixRequestLog}, and {@link HystrixEventNotifier} currently. */ protected boolean shouldOutputOnNextEvents() { return false; } private static class HystrixObservableTimeoutOperator<R> implements Operator<R, R> { final AbstractCommand<R> originalCommand; public HystrixObservableTimeoutOperator(final AbstractCommand<R> originalCommand) { this.originalCommand = originalCommand; } @Override public Subscriber<? super R> call(final Subscriber<? super R> child) { final CompositeSubscription s = new CompositeSubscription(); // if the child unsubscribes we unsubscribe our parent as well child.add(s); //capture the HystrixRequestContext upfront so that we can use it in the timeout thread later final HystrixRequestContext hystrixRequestContext = HystrixRequestContext.getContextForCurrentThread(); TimerListener listener = new TimerListener() { @Override public void tick() { // if we can go from NOT_EXECUTED to TIMED_OUT then we do the timeout codepath // otherwise it means we lost a race and the run() execution completed or did not start if (originalCommand.isCommandTimedOut.compareAndSet(TimedOutStatus.NOT_EXECUTED, TimedOutStatus.TIMED_OUT)) { // report timeout failure originalCommand.eventNotifier.markEvent(HystrixEventType.TIMEOUT, originalCommand.commandKey); // shut down the original request s.unsubscribe(); final HystrixContextRunnable timeoutRunnable = new HystrixContextRunnable(originalCommand.concurrencyStrategy, hystrixRequestContext, new Runnable() { @Override public void run() { child.onError(new HystrixTimeoutException()); } }); timeoutRunnable.run(); //if it did not start, then we need to mark a command start for concurrency metrics, and then issue the timeout } } @Override public int getIntervalTimeInMilliseconds() { return originalCommand.properties.executionTimeoutInMilliseconds().get(); } }; final Reference<TimerListener> tl = HystrixTimer.getInstance().addTimerListener(listener); // set externally so execute/queue can see this originalCommand.timeoutTimer.set(tl); /** * If this subscriber receives values it means the parent succeeded/completed */ Subscriber<R> parent = new Subscriber<R>() { @Override public void onCompleted() { if (isNotTimedOut()) { // stop timer and pass notification through tl.clear(); child.onCompleted(); } } @Override public void onError(Throwable e) { if (isNotTimedOut()) { // stop timer and pass notification through tl.clear(); child.onError(e); } } @Override public void onNext(R v) { if (isNotTimedOut()) { child.onNext(v); } } private boolean isNotTimedOut() { // if already marked COMPLETED (by onNext) or succeeds in setting to COMPLETED return originalCommand.isCommandTimedOut.get() == TimedOutStatus.COMPLETED || originalCommand.isCommandTimedOut.compareAndSet(TimedOutStatus.NOT_EXECUTED, TimedOutStatus.COMPLETED); } }; // if s is unsubscribed we want to unsubscribe the parent s.add(parent); return parent; } } private static void setRequestContextIfNeeded(final HystrixRequestContext currentRequestContext) { if (!HystrixRequestContext.isCurrentThreadInitialized()) { // even if the user Observable doesn't have context we want it set for chained operators HystrixRequestContext.setContextOnCurrentThread(currentRequestContext); } } /** * Get the TryableSemaphore this HystrixCommand should use if a fallback occurs. * * @return TryableSemaphore */ protected TryableSemaphore getFallbackSemaphore() { if (fallbackSemaphoreOverride == null) { TryableSemaphore _s = fallbackSemaphorePerCircuit.get(commandKey.name()); if (_s == null) { // we didn't find one cache so setup fallbackSemaphorePerCircuit.putIfAbsent(commandKey.name(), new TryableSemaphoreActual(properties.fallbackIsolationSemaphoreMaxConcurrentRequests())); // assign whatever got set (this or another thread) return fallbackSemaphorePerCircuit.get(commandKey.name()); } else { return _s; } } else { return fallbackSemaphoreOverride; } } /** * Get the TryableSemaphore this HystrixCommand should use for execution if not running in a separate thread. * * @return TryableSemaphore */ protected TryableSemaphore getExecutionSemaphore() { if (properties.executionIsolationStrategy().get() == ExecutionIsolationStrategy.SEMAPHORE) { if (executionSemaphoreOverride == null) { TryableSemaphore _s = executionSemaphorePerCircuit.get(commandKey.name()); if (_s == null) { // we didn't find one cache so setup executionSemaphorePerCircuit.putIfAbsent(commandKey.name(), new TryableSemaphoreActual(properties.executionIsolationSemaphoreMaxConcurrentRequests())); // assign whatever got set (this or another thread) return executionSemaphorePerCircuit.get(commandKey.name()); } else { return _s; } } else { return executionSemaphoreOverride; } } else { // return NoOp implementation since we're not using SEMAPHORE isolation return TryableSemaphoreNoOp.DEFAULT; } } /** * Each concrete implementation of AbstractCommand should return the name of the fallback method as a String * This will be used to determine if the fallback "exists" for firing the onFallbackStart/onFallbackError hooks * @deprecated This functionality is replaced by {@link #isFallbackUserDefined}, which is less implementation-aware * @return method name of fallback */ @Deprecated protected abstract String getFallbackMethodName(); protected abstract boolean isFallbackUserDefined(); /** * @return {@link HystrixCommandGroupKey} used to group together multiple {@link AbstractCommand} objects. * <p> * The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interace with, * common business purpose etc. */ public HystrixCommandGroupKey getCommandGroup() { return commandGroup; } /** * @return {@link HystrixCommandKey} identifying this command instance for statistics, circuit-breaker, properties, etc. */ public HystrixCommandKey getCommandKey() { return commandKey; } /** * @return {@link HystrixThreadPoolKey} identifying which thread-pool this command uses (when configured to run on separate threads via * {@link HystrixCommandProperties#executionIsolationStrategy()}). */ public HystrixThreadPoolKey getThreadPoolKey() { return threadPoolKey; } /* package */HystrixCircuitBreaker getCircuitBreaker() { return circuitBreaker; } /** * The {@link HystrixCommandMetrics} associated with this {@link AbstractCommand} instance. * * @return HystrixCommandMetrics */ public HystrixCommandMetrics getMetrics() { return metrics; } /** * The {@link HystrixCommandProperties} associated with this {@link AbstractCommand} instance. * * @return HystrixCommandProperties */ public HystrixCommandProperties getProperties() { return properties; } /* ******************************************************************************** */ /* ******************************************************************************** */ /* Operators that implement hook application */ /* ******************************************************************************** */ /* ******************************************************************************** */ private class ExecutionHookApplication implements Operator<R, R> { private final HystrixInvokable<R> cmd; ExecutionHookApplication(HystrixInvokable<R> cmd) { this.cmd = cmd; } @Override public Subscriber<? super R> call(final Subscriber<? super R> subscriber) { return new Subscriber<R>(subscriber) { @Override public void onCompleted() { try { executionHook.onExecutionSuccess(cmd); } catch (Throwable hookEx) { logger.warn("Error calling HystrixCommandExecutionHook.onExecutionSuccess", hookEx); } subscriber.onCompleted(); } @Override public void onError(Throwable e) { Exception wrappedEx = wrapWithOnExecutionErrorHook(e); subscriber.onError(wrappedEx); } @Override public void onNext(R r) { R wrappedValue = wrapWithOnExecutionEmitHook(r); subscriber.onNext(wrappedValue); } }; } } private class FallbackHookApplication implements Operator<R, R> { private final HystrixInvokable<R> cmd; FallbackHookApplication(HystrixInvokable<R> cmd) { this.cmd = cmd; } @Override public Subscriber<? super R> call(final Subscriber<? super R> subscriber) { return new Subscriber<R>(subscriber) { @Override public void onCompleted() { try { executionHook.onFallbackSuccess(cmd); } catch (Throwable hookEx) { logger.warn("Error calling HystrixCommandExecutionHook.onFallbackSuccess", hookEx); } subscriber.onCompleted(); } @Override public void onError(Throwable e) { Exception wrappedEx = wrapWithOnFallbackErrorHook(e); subscriber.onError(wrappedEx); } @Override public void onNext(R r) { R wrappedValue = wrapWithOnFallbackEmitHook(r); subscriber.onNext(wrappedValue); } }; } } @Deprecated //separated out to make it cleanly removable private class DeprecatedOnRunHookApplication implements Operator<R, R> { private final HystrixInvokable<R> cmd; DeprecatedOnRunHookApplication(HystrixInvokable<R> cmd) { this.cmd = cmd; } @Override public Subscriber<? super R> call(final Subscriber<? super R> subscriber) { return new Subscriber<R>(subscriber) { @Override public void onCompleted() { subscriber.onCompleted(); } @Override public void onError(Throwable t) { Exception e = getExceptionFromThrowable(t); try { Exception wrappedEx = executionHook.onRunError(cmd, e); subscriber.onError(wrappedEx); } catch (Throwable hookEx) { logger.warn("Error calling HystrixCommandExecutionHook.onRunError", hookEx); subscriber.onError(e); } } @Override public void onNext(R r) { try { R wrappedValue = executionHook.onRunSuccess(cmd, r); subscriber.onNext(wrappedValue); } catch (Throwable hookEx) { logger.warn("Error calling HystrixCommandExecutionHook.onRunSuccess", hookEx); subscriber.onNext(r); } } }; } } @Deprecated //separated out to make it cleanly removable private class DeprecatedOnFallbackHookApplication implements Operator<R, R> { private final HystrixInvokable<R> cmd; DeprecatedOnFallbackHookApplication(HystrixInvokable<R> cmd) { this.cmd = cmd; } @Override public Subscriber<? super R> call(final Subscriber<? super R> subscriber) { return new Subscriber<R>(subscriber) { @Override public void onCompleted() { subscriber.onCompleted(); } @Override public void onError(Throwable t) { //no need to call a hook here. FallbackHookApplication is already calling the proper and non-deprecated hook subscriber.onError(t); } @Override public void onNext(R r) { try { R wrappedValue = executionHook.onFallbackSuccess(cmd, r); subscriber.onNext(wrappedValue); } catch (Throwable hookEx) { logger.warn("Error calling HystrixCommandExecutionHook.onFallbackSuccess", hookEx); subscriber.onNext(r); } } }; } } private Exception wrapWithOnExecutionErrorHook(Throwable t) { Exception e = getExceptionFromThrowable(t); try { return executionHook.onExecutionError(this, e); } catch (Throwable hookEx) { logger.warn("Error calling HystrixCommandExecutionHook.onExecutionError", hookEx); return e; } } private Exception wrapWithOnFallbackErrorHook(Throwable t) { Exception e = getExceptionFromThrowable(t); try { if (isFallbackUserDefined()) { return executionHook.onFallbackError(this, e); } else { return e; } } catch (Throwable hookEx) { logger.warn("Error calling HystrixCommandExecutionHook.onFallbackError", hookEx); return e; } } private Exception wrapWithOnErrorHook(FailureType failureType, Throwable t) { Exception e = getExceptionFromThrowable(t); try { return executionHook.onError(this, failureType, e); } catch (Throwable hookEx) { logger.warn("Error calling HystrixCommandExecutionHook.onError", hookEx); return e; } } private R wrapWithOnExecutionEmitHook(R r) { try { return executionHook.onExecutionEmit(this, r); } catch (Throwable hookEx) { logger.warn("Error calling HystrixCommandExecutionHook.onExecutionEmit", hookEx); return r; } } private R wrapWithOnFallbackEmitHook(R r) { try { return executionHook.onFallbackEmit(this, r); } catch (Throwable hookEx) { logger.warn("Error calling HystrixCommandExecutionHook.onFallbackEmit", hookEx); return r; } } private R wrapWithOnEmitHook(R r) { try { return executionHook.onEmit(this, r); } catch (Throwable hookEx) { logger.warn("Error calling HystrixCommandExecutionHook.onEmit", hookEx); return r; } } /** * Take an Exception and determine whether to throw it, its cause or a new HystrixRuntimeException. * <p> * This will only throw an HystrixRuntimeException, HystrixBadRequestException, IllegalStateException * or any exception that implements ExceptionNotWrappedByHystrix. * * @param e initial exception * @return HystrixRuntimeException, HystrixBadRequestException or IllegalStateException */ protected Throwable decomposeException(Exception e) { if (e instanceof IllegalStateException) { return (IllegalStateException) e; } if (e instanceof HystrixBadRequestException) { if (shouldNotBeWrapped(e.getCause())) { return e.getCause(); } return (HystrixBadRequestException) e; } if (e.getCause() instanceof HystrixBadRequestException) { if(shouldNotBeWrapped(e.getCause().getCause())) { return e.getCause().getCause(); } return (HystrixBadRequestException) e.getCause(); } if (e instanceof HystrixRuntimeException) { return (HystrixRuntimeException) e; } // if we have an exception we know about we'll throw it directly without the wrapper exception if (e.getCause() instanceof HystrixRuntimeException) { return (HystrixRuntimeException) e.getCause(); } if (shouldNotBeWrapped(e)) { return e; } if (shouldNotBeWrapped(e.getCause())) { return e.getCause(); } // we don't know what kind of exception this is so create a generic message and throw a new HystrixRuntimeException String message = getLogMessagePrefix() + " failed while executing."; logger.debug(message, e); // debug only since we're throwing the exception and someone higher will do something with it return new HystrixRuntimeException(FailureType.COMMAND_EXCEPTION, this.getClass(), message, e, null); } /* ******************************************************************************** */ /* ******************************************************************************** */ /* TryableSemaphore */ /* ******************************************************************************** */ /* ******************************************************************************** */ /** * Semaphore that only supports tryAcquire and never blocks and that supports a dynamic permit count. * <p> * Using AtomicInteger increment/decrement instead of java.util.concurrent.Semaphore since we don't need blocking and need a custom implementation to get the dynamic permit count and since * AtomicInteger achieves the same behavior and performance without the more complex implementation of the actual Semaphore class using AbstractQueueSynchronizer. */ /* package */static class TryableSemaphoreActual implements TryableSemaphore { protected final HystrixProperty<Integer> numberOfPermits; private final AtomicInteger count = new AtomicInteger(0); public TryableSemaphoreActual(HystrixProperty<Integer> numberOfPermits) { this.numberOfPermits = numberOfPermits; } @Override public boolean tryAcquire() { int currentCount = count.incrementAndGet(); if (currentCount > numberOfPermits.get()) { count.decrementAndGet(); return false; } else { return true; } } @Override public void release() { count.decrementAndGet(); } @Override public int getNumberOfPermitsUsed() { return count.get(); } } /* package */static class TryableSemaphoreNoOp implements TryableSemaphore { public static final TryableSemaphore DEFAULT = new TryableSemaphoreNoOp(); @Override public boolean tryAcquire() { return true; } @Override public void release() { } @Override public int getNumberOfPermitsUsed() { return 0; } } /* package */static interface TryableSemaphore { /** * Use like this: * <p> * * <pre> * if (s.tryAcquire()) { * try { * // do work that is protected by 's' * } finally { * s.release(); * } * } * </pre> * * @return boolean */ public abstract boolean tryAcquire(); /** * ONLY call release if tryAcquire returned true. * <p> * * <pre> * if (s.tryAcquire()) { * try { * // do work that is protected by 's' * } finally { * s.release(); * } * } * </pre> */ public abstract void release(); public abstract int getNumberOfPermitsUsed(); } /* ******************************************************************************** */ /* ******************************************************************************** */ /* RequestCache */ /* ******************************************************************************** */ /* ******************************************************************************** */ /** * Key to be used for request caching. * <p> * By default this returns null which means "do not cache". * <p> * To enable caching override this method and return a string key uniquely representing the state of a command instance. * <p> * If multiple command instances in the same request scope match keys then only the first will be executed and all others returned from cache. * * @return cacheKey */ protected String getCacheKey() { return null; } public String getPublicCacheKey() { return getCacheKey(); } protected boolean isRequestCachingEnabled() { return properties.requestCacheEnabled().get() && getCacheKey() != null; } protected String getLogMessagePrefix() { return getCommandKey().name(); } /** * Whether the 'circuit-breaker' is open meaning that <code>execute()</code> will immediately return * the <code>getFallback()</code> response and not attempt a HystrixCommand execution. * * 4 columns are ForcedOpen | ForcedClosed | CircuitBreaker open due to health ||| Expected Result * * T | T | T ||| OPEN (true) * T | T | F ||| OPEN (true) * T | F | T ||| OPEN (true) * T | F | F ||| OPEN (true) * F | T | T ||| CLOSED (false) * F | T | F ||| CLOSED (false) * F | F | T ||| OPEN (true) * F | F | F ||| CLOSED (false) * * @return boolean */ public boolean isCircuitBreakerOpen() { return properties.circuitBreakerForceOpen().get() || (!properties.circuitBreakerForceClosed().get() && circuitBreaker.isOpen()); } /** * If this command has completed execution either successfully, via fallback or failure. * * @return boolean */ public boolean isExecutionComplete() { return commandState.get() == CommandState.TERMINAL; } /** * Whether the execution occurred in a separate thread. * <p> * This should be called only once execute()/queue()/fireOrForget() are called otherwise it will always return false. * <p> * This specifies if a thread execution actually occurred, not just if it is configured to be executed in a thread. * * @return boolean */ public boolean isExecutedInThread() { return getCommandResult().isExecutedInThread(); } /** * Whether the response was returned successfully either by executing <code>run()</code> or from cache. * * @return boolean */ public boolean isSuccessfulExecution() { return getCommandResult().getEventCounts().contains(HystrixEventType.SUCCESS); } /** * Whether the <code>run()</code> resulted in a failure (exception). * * @return boolean */ public boolean isFailedExecution() { return getCommandResult().getEventCounts().contains(HystrixEventType.FAILURE); } /** * Get the Throwable/Exception thrown that caused the failure. * <p> * If <code>isFailedExecution() == true</code> then this would represent the Exception thrown by the <code>run()</code> method. * <p> * If <code>isFailedExecution() == false</code> then this would return null. * * @return Throwable or null */ public Throwable getFailedExecutionException() { return executionResult.getException(); } /** * Get the Throwable/Exception emitted by this command instance prior to checking the fallback. * This exception instance may have been generated via a number of mechanisms: * 1) failed execution (in this case, same result as {@link #getFailedExecutionException()}. * 2) timeout * 3) short-circuit * 4) rejection * 5) bad request * * If the command execution was successful, then this exception instance is null (there was no exception) * * Note that the caller of the command may not receive this exception, as fallbacks may be served as a response to * the exception. * * @return Throwable or null */ public Throwable getExecutionException() { return executionResult.getExecutionException(); } /** * Whether the response received from was the result of some type of failure * and <code>getFallback()</code> being called. * * @return boolean */ public boolean isResponseFromFallback() { return getCommandResult().getEventCounts().contains(HystrixEventType.FALLBACK_SUCCESS); } /** * Whether the response received was the result of a timeout * and <code>getFallback()</code> being called. * * @return boolean */ public boolean isResponseTimedOut() { return getCommandResult().getEventCounts().contains(HystrixEventType.TIMEOUT); } /** * Whether the response received was a fallback as result of being * short-circuited (meaning <code>isCircuitBreakerOpen() == true</code>) and <code>getFallback()</code> being called. * * @return boolean */ public boolean isResponseShortCircuited() { return getCommandResult().getEventCounts().contains(HystrixEventType.SHORT_CIRCUITED); } /** * Whether the response is from cache and <code>run()</code> was not invoked. * * @return boolean */ public boolean isResponseFromCache() { return isResponseFromCache; } /** * Whether the response received was a fallback as result of being rejected via sempahore * * @return boolean */ public boolean isResponseSemaphoreRejected() { return getCommandResult().isResponseSemaphoreRejected(); } /** * Whether the response received was a fallback as result of being rejected via threadpool * * @return boolean */ public boolean isResponseThreadPoolRejected() { return getCommandResult().isResponseThreadPoolRejected(); } /** * Whether the response received was a fallback as result of being rejected (either via threadpool or semaphore) * * @return boolean */ public boolean isResponseRejected() { return getCommandResult().isResponseRejected(); } /** * List of HystrixCommandEventType enums representing events that occurred during execution. * <p> * Examples of events are SUCCESS, FAILURE, TIMEOUT, and SHORT_CIRCUITED * * @return {@code List<HystrixEventType>} */ public List<HystrixEventType> getExecutionEvents() { return getCommandResult().getOrderedList(); } private ExecutionResult getCommandResult() { ExecutionResult resultToReturn; if (executionResultAtTimeOfCancellation == null) { resultToReturn = executionResult; } else { resultToReturn = executionResultAtTimeOfCancellation; } if (isResponseFromCache) { resultToReturn = resultToReturn.addEvent(HystrixEventType.RESPONSE_FROM_CACHE); } return resultToReturn; } /** * Number of emissions of the execution of a command. Only interesting in the streaming case. * @return number of <code>OnNext</code> emissions by a streaming command */ @Override public int getNumberEmissions() { return getCommandResult().getEventCounts().getCount(HystrixEventType.EMIT); } /** * Number of emissions of the execution of a fallback. Only interesting in the streaming case. * @return number of <code>OnNext</code> emissions by a streaming fallback */ @Override public int getNumberFallbackEmissions() { return getCommandResult().getEventCounts().getCount(HystrixEventType.FALLBACK_EMIT); } @Override public int getNumberCollapsed() { return getCommandResult().getEventCounts().getCount(HystrixEventType.COLLAPSED); } @Override public HystrixCollapserKey getOriginatingCollapserKey() { return executionResult.getCollapserKey(); } /** * The execution time of this command instance in milliseconds, or -1 if not executed. * * @return int */ public int getExecutionTimeInMilliseconds() { return getCommandResult().getExecutionLatency(); } /** * Time in Nanos when this command instance's run method was called, or -1 if not executed * for e.g., command threw an exception * * @return long */ public long getCommandRunStartTimeInNanos() { return executionResult.getCommandRunStartTimeInNanos(); } @Override public ExecutionResult.EventCounts getEventCounts() { return getCommandResult().getEventCounts(); } protected Exception getExceptionFromThrowable(Throwable t) { Exception e; if (t instanceof Exception) { e = (Exception) t; } else { // Hystrix 1.x uses Exception, not Throwable so to prevent a breaking change Throwable will be wrapped in Exception e = new Exception("Throwable caught while executing.", t); } return e; } private static class ExecutionHookDeprecationWrapper extends HystrixCommandExecutionHook { private final HystrixCommandExecutionHook actual; ExecutionHookDeprecationWrapper(HystrixCommandExecutionHook actual) { this.actual = actual; } @Override public <T> T onEmit(HystrixInvokable<T> commandInstance, T value) { return actual.onEmit(commandInstance, value); } @Override public <T> void onSuccess(HystrixInvokable<T> commandInstance) { actual.onSuccess(commandInstance); } @Override public <T> void onExecutionStart(HystrixInvokable<T> commandInstance) { actual.onExecutionStart(commandInstance); } @Override public <T> T onExecutionEmit(HystrixInvokable<T> commandInstance, T value) { return actual.onExecutionEmit(commandInstance, value); } @Override public <T> Exception onExecutionError(HystrixInvokable<T> commandInstance, Exception e) { return actual.onExecutionError(commandInstance, e); } @Override public <T> void onExecutionSuccess(HystrixInvokable<T> commandInstance) { actual.onExecutionSuccess(commandInstance); } @Override public <T> T onFallbackEmit(HystrixInvokable<T> commandInstance, T value) { return actual.onFallbackEmit(commandInstance, value); } @Override public <T> void onFallbackSuccess(HystrixInvokable<T> commandInstance) { actual.onFallbackSuccess(commandInstance); } @Override @Deprecated public <T> void onRunStart(HystrixCommand<T> commandInstance) { actual.onRunStart(commandInstance); } @Override public <T> void onRunStart(HystrixInvokable<T> commandInstance) { HystrixCommand<T> c = getHystrixCommandFromAbstractIfApplicable(commandInstance); if (c != null) { onRunStart(c); } actual.onRunStart(commandInstance); } @Override @Deprecated public <T> T onRunSuccess(HystrixCommand<T> commandInstance, T response) { return actual.onRunSuccess(commandInstance, response); } @Override @Deprecated public <T> T onRunSuccess(HystrixInvokable<T> commandInstance, T response) { HystrixCommand<T> c = getHystrixCommandFromAbstractIfApplicable(commandInstance); if (c != null) { response = onRunSuccess(c, response); } return actual.onRunSuccess(commandInstance, response); } @Override @Deprecated public <T> Exception onRunError(HystrixCommand<T> commandInstance, Exception e) { return actual.onRunError(commandInstance, e); } @Override @Deprecated public <T> Exception onRunError(HystrixInvokable<T> commandInstance, Exception e) { HystrixCommand<T> c = getHystrixCommandFromAbstractIfApplicable(commandInstance); if (c != null) { e = onRunError(c, e); } return actual.onRunError(commandInstance, e); } @Override @Deprecated public <T> void onFallbackStart(HystrixCommand<T> commandInstance) { actual.onFallbackStart(commandInstance); } @Override public <T> void onFallbackStart(HystrixInvokable<T> commandInstance) { HystrixCommand<T> c = getHystrixCommandFromAbstractIfApplicable(commandInstance); if (c != null) { onFallbackStart(c); } actual.onFallbackStart(commandInstance); } @Override @Deprecated public <T> T onFallbackSuccess(HystrixCommand<T> commandInstance, T fallbackResponse) { return actual.onFallbackSuccess(commandInstance, fallbackResponse); } @Override @Deprecated public <T> T onFallbackSuccess(HystrixInvokable<T> commandInstance, T fallbackResponse) { HystrixCommand<T> c = getHystrixCommandFromAbstractIfApplicable(commandInstance); if (c != null) { fallbackResponse = onFallbackSuccess(c, fallbackResponse); } return actual.onFallbackSuccess(commandInstance, fallbackResponse); } @Override @Deprecated public <T> Exception onFallbackError(HystrixCommand<T> commandInstance, Exception e) { return actual.onFallbackError(commandInstance, e); } @Override public <T> Exception onFallbackError(HystrixInvokable<T> commandInstance, Exception e) { HystrixCommand<T> c = getHystrixCommandFromAbstractIfApplicable(commandInstance); if (c != null) { e = onFallbackError(c, e); } return actual.onFallbackError(commandInstance, e); } @Override @Deprecated public <T> void onStart(HystrixCommand<T> commandInstance) { actual.onStart(commandInstance); } @Override public <T> void onStart(HystrixInvokable<T> commandInstance) { HystrixCommand<T> c = getHystrixCommandFromAbstractIfApplicable(commandInstance); if (c != null) { onStart(c); } actual.onStart(commandInstance); } @Override @Deprecated public <T> T onComplete(HystrixCommand<T> commandInstance, T response) { return actual.onComplete(commandInstance, response); } @Override @Deprecated public <T> T onComplete(HystrixInvokable<T> commandInstance, T response) { HystrixCommand<T> c = getHystrixCommandFromAbstractIfApplicable(commandInstance); if (c != null) { response = onComplete(c, response); } return actual.onComplete(commandInstance, response); } @Override @Deprecated public <T> Exception onError(HystrixCommand<T> commandInstance, FailureType failureType, Exception e) { return actual.onError(commandInstance, failureType, e); } @Override public <T> Exception onError(HystrixInvokable<T> commandInstance, FailureType failureType, Exception e) { HystrixCommand<T> c = getHystrixCommandFromAbstractIfApplicable(commandInstance); if (c != null) { e = onError(c, failureType, e); } return actual.onError(commandInstance, failureType, e); } @Override @Deprecated public <T> void onThreadStart(HystrixCommand<T> commandInstance) { actual.onThreadStart(commandInstance); } @Override public <T> void onThreadStart(HystrixInvokable<T> commandInstance) { HystrixCommand<T> c = getHystrixCommandFromAbstractIfApplicable(commandInstance); if (c != null) { onThreadStart(c); } actual.onThreadStart(commandInstance); } @Override @Deprecated public <T> void onThreadComplete(HystrixCommand<T> commandInstance) { actual.onThreadComplete(commandInstance); } @Override public <T> void onThreadComplete(HystrixInvokable<T> commandInstance) { HystrixCommand<T> c = getHystrixCommandFromAbstractIfApplicable(commandInstance); if (c != null) { onThreadComplete(c); } actual.onThreadComplete(commandInstance); } @Override public <T> void onCacheHit(HystrixInvokable<T> commandInstance) { actual.onCacheHit(commandInstance); } @Override public <T> void onUnsubscribe(HystrixInvokable<T> commandInstance) { actual.onUnsubscribe(commandInstance); } @SuppressWarnings({ "unchecked", "rawtypes" }) private <T> HystrixCommand<T> getHystrixCommandFromAbstractIfApplicable(HystrixInvokable<T> commandInstance) { if (commandInstance instanceof HystrixCommand) { return (HystrixCommand) commandInstance; } else { return null; } } } }
4,622
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixCollapserKey.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; import java.util.concurrent.ConcurrentHashMap; /** * A key to represent a {@link HystrixCollapser} for monitoring, circuit-breakers, metrics publishing, caching and other such uses. * <p> * This interface is intended to work natively with Enums so that implementing code can be an enum that implements this interface. */ public interface HystrixCollapserKey { /** * The word 'name' is used instead of 'key' so that Enums can implement this interface and it work natively. * * @return String */ public String name(); public static class Factory { private Factory() { } // used to intern instances so we don't keep re-creating them millions of times for the same key private static ConcurrentHashMap<String, HystrixCollapserKey> intern = new ConcurrentHashMap<String, HystrixCollapserKey>(); /** * Retrieve (or create) an interned HystrixCollapserKey instance for a given name. * * @param name collapser name * @return HystrixCollapserKey instance that is interned (cached) so a given name will always retrieve the same instance. */ public static HystrixCollapserKey asKey(String name) { HystrixCollapserKey k = intern.get(name); if (k == null) { intern.putIfAbsent(name, new HystrixCollapserKeyDefault(name)); } return intern.get(name); } private static class HystrixCollapserKeyDefault implements HystrixCollapserKey { private String name; private HystrixCollapserKeyDefault(String name) { this.name = name; } @Override public String name() { return name; } @Override public String toString() { return name; } } } }
4,623
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixCachedObservable.java
package com.netflix.hystrix; import rx.Observable; import rx.Subscription; import rx.functions.Action0; import rx.subjects.ReplaySubject; public class HystrixCachedObservable<R> { protected final Subscription originalSubscription; protected final Observable<R> cachedObservable; private volatile int outstandingSubscriptions = 0; protected HystrixCachedObservable(final Observable<R> originalObservable) { ReplaySubject<R> replaySubject = ReplaySubject.create(); this.originalSubscription = originalObservable .subscribe(replaySubject); this.cachedObservable = replaySubject .doOnUnsubscribe(new Action0() { @Override public void call() { outstandingSubscriptions--; if (outstandingSubscriptions == 0) { originalSubscription.unsubscribe(); } } }) .doOnSubscribe(new Action0() { @Override public void call() { outstandingSubscriptions++; } }); } public static <R> HystrixCachedObservable<R> from(Observable<R> o, AbstractCommand<R> originalCommand) { return new HystrixCommandResponseFromCache<R>(o, originalCommand); } public static <R> HystrixCachedObservable<R> from(Observable<R> o) { return new HystrixCachedObservable<R>(o); } public Observable<R> toObservable() { return cachedObservable; } public void unsubscribe() { originalSubscription.unsubscribe(); } }
4,624
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixCollapserMetrics.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; import com.netflix.hystrix.metric.HystrixCollapserEvent; import com.netflix.hystrix.metric.HystrixThreadEventStream; import com.netflix.hystrix.metric.consumer.CumulativeCollapserEventCounterStream; import com.netflix.hystrix.metric.consumer.RollingCollapserBatchSizeDistributionStream; import com.netflix.hystrix.metric.consumer.RollingCollapserEventCounterStream; import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier; import com.netflix.hystrix.util.HystrixRollingNumberEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.functions.Func2; import java.util.Collection; import java.util.Collections; import java.util.concurrent.ConcurrentHashMap; /** * Used by {@link HystrixCollapser} to record metrics. * {@link HystrixEventNotifier} not hooked up yet. It may be in the future. */ public class HystrixCollapserMetrics extends HystrixMetrics { @SuppressWarnings("unused") private static final Logger logger = LoggerFactory.getLogger(HystrixCollapserMetrics.class); // String is HystrixCollapserKey.name() (we can't use HystrixCollapserKey directly as we can't guarantee it implements hashcode/equals correctly) private static final ConcurrentHashMap<String, HystrixCollapserMetrics> metrics = new ConcurrentHashMap<String, HystrixCollapserMetrics>(); /** * Get or create the {@link HystrixCollapserMetrics} instance for a given {@link HystrixCollapserKey}. * <p> * This is thread-safe and ensures only 1 {@link HystrixCollapserMetrics} per {@link HystrixCollapserKey}. * * @param key * {@link HystrixCollapserKey} of {@link HystrixCollapser} instance requesting the {@link HystrixCollapserMetrics} * @return {@link HystrixCollapserMetrics} */ public static HystrixCollapserMetrics getInstance(HystrixCollapserKey key, HystrixCollapserProperties properties) { // attempt to retrieve from cache first HystrixCollapserMetrics collapserMetrics = metrics.get(key.name()); if (collapserMetrics != null) { return collapserMetrics; } // it doesn't exist so we need to create it collapserMetrics = new HystrixCollapserMetrics(key, properties); // attempt to store it (race other threads) HystrixCollapserMetrics existing = metrics.putIfAbsent(key.name(), collapserMetrics); if (existing == null) { // we won the thread-race to store the instance we created return collapserMetrics; } else { // we lost so return 'existing' and let the one we created be garbage collected return existing; } } /** * All registered instances of {@link HystrixCollapserMetrics} * * @return {@code Collection<HystrixCollapserMetrics>} */ public static Collection<HystrixCollapserMetrics> getInstances() { return Collections.unmodifiableCollection(metrics.values()); } private static final HystrixEventType.Collapser[] ALL_EVENT_TYPES = HystrixEventType.Collapser.values(); public static final Func2<long[], HystrixCollapserEvent, long[]> appendEventToBucket = new Func2<long[], HystrixCollapserEvent, long[]>() { @Override public long[] call(long[] initialCountArray, HystrixCollapserEvent collapserEvent) { HystrixEventType.Collapser eventType = collapserEvent.getEventType(); int count = collapserEvent.getCount(); initialCountArray[eventType.ordinal()] += count; return initialCountArray; } }; public static final Func2<long[], long[], long[]> bucketAggregator = new Func2<long[], long[], long[]>() { @Override public long[] call(long[] cumulativeEvents, long[] bucketEventCounts) { for (HystrixEventType.Collapser eventType: ALL_EVENT_TYPES) { cumulativeEvents[eventType.ordinal()] += bucketEventCounts[eventType.ordinal()]; } return cumulativeEvents; } }; /** * Clears all state from metrics. If new requests come in instances will be recreated and metrics started from scratch. */ /* package */ static void reset() { metrics.clear(); } private final HystrixCollapserKey collapserKey; private final HystrixCollapserProperties properties; private final RollingCollapserEventCounterStream rollingCollapserEventCounterStream; private final CumulativeCollapserEventCounterStream cumulativeCollapserEventCounterStream; private final RollingCollapserBatchSizeDistributionStream rollingCollapserBatchSizeDistributionStream; /* package */HystrixCollapserMetrics(HystrixCollapserKey key, HystrixCollapserProperties properties) { super(null); this.collapserKey = key; this.properties = properties; rollingCollapserEventCounterStream = RollingCollapserEventCounterStream.getInstance(key, properties); cumulativeCollapserEventCounterStream = CumulativeCollapserEventCounterStream.getInstance(key, properties); rollingCollapserBatchSizeDistributionStream = RollingCollapserBatchSizeDistributionStream.getInstance(key, properties); } /** * {@link HystrixCollapserKey} these metrics represent. * * @return HystrixCollapserKey */ public HystrixCollapserKey getCollapserKey() { return collapserKey; } public HystrixCollapserProperties getProperties() { return properties; } public long getRollingCount(HystrixEventType.Collapser collapserEventType) { return rollingCollapserEventCounterStream.getLatest(collapserEventType); } public long getCumulativeCount(HystrixEventType.Collapser collapserEventType) { return cumulativeCollapserEventCounterStream.getLatest(collapserEventType); } @Override public long getCumulativeCount(HystrixRollingNumberEvent event) { return getCumulativeCount(HystrixEventType.Collapser.from(event)); } @Override public long getRollingCount(HystrixRollingNumberEvent event) { return getRollingCount(HystrixEventType.Collapser.from(event)); } /** * Retrieve the batch size for the {@link HystrixCollapser} being invoked at a given percentile. * <p> * Percentile capture and calculation is configured via {@link HystrixCollapserProperties#metricsRollingStatisticalWindowInMilliseconds()} and other related properties. * * @param percentile * Percentile such as 50, 99, or 99.5. * @return batch size */ public int getBatchSizePercentile(double percentile) { return rollingCollapserBatchSizeDistributionStream.getLatestPercentile(percentile); } public int getBatchSizeMean() { return rollingCollapserBatchSizeDistributionStream.getLatestMean(); } /** * Retrieve the shard size for the {@link HystrixCollapser} being invoked at a given percentile. * <p> * Percentile capture and calculation is configured via {@link HystrixCollapserProperties#metricsRollingStatisticalWindowInMilliseconds()} and other related properties. * * @param percentile * Percentile such as 50, 99, or 99.5. * @return batch size */ public int getShardSizePercentile(double percentile) { return 0; //return rollingCollapserUsageDistributionStream.getLatestBatchSizePercentile(percentile); } public int getShardSizeMean() { return 0; //return percentileShardSize.getMean(); } public void markRequestBatched() { } public void markResponseFromCache() { HystrixThreadEventStream.getInstance().collapserResponseFromCache(collapserKey); } public void markBatch(int batchSize) { HystrixThreadEventStream.getInstance().collapserBatchExecuted(collapserKey, batchSize); } public void markShards(int numShards) { } }
4,625
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixCommandProperties.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; import static com.netflix.hystrix.strategy.properties.HystrixPropertiesChainedProperty.forBoolean; import static com.netflix.hystrix.strategy.properties.HystrixPropertiesChainedProperty.forInteger; import static com.netflix.hystrix.strategy.properties.HystrixPropertiesChainedProperty.forString; import java.util.concurrent.Future; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.hystrix.strategy.properties.HystrixDynamicProperty; import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy; import com.netflix.hystrix.strategy.properties.HystrixProperty; import com.netflix.hystrix.util.HystrixRollingNumber; import com.netflix.hystrix.util.HystrixRollingPercentile; /** * Properties for instances of {@link HystrixCommand}. * <p> * Default implementation of methods uses Archaius (https://github.com/Netflix/archaius) */ public abstract class HystrixCommandProperties { private static final Logger logger = LoggerFactory.getLogger(HystrixCommandProperties.class); /* defaults */ /* package */ static final Integer default_metricsRollingStatisticalWindow = 10000;// default => statisticalWindow: 10000 = 10 seconds (and default of 10 buckets so each bucket is 1 second) private static final Integer default_metricsRollingStatisticalWindowBuckets = 10;// default => statisticalWindowBuckets: 10 = 10 buckets in a 10 second window so each bucket is 1 second private static final Integer default_circuitBreakerRequestVolumeThreshold = 20;// default => statisticalWindowVolumeThreshold: 20 requests in 10 seconds must occur before statistics matter private static final Integer default_circuitBreakerSleepWindowInMilliseconds = 5000;// default => sleepWindow: 5000 = 5 seconds that we will sleep before trying again after tripping the circuit private static final Integer default_circuitBreakerErrorThresholdPercentage = 50;// default => errorThresholdPercentage = 50 = if 50%+ of requests in 10 seconds are failures or latent then we will trip the circuit private static final Boolean default_circuitBreakerForceOpen = false;// default => forceCircuitOpen = false (we want to allow traffic) /* package */ static final Boolean default_circuitBreakerForceClosed = false;// default => ignoreErrors = false private static final Integer default_executionTimeoutInMilliseconds = 1000; // default => executionTimeoutInMilliseconds: 1000 = 1 second private static final Boolean default_executionTimeoutEnabled = true; private static final ExecutionIsolationStrategy default_executionIsolationStrategy = ExecutionIsolationStrategy.THREAD; private static final Boolean default_executionIsolationThreadInterruptOnTimeout = true; private static final Boolean default_executionIsolationThreadInterruptOnFutureCancel = false; private static final Boolean default_metricsRollingPercentileEnabled = true; private static final Boolean default_requestCacheEnabled = true; private static final Integer default_fallbackIsolationSemaphoreMaxConcurrentRequests = 10; private static final Boolean default_fallbackEnabled = true; private static final Integer default_executionIsolationSemaphoreMaxConcurrentRequests = 10; private static final Boolean default_requestLogEnabled = true; private static final Boolean default_circuitBreakerEnabled = true; private static final Integer default_metricsRollingPercentileWindow = 60000; // default to 1 minute for RollingPercentile private static final Integer default_metricsRollingPercentileWindowBuckets = 6; // default to 6 buckets (10 seconds each in 60 second window) private static final Integer default_metricsRollingPercentileBucketSize = 100; // default to 100 values max per bucket private static final Integer default_metricsHealthSnapshotIntervalInMilliseconds = 500; // default to 500ms as max frequency between allowing snapshots of health (error percentage etc) @SuppressWarnings("unused") private final HystrixCommandKey key; private final HystrixProperty<Integer> circuitBreakerRequestVolumeThreshold; // number of requests that must be made within a statisticalWindow before open/close decisions are made using stats private final HystrixProperty<Integer> circuitBreakerSleepWindowInMilliseconds; // milliseconds after tripping circuit before allowing retry private final HystrixProperty<Boolean> circuitBreakerEnabled; // Whether circuit breaker should be enabled. private final HystrixProperty<Integer> circuitBreakerErrorThresholdPercentage; // % of 'marks' that must be failed to trip the circuit private final HystrixProperty<Boolean> circuitBreakerForceOpen; // a property to allow forcing the circuit open (stopping all requests) private final HystrixProperty<Boolean> circuitBreakerForceClosed; // a property to allow ignoring errors and therefore never trip 'open' (ie. allow all traffic through) private final HystrixProperty<ExecutionIsolationStrategy> executionIsolationStrategy; // Whether a command should be executed in a separate thread or not. private final HystrixProperty<Integer> executionTimeoutInMilliseconds; // Timeout value in milliseconds for a command private final HystrixProperty<Boolean> executionTimeoutEnabled; //Whether timeout should be triggered private final HystrixProperty<String> executionIsolationThreadPoolKeyOverride; // What thread-pool this command should run in (if running on a separate thread). private final HystrixProperty<Integer> executionIsolationSemaphoreMaxConcurrentRequests; // Number of permits for execution semaphore private final HystrixProperty<Integer> fallbackIsolationSemaphoreMaxConcurrentRequests; // Number of permits for fallback semaphore private final HystrixProperty<Boolean> fallbackEnabled; // Whether fallback should be attempted. private final HystrixProperty<Boolean> executionIsolationThreadInterruptOnTimeout; // Whether an underlying Future/Thread (when runInSeparateThread == true) should be interrupted after a timeout private final HystrixProperty<Boolean> executionIsolationThreadInterruptOnFutureCancel; // Whether canceling an underlying Future/Thread (when runInSeparateThread == true) should interrupt the execution thread private final HystrixProperty<Integer> metricsRollingStatisticalWindowInMilliseconds; // milliseconds back that will be tracked private final HystrixProperty<Integer> metricsRollingStatisticalWindowBuckets; // number of buckets in the statisticalWindow private final HystrixProperty<Boolean> metricsRollingPercentileEnabled; // Whether monitoring should be enabled (SLA and Tracers). private final HystrixProperty<Integer> metricsRollingPercentileWindowInMilliseconds; // number of milliseconds that will be tracked in RollingPercentile private final HystrixProperty<Integer> metricsRollingPercentileWindowBuckets; // number of buckets percentileWindow will be divided into private final HystrixProperty<Integer> metricsRollingPercentileBucketSize; // how many values will be stored in each percentileWindowBucket private final HystrixProperty<Integer> metricsHealthSnapshotIntervalInMilliseconds; // time between health snapshots private final HystrixProperty<Boolean> requestLogEnabled; // whether command request logging is enabled. private final HystrixProperty<Boolean> requestCacheEnabled; // Whether request caching is enabled. /** * Isolation strategy to use when executing a {@link HystrixCommand}. * <p> * <ul> * <li>THREAD: Execute the {@link HystrixCommand#run()} method on a separate thread and restrict concurrent executions using the thread-pool size.</li> * <li>SEMAPHORE: Execute the {@link HystrixCommand#run()} method on the calling thread and restrict concurrent executions using the semaphore permit count.</li> * </ul> */ public static enum ExecutionIsolationStrategy { THREAD, SEMAPHORE } protected HystrixCommandProperties(HystrixCommandKey key) { this(key, new Setter(), "hystrix"); } protected HystrixCommandProperties(HystrixCommandKey key, HystrixCommandProperties.Setter builder) { this(key, builder, "hystrix"); } // known that we're using deprecated HystrixPropertiesChainedServoProperty until ChainedDynamicProperty exists in Archaius protected HystrixCommandProperties(HystrixCommandKey key, HystrixCommandProperties.Setter builder, String propertyPrefix) { this.key = key; this.circuitBreakerEnabled = getProperty(propertyPrefix, key, "circuitBreaker.enabled", builder.getCircuitBreakerEnabled(), default_circuitBreakerEnabled); this.circuitBreakerRequestVolumeThreshold = getProperty(propertyPrefix, key, "circuitBreaker.requestVolumeThreshold", builder.getCircuitBreakerRequestVolumeThreshold(), default_circuitBreakerRequestVolumeThreshold); this.circuitBreakerSleepWindowInMilliseconds = getProperty(propertyPrefix, key, "circuitBreaker.sleepWindowInMilliseconds", builder.getCircuitBreakerSleepWindowInMilliseconds(), default_circuitBreakerSleepWindowInMilliseconds); this.circuitBreakerErrorThresholdPercentage = getProperty(propertyPrefix, key, "circuitBreaker.errorThresholdPercentage", builder.getCircuitBreakerErrorThresholdPercentage(), default_circuitBreakerErrorThresholdPercentage); this.circuitBreakerForceOpen = getProperty(propertyPrefix, key, "circuitBreaker.forceOpen", builder.getCircuitBreakerForceOpen(), default_circuitBreakerForceOpen); this.circuitBreakerForceClosed = getProperty(propertyPrefix, key, "circuitBreaker.forceClosed", builder.getCircuitBreakerForceClosed(), default_circuitBreakerForceClosed); this.executionIsolationStrategy = getProperty(propertyPrefix, key, "execution.isolation.strategy", builder.getExecutionIsolationStrategy(), default_executionIsolationStrategy); //this property name is now misleading. //TODO figure out a good way to deprecate this property name this.executionTimeoutInMilliseconds = getProperty(propertyPrefix, key, "execution.isolation.thread.timeoutInMilliseconds", builder.getExecutionIsolationThreadTimeoutInMilliseconds(), default_executionTimeoutInMilliseconds); this.executionTimeoutEnabled = getProperty(propertyPrefix, key, "execution.timeout.enabled", builder.getExecutionTimeoutEnabled(), default_executionTimeoutEnabled); this.executionIsolationThreadInterruptOnTimeout = getProperty(propertyPrefix, key, "execution.isolation.thread.interruptOnTimeout", builder.getExecutionIsolationThreadInterruptOnTimeout(), default_executionIsolationThreadInterruptOnTimeout); this.executionIsolationThreadInterruptOnFutureCancel = getProperty(propertyPrefix, key, "execution.isolation.thread.interruptOnFutureCancel", builder.getExecutionIsolationThreadInterruptOnFutureCancel(), default_executionIsolationThreadInterruptOnFutureCancel); this.executionIsolationSemaphoreMaxConcurrentRequests = getProperty(propertyPrefix, key, "execution.isolation.semaphore.maxConcurrentRequests", builder.getExecutionIsolationSemaphoreMaxConcurrentRequests(), default_executionIsolationSemaphoreMaxConcurrentRequests); this.fallbackIsolationSemaphoreMaxConcurrentRequests = getProperty(propertyPrefix, key, "fallback.isolation.semaphore.maxConcurrentRequests", builder.getFallbackIsolationSemaphoreMaxConcurrentRequests(), default_fallbackIsolationSemaphoreMaxConcurrentRequests); this.fallbackEnabled = getProperty(propertyPrefix, key, "fallback.enabled", builder.getFallbackEnabled(), default_fallbackEnabled); this.metricsRollingStatisticalWindowInMilliseconds = getProperty(propertyPrefix, key, "metrics.rollingStats.timeInMilliseconds", builder.getMetricsRollingStatisticalWindowInMilliseconds(), default_metricsRollingStatisticalWindow); this.metricsRollingStatisticalWindowBuckets = getProperty(propertyPrefix, key, "metrics.rollingStats.numBuckets", builder.getMetricsRollingStatisticalWindowBuckets(), default_metricsRollingStatisticalWindowBuckets); this.metricsRollingPercentileEnabled = getProperty(propertyPrefix, key, "metrics.rollingPercentile.enabled", builder.getMetricsRollingPercentileEnabled(), default_metricsRollingPercentileEnabled); this.metricsRollingPercentileWindowInMilliseconds = getProperty(propertyPrefix, key, "metrics.rollingPercentile.timeInMilliseconds", builder.getMetricsRollingPercentileWindowInMilliseconds(), default_metricsRollingPercentileWindow); this.metricsRollingPercentileWindowBuckets = getProperty(propertyPrefix, key, "metrics.rollingPercentile.numBuckets", builder.getMetricsRollingPercentileWindowBuckets(), default_metricsRollingPercentileWindowBuckets); this.metricsRollingPercentileBucketSize = getProperty(propertyPrefix, key, "metrics.rollingPercentile.bucketSize", builder.getMetricsRollingPercentileBucketSize(), default_metricsRollingPercentileBucketSize); this.metricsHealthSnapshotIntervalInMilliseconds = getProperty(propertyPrefix, key, "metrics.healthSnapshot.intervalInMilliseconds", builder.getMetricsHealthSnapshotIntervalInMilliseconds(), default_metricsHealthSnapshotIntervalInMilliseconds); this.requestCacheEnabled = getProperty(propertyPrefix, key, "requestCache.enabled", builder.getRequestCacheEnabled(), default_requestCacheEnabled); this.requestLogEnabled = getProperty(propertyPrefix, key, "requestLog.enabled", builder.getRequestLogEnabled(), default_requestLogEnabled); // threadpool doesn't have a global override, only instance level makes sense this.executionIsolationThreadPoolKeyOverride = forString().add(propertyPrefix + ".command." + key.name() + ".threadPoolKeyOverride", null).build(); } /** * Whether to use a {@link HystrixCircuitBreaker} or not. If false no circuit-breaker logic will be used and all requests permitted. * <p> * This is similar in effect to {@link #circuitBreakerForceClosed()} except that continues tracking metrics and knowing whether it * should be open/closed, this property results in not even instantiating a circuit-breaker. * * @return {@code HystrixProperty<Boolean>} */ public HystrixProperty<Boolean> circuitBreakerEnabled() { return circuitBreakerEnabled; } /** * Error percentage threshold (as whole number such as 50) at which point the circuit breaker will trip open and reject requests. * <p> * It will stay tripped for the duration defined in {@link #circuitBreakerSleepWindowInMilliseconds()}; * <p> * The error percentage this is compared against comes from {@link HystrixCommandMetrics#getHealthCounts()}. * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> circuitBreakerErrorThresholdPercentage() { return circuitBreakerErrorThresholdPercentage; } /** * If true the {@link HystrixCircuitBreaker#allowRequest()} will always return true to allow requests regardless of the error percentage from {@link HystrixCommandMetrics#getHealthCounts()}. * <p> * The {@link #circuitBreakerForceOpen()} property takes precedence so if it set to true this property does nothing. * * @return {@code HystrixProperty<Boolean>} */ public HystrixProperty<Boolean> circuitBreakerForceClosed() { return circuitBreakerForceClosed; } /** * If true the {@link HystrixCircuitBreaker#allowRequest()} will always return false, causing the circuit to be open (tripped) and reject all requests. * <p> * This property takes precedence over {@link #circuitBreakerForceClosed()}; * * @return {@code HystrixProperty<Boolean>} */ public HystrixProperty<Boolean> circuitBreakerForceOpen() { return circuitBreakerForceOpen; } /** * Minimum number of requests in the {@link #metricsRollingStatisticalWindowInMilliseconds()} that must exist before the {@link HystrixCircuitBreaker} will trip. * <p> * If below this number the circuit will not trip regardless of error percentage. * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> circuitBreakerRequestVolumeThreshold() { return circuitBreakerRequestVolumeThreshold; } /** * The time in milliseconds after a {@link HystrixCircuitBreaker} trips open that it should wait before trying requests again. * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> circuitBreakerSleepWindowInMilliseconds() { return circuitBreakerSleepWindowInMilliseconds; } /** * Number of concurrent requests permitted to {@link HystrixCommand#run()}. Requests beyond the concurrent limit will be rejected. * <p> * Applicable only when {@link #executionIsolationStrategy()} == SEMAPHORE. * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> executionIsolationSemaphoreMaxConcurrentRequests() { return executionIsolationSemaphoreMaxConcurrentRequests; } /** * What isolation strategy {@link HystrixCommand#run()} will be executed with. * <p> * If {@link ExecutionIsolationStrategy#THREAD} then it will be executed on a separate thread and concurrent requests limited by the number of threads in the thread-pool. * <p> * If {@link ExecutionIsolationStrategy#SEMAPHORE} then it will be executed on the calling thread and concurrent requests limited by the semaphore count. * * @return {@code HystrixProperty<Boolean>} */ public HystrixProperty<ExecutionIsolationStrategy> executionIsolationStrategy() { return executionIsolationStrategy; } /** * Whether the execution thread should attempt an interrupt (using {@link Future#cancel}) when a thread times out. * <p> * Applicable only when {@link #executionIsolationStrategy()} == THREAD. * * @return {@code HystrixProperty<Boolean>} */ public HystrixProperty<Boolean> executionIsolationThreadInterruptOnTimeout() { return executionIsolationThreadInterruptOnTimeout; } /** * Whether the execution thread should be interrupted if the execution observable is unsubscribed or the future is cancelled via {@link Future#cancel(true)}). * <p> * Applicable only when {@link #executionIsolationStrategy()} == THREAD. * * @return {@code HystrixProperty<Boolean>} */ public HystrixProperty<Boolean> executionIsolationThreadInterruptOnFutureCancel() { return executionIsolationThreadInterruptOnFutureCancel; } /** * Allow a dynamic override of the {@link HystrixThreadPoolKey} that will dynamically change which {@link HystrixThreadPool} a {@link HystrixCommand} executes on. * <p> * Typically this should return NULL which will cause it to use the {@link HystrixThreadPoolKey} injected into a {@link HystrixCommand} or derived from the {@link HystrixCommandGroupKey}. * <p> * When set the injected or derived values will be ignored and a new {@link HystrixThreadPool} created (if necessary) and the {@link HystrixCommand} will begin using the newly defined pool. * * @return {@code HystrixProperty<String>} */ public HystrixProperty<String> executionIsolationThreadPoolKeyOverride() { return executionIsolationThreadPoolKeyOverride; } /** * * @deprecated As of release 1.4.0, replaced by {@link #executionTimeoutInMilliseconds()}. Timeout is no longer specific to thread-isolation commands, so the thread-specific name is misleading. * * Time in milliseconds at which point the command will timeout and halt execution. * <p> * If {@link #executionIsolationThreadInterruptOnTimeout} == true and the command is thread-isolated, the executing thread will be interrupted. * If the command is semaphore-isolated and a {@link HystrixObservableCommand}, that command will get unsubscribed. * <p> * * @return {@code HystrixProperty<Integer>} */ @Deprecated //prefer {@link #executionTimeoutInMilliseconds} public HystrixProperty<Integer> executionIsolationThreadTimeoutInMilliseconds() { return executionTimeoutInMilliseconds; } /** * Time in milliseconds at which point the command will timeout and halt execution. * <p> * If {@link #executionIsolationThreadInterruptOnTimeout} == true and the command is thread-isolated, the executing thread will be interrupted. * If the command is semaphore-isolated and a {@link HystrixObservableCommand}, that command will get unsubscribed. * <p> * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> executionTimeoutInMilliseconds() { /** * Calling a deprecated method here is a temporary workaround. We do this because {@link #executionTimeoutInMilliseconds()} is a new method (as of 1.4.0-rc.7) and an extending * class will not have this method. It will have {@link #executionIsolationThreadTimeoutInMilliseconds()}, however. * So, to stay compatible with an extension, we perform this redirect. */ return executionIsolationThreadTimeoutInMilliseconds(); } /** * Whether the timeout mechanism is enabled for this command * * @return {@code HystrixProperty<Boolean>} * * @since 1.4.4 */ public HystrixProperty<Boolean> executionTimeoutEnabled() { return executionTimeoutEnabled; } /** * Number of concurrent requests permitted to {@link HystrixCommand#getFallback()}. Requests beyond the concurrent limit will fail-fast and not attempt retrieving a fallback. * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> fallbackIsolationSemaphoreMaxConcurrentRequests() { return fallbackIsolationSemaphoreMaxConcurrentRequests; } /** * Whether {@link HystrixCommand#getFallback()} should be attempted when failure occurs. * * @return {@code HystrixProperty<Boolean>} * * @since 1.2 */ public HystrixProperty<Boolean> fallbackEnabled() { return fallbackEnabled; } /** * Time in milliseconds to wait between allowing health snapshots to be taken that calculate success and error percentages and affect {@link HystrixCircuitBreaker#isOpen()} status. * <p> * On high-volume circuits the continual calculation of error percentage can become CPU intensive thus this controls how often it is calculated. * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> metricsHealthSnapshotIntervalInMilliseconds() { return metricsHealthSnapshotIntervalInMilliseconds; } /** * Maximum number of values stored in each bucket of the rolling percentile. This is passed into {@link HystrixRollingPercentile} inside {@link HystrixCommandMetrics}. * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> metricsRollingPercentileBucketSize() { return metricsRollingPercentileBucketSize; } /** * Whether percentile metrics should be captured using {@link HystrixRollingPercentile} inside {@link HystrixCommandMetrics}. * * @return {@code HystrixProperty<Boolean>} */ public HystrixProperty<Boolean> metricsRollingPercentileEnabled() { return metricsRollingPercentileEnabled; } /** * Duration of percentile rolling window in milliseconds. This is passed into {@link HystrixRollingPercentile} inside {@link HystrixCommandMetrics}. * * @return {@code HystrixProperty<Integer>} * @deprecated Use {@link #metricsRollingPercentileWindowInMilliseconds()} */ public HystrixProperty<Integer> metricsRollingPercentileWindow() { return metricsRollingPercentileWindowInMilliseconds; } /** * Duration of percentile rolling window in milliseconds. This is passed into {@link HystrixRollingPercentile} inside {@link HystrixCommandMetrics}. * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> metricsRollingPercentileWindowInMilliseconds() { return metricsRollingPercentileWindowInMilliseconds; } /** * Number of buckets the rolling percentile window is broken into. This is passed into {@link HystrixRollingPercentile} inside {@link HystrixCommandMetrics}. * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> metricsRollingPercentileWindowBuckets() { return metricsRollingPercentileWindowBuckets; } /** * Duration of statistical rolling window in milliseconds. This is passed into {@link HystrixRollingNumber} inside {@link HystrixCommandMetrics}. * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> metricsRollingStatisticalWindowInMilliseconds() { return metricsRollingStatisticalWindowInMilliseconds; } /** * Number of buckets the rolling statistical window is broken into. This is passed into {@link HystrixRollingNumber} inside {@link HystrixCommandMetrics}. * * @return {@code HystrixProperty<Integer>} */ public HystrixProperty<Integer> metricsRollingStatisticalWindowBuckets() { return metricsRollingStatisticalWindowBuckets; } /** * Whether {@link HystrixCommand#getCacheKey()} should be used with {@link HystrixRequestCache} to provide de-duplication functionality via request-scoped caching. * * @return {@code HystrixProperty<Boolean>} */ public HystrixProperty<Boolean> requestCacheEnabled() { return requestCacheEnabled; } /** * Whether {@link HystrixCommand} execution and events should be logged to {@link HystrixRequestLog}. * * @return {@code HystrixProperty<Boolean>} */ public HystrixProperty<Boolean> requestLogEnabled() { return requestLogEnabled; } private static HystrixProperty<Boolean> getProperty(String propertyPrefix, HystrixCommandKey key, String instanceProperty, Boolean builderOverrideValue, Boolean defaultValue) { return forBoolean() .add(propertyPrefix + ".command." + key.name() + "." + instanceProperty, builderOverrideValue) .add(propertyPrefix + ".command.default." + instanceProperty, defaultValue) .build(); } private static HystrixProperty<Integer> getProperty(String propertyPrefix, HystrixCommandKey key, String instanceProperty, Integer builderOverrideValue, Integer defaultValue) { return forInteger() .add(propertyPrefix + ".command." + key.name() + "." + instanceProperty, builderOverrideValue) .add(propertyPrefix + ".command.default." + instanceProperty, defaultValue) .build(); } @SuppressWarnings("unused") private static HystrixProperty<String> getProperty(String propertyPrefix, HystrixCommandKey key, String instanceProperty, String builderOverrideValue, String defaultValue) { return forString() .add(propertyPrefix + ".command." + key.name() + "." + instanceProperty, builderOverrideValue) .add(propertyPrefix + ".command.default." + instanceProperty, defaultValue) .build(); } private static HystrixProperty<ExecutionIsolationStrategy> getProperty(final String propertyPrefix, final HystrixCommandKey key, final String instanceProperty, final ExecutionIsolationStrategy builderOverrideValue, final ExecutionIsolationStrategy defaultValue) { return new ExecutionIsolationStrategyHystrixProperty(builderOverrideValue, key, propertyPrefix, defaultValue, instanceProperty); } /** * HystrixProperty that converts a String to ExecutionIsolationStrategy so we remain TypeSafe. */ private static final class ExecutionIsolationStrategyHystrixProperty implements HystrixProperty<ExecutionIsolationStrategy> { private final HystrixDynamicProperty<String> property; private volatile ExecutionIsolationStrategy value; private final ExecutionIsolationStrategy defaultValue; private ExecutionIsolationStrategyHystrixProperty(ExecutionIsolationStrategy builderOverrideValue, HystrixCommandKey key, String propertyPrefix, ExecutionIsolationStrategy defaultValue, String instanceProperty) { this.defaultValue = defaultValue; String overrideValue = null; if (builderOverrideValue != null) { overrideValue = builderOverrideValue.name(); } property = forString() .add(propertyPrefix + ".command." + key.name() + "." + instanceProperty, overrideValue) .add(propertyPrefix + ".command.default." + instanceProperty, defaultValue.name()) .build(); // initialize the enum value from the property parseProperty(); // use a callback to handle changes so we only handle the parse cost on updates rather than every fetch property.addCallback(new Runnable() { @Override public void run() { // when the property value changes we'll update the value parseProperty(); } }); } @Override public ExecutionIsolationStrategy get() { return value; } private void parseProperty() { try { value = ExecutionIsolationStrategy.valueOf(property.get()); } catch (Exception e) { logger.error("Unable to derive ExecutionIsolationStrategy from property value: " + property.get(), e); // use the default value value = defaultValue; } } } /** * Factory method to retrieve the default Setter. */ public static Setter Setter() { return new Setter(); } /** * Factory method to retrieve the default Setter. * Groovy has a bug (GROOVY-6286) which does not allow method names and inner classes to have the same name * This method fixes Issue #967 and allows Groovy consumers to choose this method and not trigger the bug */ public static Setter defaultSetter() { return Setter(); } /** * Fluent interface that allows chained setting of properties that can be passed into a {@link HystrixCommand} constructor to inject instance specific property overrides. * <p> * See {@link HystrixPropertiesStrategy} for more information on order of precedence. * <p> * Example: * <p> * <pre> {@code * HystrixCommandProperties.Setter() * .withExecutionTimeoutInMilliseconds(100) * .withExecuteCommandOnSeparateThread(true); * } </pre> * * @NotThreadSafe */ public static class Setter { private Boolean circuitBreakerEnabled = null; private Integer circuitBreakerErrorThresholdPercentage = null; private Boolean circuitBreakerForceClosed = null; private Boolean circuitBreakerForceOpen = null; private Integer circuitBreakerRequestVolumeThreshold = null; private Integer circuitBreakerSleepWindowInMilliseconds = null; private Integer executionIsolationSemaphoreMaxConcurrentRequests = null; private ExecutionIsolationStrategy executionIsolationStrategy = null; private Boolean executionIsolationThreadInterruptOnTimeout = null; private Boolean executionIsolationThreadInterruptOnFutureCancel = null; private Integer executionTimeoutInMilliseconds = null; private Boolean executionTimeoutEnabled = null; private Integer fallbackIsolationSemaphoreMaxConcurrentRequests = null; private Boolean fallbackEnabled = null; private Integer metricsHealthSnapshotIntervalInMilliseconds = null; private Integer metricsRollingPercentileBucketSize = null; private Boolean metricsRollingPercentileEnabled = null; private Integer metricsRollingPercentileWindowInMilliseconds = null; private Integer metricsRollingPercentileWindowBuckets = null; /* null means it hasn't been overridden */ private Integer metricsRollingStatisticalWindowInMilliseconds = null; private Integer metricsRollingStatisticalWindowBuckets = null; private Boolean requestCacheEnabled = null; private Boolean requestLogEnabled = null; /* package */ Setter() { } public Boolean getCircuitBreakerEnabled() { return circuitBreakerEnabled; } public Integer getCircuitBreakerErrorThresholdPercentage() { return circuitBreakerErrorThresholdPercentage; } public Boolean getCircuitBreakerForceClosed() { return circuitBreakerForceClosed; } public Boolean getCircuitBreakerForceOpen() { return circuitBreakerForceOpen; } public Integer getCircuitBreakerRequestVolumeThreshold() { return circuitBreakerRequestVolumeThreshold; } public Integer getCircuitBreakerSleepWindowInMilliseconds() { return circuitBreakerSleepWindowInMilliseconds; } public Integer getExecutionIsolationSemaphoreMaxConcurrentRequests() { return executionIsolationSemaphoreMaxConcurrentRequests; } public ExecutionIsolationStrategy getExecutionIsolationStrategy() { return executionIsolationStrategy; } public Boolean getExecutionIsolationThreadInterruptOnTimeout() { return executionIsolationThreadInterruptOnTimeout; } public Boolean getExecutionIsolationThreadInterruptOnFutureCancel() { return executionIsolationThreadInterruptOnFutureCancel; } /** * @deprecated As of 1.4.0, use {@link #getExecutionTimeoutInMilliseconds()} */ @Deprecated public Integer getExecutionIsolationThreadTimeoutInMilliseconds() { return executionTimeoutInMilliseconds; } public Integer getExecutionTimeoutInMilliseconds() { return executionTimeoutInMilliseconds; } public Boolean getExecutionTimeoutEnabled() { return executionTimeoutEnabled; } public Integer getFallbackIsolationSemaphoreMaxConcurrentRequests() { return fallbackIsolationSemaphoreMaxConcurrentRequests; } public Boolean getFallbackEnabled() { return fallbackEnabled; } public Integer getMetricsHealthSnapshotIntervalInMilliseconds() { return metricsHealthSnapshotIntervalInMilliseconds; } public Integer getMetricsRollingPercentileBucketSize() { return metricsRollingPercentileBucketSize; } public Boolean getMetricsRollingPercentileEnabled() { return metricsRollingPercentileEnabled; } public Integer getMetricsRollingPercentileWindowInMilliseconds() { return metricsRollingPercentileWindowInMilliseconds; } public Integer getMetricsRollingPercentileWindowBuckets() { return metricsRollingPercentileWindowBuckets; } public Integer getMetricsRollingStatisticalWindowInMilliseconds() { return metricsRollingStatisticalWindowInMilliseconds; } public Integer getMetricsRollingStatisticalWindowBuckets() { return metricsRollingStatisticalWindowBuckets; } public Boolean getRequestCacheEnabled() { return requestCacheEnabled; } public Boolean getRequestLogEnabled() { return requestLogEnabled; } public Setter withCircuitBreakerEnabled(boolean value) { this.circuitBreakerEnabled = value; return this; } public Setter withCircuitBreakerErrorThresholdPercentage(int value) { this.circuitBreakerErrorThresholdPercentage = value; return this; } public Setter withCircuitBreakerForceClosed(boolean value) { this.circuitBreakerForceClosed = value; return this; } public Setter withCircuitBreakerForceOpen(boolean value) { this.circuitBreakerForceOpen = value; return this; } public Setter withCircuitBreakerRequestVolumeThreshold(int value) { this.circuitBreakerRequestVolumeThreshold = value; return this; } public Setter withCircuitBreakerSleepWindowInMilliseconds(int value) { this.circuitBreakerSleepWindowInMilliseconds = value; return this; } public Setter withExecutionIsolationSemaphoreMaxConcurrentRequests(int value) { this.executionIsolationSemaphoreMaxConcurrentRequests = value; return this; } public Setter withExecutionIsolationStrategy(ExecutionIsolationStrategy value) { this.executionIsolationStrategy = value; return this; } public Setter withExecutionIsolationThreadInterruptOnTimeout(boolean value) { this.executionIsolationThreadInterruptOnTimeout = value; return this; } public Setter withExecutionIsolationThreadInterruptOnFutureCancel(boolean value) { this.executionIsolationThreadInterruptOnFutureCancel = value; return this; } /** * @deprecated As of 1.4.0, replaced with {@link #withExecutionTimeoutInMilliseconds(int)}. Timeouts are no longer applied only to thread-isolated commands, so a thread-specific name is misleading */ @Deprecated public Setter withExecutionIsolationThreadTimeoutInMilliseconds(int value) { this.executionTimeoutInMilliseconds = value; return this; } public Setter withExecutionTimeoutInMilliseconds(int value) { this.executionTimeoutInMilliseconds = value; return this; } public Setter withExecutionTimeoutEnabled(boolean value) { this.executionTimeoutEnabled = value; return this; } public Setter withFallbackIsolationSemaphoreMaxConcurrentRequests(int value) { this.fallbackIsolationSemaphoreMaxConcurrentRequests = value; return this; } public Setter withFallbackEnabled(boolean value) { this.fallbackEnabled = value; return this; } public Setter withMetricsHealthSnapshotIntervalInMilliseconds(int value) { this.metricsHealthSnapshotIntervalInMilliseconds = value; return this; } public Setter withMetricsRollingPercentileBucketSize(int value) { this.metricsRollingPercentileBucketSize = value; return this; } public Setter withMetricsRollingPercentileEnabled(boolean value) { this.metricsRollingPercentileEnabled = value; return this; } public Setter withMetricsRollingPercentileWindowInMilliseconds(int value) { this.metricsRollingPercentileWindowInMilliseconds = value; return this; } public Setter withMetricsRollingPercentileWindowBuckets(int value) { this.metricsRollingPercentileWindowBuckets = value; return this; } public Setter withMetricsRollingStatisticalWindowInMilliseconds(int value) { this.metricsRollingStatisticalWindowInMilliseconds = value; return this; } public Setter withMetricsRollingStatisticalWindowBuckets(int value) { this.metricsRollingStatisticalWindowBuckets = value; return this; } public Setter withRequestCacheEnabled(boolean value) { this.requestCacheEnabled = value; return this; } public Setter withRequestLogEnabled(boolean value) { this.requestLogEnabled = value; return this; } } }
4,626
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixCommand.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; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import com.netflix.hystrix.util.Exceptions; import rx.Observable; import rx.functions.Action0; import com.netflix.hystrix.exception.HystrixBadRequestException; import com.netflix.hystrix.exception.HystrixRuntimeException; import com.netflix.hystrix.exception.HystrixRuntimeException.FailureType; import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook; import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy; import rx.functions.Func0; /** * Used to wrap code that will execute potentially risky functionality (typically meaning a service call over the network) * with fault and latency tolerance, statistics and performance metrics capture, circuit breaker and bulkhead functionality. * This command is essentially a blocking command but provides an Observable facade if used with observe() * * @param <R> * the return type * * @ThreadSafe */ public abstract class HystrixCommand<R> extends AbstractCommand<R> implements HystrixExecutable<R>, HystrixInvokableInfo<R>, HystrixObservable<R> { /** * Construct a {@link HystrixCommand} with defined {@link HystrixCommandGroupKey}. * <p> * The {@link HystrixCommandKey} will be derived from the implementing class name. * * @param group * {@link HystrixCommandGroupKey} used to group together multiple {@link HystrixCommand} objects. * <p> * The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interact with, * common business purpose etc. */ protected HystrixCommand(HystrixCommandGroupKey group) { super(group, null, null, null, null, null, null, null, null, null, null, null); } /** * Construct a {@link HystrixCommand} with defined {@link HystrixCommandGroupKey} and {@link HystrixThreadPoolKey}. * <p> * The {@link HystrixCommandKey} will be derived from the implementing class name. * * @param group * {@link HystrixCommandGroupKey} used to group together multiple {@link HystrixCommand} objects. * <p> * The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interact with, * common business purpose etc. * @param threadPool * {@link HystrixThreadPoolKey} used to identify the thread pool in which a {@link HystrixCommand} executes. */ protected HystrixCommand(HystrixCommandGroupKey group, HystrixThreadPoolKey threadPool) { super(group, null, threadPool, null, null, null, null, null, null, null, null, null); } /** * Construct a {@link HystrixCommand} with defined {@link HystrixCommandGroupKey} and thread timeout * <p> * The {@link HystrixCommandKey} will be derived from the implementing class name. * * @param group * {@link HystrixCommandGroupKey} used to group together multiple {@link HystrixCommand} objects. * <p> * The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interact with, * common business purpose etc. * @param executionIsolationThreadTimeoutInMilliseconds * Time in milliseconds at which point the calling thread will timeout (using {@link Future#get}) and walk away from the executing thread. */ protected HystrixCommand(HystrixCommandGroupKey group, int executionIsolationThreadTimeoutInMilliseconds) { super(group, null, null, null, null, HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(executionIsolationThreadTimeoutInMilliseconds), null, null, null, null, null, null); } /** * Construct a {@link HystrixCommand} with defined {@link HystrixCommandGroupKey}, {@link HystrixThreadPoolKey}, and thread timeout. * <p> * The {@link HystrixCommandKey} will be derived from the implementing class name. * * @param group * {@link HystrixCommandGroupKey} used to group together multiple {@link HystrixCommand} objects. * <p> * The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interact with, * common business purpose etc. * @param threadPool * {@link HystrixThreadPool} used to identify the thread pool in which a {@link HystrixCommand} executes. * @param executionIsolationThreadTimeoutInMilliseconds * Time in milliseconds at which point the calling thread will timeout (using {@link Future#get}) and walk away from the executing thread. */ protected HystrixCommand(HystrixCommandGroupKey group, HystrixThreadPoolKey threadPool, int executionIsolationThreadTimeoutInMilliseconds) { super(group, null, threadPool, null, null, HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(executionIsolationThreadTimeoutInMilliseconds), null, null, null, null, null, null); } /** * Construct a {@link HystrixCommand} with defined {@link Setter} that allows injecting property and strategy overrides and other optional arguments. * <p> * NOTE: The {@link HystrixCommandKey} is used to associate a {@link HystrixCommand} with {@link HystrixCircuitBreaker}, {@link HystrixCommandMetrics} and other objects. * <p> * Do not create multiple {@link HystrixCommand} implementations with the same {@link HystrixCommandKey} but different injected default properties as the first instantiated will win. * <p> * Properties passed in via {@link Setter#andCommandPropertiesDefaults} or {@link Setter#andThreadPoolPropertiesDefaults} are cached for the given {@link HystrixCommandKey} for the life of the JVM * or until {@link Hystrix#reset()} is called. Dynamic properties allow runtime changes. Read more on the <a href="https://github.com/Netflix/Hystrix/wiki/Configuration">Hystrix Wiki</a>. * * @param setter * Fluent interface for constructor arguments */ protected HystrixCommand(Setter setter) { // use 'null' to specify use the default this(setter.groupKey, setter.commandKey, setter.threadPoolKey, null, null, setter.commandPropertiesDefaults, setter.threadPoolPropertiesDefaults, null, null, null, null, null); } /** * Allow constructing a {@link HystrixCommand} with injection of most aspects of its functionality. * <p> * Some of these never have a legitimate reason for injection except in unit testing. * <p> * Most of the args will revert to a valid default if 'null' is passed in. */ /* package for testing */HystrixCommand(HystrixCommandGroupKey group, HystrixCommandKey key, HystrixThreadPoolKey threadPoolKey, HystrixCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, HystrixCommandProperties.Setter commandPropertiesDefaults, HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults, HystrixCommandMetrics metrics, TryableSemaphore fallbackSemaphore, TryableSemaphore executionSemaphore, HystrixPropertiesStrategy propertiesStrategy, HystrixCommandExecutionHook executionHook) { super(group, key, threadPoolKey, circuitBreaker, threadPool, commandPropertiesDefaults, threadPoolPropertiesDefaults, metrics, fallbackSemaphore, executionSemaphore, propertiesStrategy, executionHook); } /** * Fluent interface for arguments to the {@link HystrixCommand} constructor. * <p> * The required arguments are set via the 'with' factory method and optional arguments via the 'and' chained methods. * <p> * Example: * <pre> {@code * Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("GroupName")) .andCommandKey(HystrixCommandKey.Factory.asKey("CommandName")); * } </pre> * * @NotThreadSafe */ final public static class Setter { protected final HystrixCommandGroupKey groupKey; protected HystrixCommandKey commandKey; protected HystrixThreadPoolKey threadPoolKey; protected HystrixCommandProperties.Setter commandPropertiesDefaults; protected HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults; /** * Setter factory method containing required values. * <p> * All optional arguments can be set via the chained methods. * * @param groupKey * {@link HystrixCommandGroupKey} used to group together multiple {@link HystrixCommand} objects. * <p> * The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interace * with, * common business purpose etc. */ protected Setter(HystrixCommandGroupKey groupKey) { this.groupKey = groupKey; } /** * Setter factory method with required values. * <p> * All optional arguments can be set via the chained methods. * * @param groupKey * {@link HystrixCommandGroupKey} used to group together multiple {@link HystrixCommand} objects. * <p> * The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interace * with, * common business purpose etc. */ public static Setter withGroupKey(HystrixCommandGroupKey groupKey) { return new Setter(groupKey); } /** * @param commandKey * {@link HystrixCommandKey} used to identify a {@link HystrixCommand} instance for statistics, circuit-breaker, properties, etc. * <p> * By default this will be derived from the instance class name. * <p> * NOTE: Every unique {@link HystrixCommandKey} will result in new instances of {@link HystrixCircuitBreaker}, {@link HystrixCommandMetrics} and {@link HystrixCommandProperties}. * Thus, * the number of variants should be kept to a finite and reasonable number to avoid high-memory usage or memory leaks. * <p> * Hundreds of keys is fine, tens of thousands is probably not. * @return Setter for fluent interface via method chaining */ public Setter andCommandKey(HystrixCommandKey commandKey) { this.commandKey = commandKey; return this; } /** * @param threadPoolKey * {@link HystrixThreadPoolKey} used to define which thread-pool this command should run in (when configured to run on separate threads via * {@link HystrixCommandProperties#executionIsolationStrategy()}). * <p> * By default this is derived from the {@link HystrixCommandGroupKey} but if injected this allows multiple commands to have the same {@link HystrixCommandGroupKey} but different * thread-pools. * @return Setter for fluent interface via method chaining */ public Setter andThreadPoolKey(HystrixThreadPoolKey threadPoolKey) { this.threadPoolKey = threadPoolKey; return this; } /** * Optional * * @param commandPropertiesDefaults * {@link HystrixCommandProperties.Setter} with property overrides for this specific instance of {@link HystrixCommand}. * <p> * See the {@link HystrixPropertiesStrategy} JavaDocs for more information on properties and order of precedence. * @return Setter for fluent interface via method chaining */ public Setter andCommandPropertiesDefaults(HystrixCommandProperties.Setter commandPropertiesDefaults) { this.commandPropertiesDefaults = commandPropertiesDefaults; return this; } /** * Optional * * @param threadPoolPropertiesDefaults * {@link HystrixThreadPoolProperties.Setter} with property overrides for the {@link HystrixThreadPool} used by this specific instance of {@link HystrixCommand}. * <p> * See the {@link HystrixPropertiesStrategy} JavaDocs for more information on properties and order of precedence. * @return Setter for fluent interface via method chaining */ public Setter andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults) { this.threadPoolPropertiesDefaults = threadPoolPropertiesDefaults; return this; } } private final AtomicReference<Thread> executionThread = new AtomicReference<Thread>(); private final AtomicBoolean interruptOnFutureCancel = new AtomicBoolean(false); /** * Implement this method with code to be executed when {@link #execute()} or {@link #queue()} are invoked. * * @return R response type * @throws Exception * if command execution fails */ protected abstract R run() throws Exception; /** * If {@link #execute()} or {@link #queue()} fails in any way then this method will be invoked to provide an opportunity to return a fallback response. * <p> * This should do work that does not require network transport to produce. * <p> * In other words, this should be a static or cached result that can immediately be returned upon failure. * <p> * If network traffic is wanted for fallback (such as going to MemCache) then the fallback implementation should invoke another {@link HystrixCommand} instance that protects against that network * access and possibly has another level of fallback that does not involve network access. * <p> * DEFAULT BEHAVIOR: It throws UnsupportedOperationException. * * @return R or throw UnsupportedOperationException if not implemented */ protected R getFallback() { throw new UnsupportedOperationException("No fallback available."); } @Override final protected Observable<R> getExecutionObservable() { return Observable.defer(new Func0<Observable<R>>() { @Override public Observable<R> call() { try { return Observable.just(run()); } catch (Throwable ex) { return Observable.error(ex); } } }).doOnSubscribe(new Action0() { @Override public void call() { // Save thread on which we get subscribed so that we can interrupt it later if needed executionThread.set(Thread.currentThread()); } }); } @Override final protected Observable<R> getFallbackObservable() { return Observable.defer(new Func0<Observable<R>>() { @Override public Observable<R> call() { try { return Observable.just(getFallback()); } catch (Throwable ex) { return Observable.error(ex); } } }); } /** * Used for synchronous execution of command. * * @return R * Result of {@link #run()} execution or a fallback from {@link #getFallback()} if the command fails for any reason. * @throws HystrixRuntimeException * if a failure occurs and a fallback cannot be retrieved * @throws HystrixBadRequestException * if invalid arguments or state were used representing a user failure, not a system failure * @throws IllegalStateException * if invoked more than once */ public R execute() { try { return queue().get(); } catch (Exception e) { throw Exceptions.sneakyThrow(decomposeException(e)); } } /** * Used for asynchronous execution of command. * <p> * This will queue up the command on the thread pool and return an {@link Future} to get the result once it completes. * <p> * NOTE: If configured to not run in a separate thread, this will have the same effect as {@link #execute()} and will block. * <p> * We don't throw an exception but just flip to synchronous execution so code doesn't need to change in order to switch a command from running on a separate thread to the calling thread. * * @return {@code Future<R>} Result of {@link #run()} execution or a fallback from {@link #getFallback()} if the command fails for any reason. * @throws HystrixRuntimeException * if a fallback does not exist * <p> * <ul> * <li>via {@code Future.get()} in {@link ExecutionException#getCause()} if a failure occurs</li> * <li>or immediately if the command can not be queued (such as short-circuited, thread-pool/semaphore rejected)</li> * </ul> * @throws HystrixBadRequestException * via {@code Future.get()} in {@link ExecutionException#getCause()} if invalid arguments or state were used representing a user failure, not a system failure * @throws IllegalStateException * if invoked more than once */ public Future<R> queue() { /* * The Future returned by Observable.toBlocking().toFuture() does not implement the * interruption of the execution thread when the "mayInterrupt" flag of Future.cancel(boolean) is set to true; * thus, to comply with the contract of Future, we must wrap around it. */ final Future<R> delegate = toObservable().toBlocking().toFuture(); final Future<R> f = new Future<R>() { @Override public boolean cancel(boolean mayInterruptIfRunning) { if (delegate.isCancelled()) { return false; } if (HystrixCommand.this.getProperties().executionIsolationThreadInterruptOnFutureCancel().get()) { /* * The only valid transition here is false -> true. If there are two futures, say f1 and f2, created by this command * (which is super-weird, but has never been prohibited), and calls to f1.cancel(true) and to f2.cancel(false) are * issued by different threads, it's unclear about what value would be used by the time mayInterruptOnCancel is checked. * The most consistent way to deal with this scenario is to say that if *any* cancellation is invoked with interruption, * than that interruption request cannot be taken back. */ interruptOnFutureCancel.compareAndSet(false, mayInterruptIfRunning); } final boolean res = delegate.cancel(interruptOnFutureCancel.get()); if (!isExecutionComplete() && interruptOnFutureCancel.get()) { final Thread t = executionThread.get(); if (t != null && !t.equals(Thread.currentThread())) { t.interrupt(); } } return res; } @Override public boolean isCancelled() { return delegate.isCancelled(); } @Override public boolean isDone() { return delegate.isDone(); } @Override public R get() throws InterruptedException, ExecutionException { return delegate.get(); } @Override public R get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return delegate.get(timeout, unit); } }; /* special handling of error states that throw immediately */ if (f.isDone()) { try { f.get(); return f; } catch (Exception e) { Throwable t = decomposeException(e); if (t instanceof HystrixBadRequestException) { return f; } else if (t instanceof HystrixRuntimeException) { HystrixRuntimeException hre = (HystrixRuntimeException) t; switch (hre.getFailureType()) { case COMMAND_EXCEPTION: case TIMEOUT: // we don't throw these types from queue() only from queue().get() as they are execution errors return f; default: // these are errors we throw from queue() as they as rejection type errors throw hre; } } else { throw Exceptions.sneakyThrow(t); } } } return f; } @Override protected String getFallbackMethodName() { return "getFallback"; } @Override protected boolean isFallbackUserDefined() { Boolean containsFromMap = commandContainsFallback.get(commandKey); if (containsFromMap != null) { return containsFromMap; } else { Boolean toInsertIntoMap; try { getClass().getDeclaredMethod("getFallback"); toInsertIntoMap = true; } catch (NoSuchMethodException nsme) { toInsertIntoMap = false; } commandContainsFallback.put(commandKey, toInsertIntoMap); return toInsertIntoMap; } } @Override protected boolean commandIsScalar() { return true; } }
4,627
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixCommandResponseFromCache.java
package com.netflix.hystrix; import rx.Observable; import rx.functions.Action0; import rx.functions.Action1; import java.util.concurrent.atomic.AtomicBoolean; public class HystrixCommandResponseFromCache<R> extends HystrixCachedObservable<R> { private final AbstractCommand<R> originalCommand; /* package-private */ HystrixCommandResponseFromCache(Observable<R> originalObservable, final AbstractCommand<R> originalCommand) { super(originalObservable); this.originalCommand = originalCommand; } public Observable<R> toObservableWithStateCopiedInto(final AbstractCommand<R> commandToCopyStateInto) { final AtomicBoolean completionLogicRun = new AtomicBoolean(false); return cachedObservable .doOnError(new Action1<Throwable>() { @Override public void call(Throwable throwable) { if (completionLogicRun.compareAndSet(false, true)) { commandCompleted(commandToCopyStateInto); } } }) .doOnCompleted(new Action0() { @Override public void call() { if (completionLogicRun.compareAndSet(false, true)) { commandCompleted(commandToCopyStateInto); } } }) .doOnUnsubscribe(new Action0() { @Override public void call() { if (completionLogicRun.compareAndSet(false, true)) { commandUnsubscribed(commandToCopyStateInto); } } }); } private void commandCompleted(final AbstractCommand<R> commandToCopyStateInto) { commandToCopyStateInto.executionResult = originalCommand.executionResult; } private void commandUnsubscribed(final AbstractCommand<R> commandToCopyStateInto) { commandToCopyStateInto.executionResult = commandToCopyStateInto.executionResult.addEvent(HystrixEventType.CANCELLED); commandToCopyStateInto.executionResult = commandToCopyStateInto.executionResult.setExecutionLatency(-1); } }
4,628
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixKey.java
package com.netflix.hystrix; /** * Basic class for hystrix keys */ public interface HystrixKey { /** * The word 'name' is used instead of 'key' so that Enums can implement this interface and it work natively. * * @return String */ String name(); /** * Default implementation of the interface */ abstract class HystrixKeyDefault implements HystrixKey { private final String name; public HystrixKeyDefault(String name) { this.name = name; } @Override public String name() { return name; } @Override public String toString() { return name; } } }
4,629
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixRequestCache.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; import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableDefault; import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableHolder; import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableLifecycle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.internal.operators.CachedObservable; import java.util.concurrent.ConcurrentHashMap; /** * Cache that is scoped to the current request as managed by {@link HystrixRequestVariableDefault}. * <p> * This is used for short-lived caching of {@link HystrixCommand} instances to allow de-duping of command executions within a request. */ public class HystrixRequestCache { @SuppressWarnings("unused") private static final Logger logger = LoggerFactory.getLogger(HystrixRequestCache.class); // the String key must be: HystrixRequestCache.prefix + concurrencyStrategy + cacheKey private final static ConcurrentHashMap<RequestCacheKey, HystrixRequestCache> caches = new ConcurrentHashMap<RequestCacheKey, HystrixRequestCache>(); private final RequestCacheKey rcKey; private final HystrixConcurrencyStrategy concurrencyStrategy; /** * A ConcurrentHashMap per 'prefix' and per request scope that is used to to dedupe requests in the same request. * <p> * Key => CommandPrefix + CacheKey : Future<?> from queue() */ private static final HystrixRequestVariableHolder<ConcurrentHashMap<ValueCacheKey, HystrixCachedObservable<?>>> requestVariableForCache = new HystrixRequestVariableHolder<ConcurrentHashMap<ValueCacheKey, HystrixCachedObservable<?>>>(new HystrixRequestVariableLifecycle<ConcurrentHashMap<ValueCacheKey, HystrixCachedObservable<?>>>() { @Override public ConcurrentHashMap<ValueCacheKey, HystrixCachedObservable<?>> initialValue() { return new ConcurrentHashMap<ValueCacheKey, HystrixCachedObservable<?>>(); } @Override public void shutdown(ConcurrentHashMap<ValueCacheKey, HystrixCachedObservable<?>> value) { // nothing to shutdown } }); private HystrixRequestCache(RequestCacheKey rcKey, HystrixConcurrencyStrategy concurrencyStrategy) { this.rcKey = rcKey; this.concurrencyStrategy = concurrencyStrategy; } public static HystrixRequestCache getInstance(HystrixCommandKey key, HystrixConcurrencyStrategy concurrencyStrategy) { return getInstance(new RequestCacheKey(key, concurrencyStrategy), concurrencyStrategy); } public static HystrixRequestCache getInstance(HystrixCollapserKey key, HystrixConcurrencyStrategy concurrencyStrategy) { return getInstance(new RequestCacheKey(key, concurrencyStrategy), concurrencyStrategy); } private static HystrixRequestCache getInstance(RequestCacheKey rcKey, HystrixConcurrencyStrategy concurrencyStrategy) { HystrixRequestCache c = caches.get(rcKey); if (c == null) { HystrixRequestCache newRequestCache = new HystrixRequestCache(rcKey, concurrencyStrategy); HystrixRequestCache existing = caches.putIfAbsent(rcKey, newRequestCache); if (existing == null) { // we won so use the new one c = newRequestCache; } else { // we lost so use the existing c = existing; } } return c; } /** * Retrieve a cached Future for this request scope if a matching command has already been executed/queued. * * @return {@code Future<T>} */ // suppressing warnings because we are using a raw Future since it's in a heterogeneous ConcurrentHashMap cache @SuppressWarnings({ "unchecked" }) /* package */<T> HystrixCachedObservable<T> get(String cacheKey) { ValueCacheKey key = getRequestCacheKey(cacheKey); if (key != null) { ConcurrentHashMap<ValueCacheKey, HystrixCachedObservable<?>> cacheInstance = requestVariableForCache.get(concurrencyStrategy); if (cacheInstance == null) { throw new IllegalStateException("Request caching is not available. Maybe you need to initialize the HystrixRequestContext?"); } /* look for the stored value */ return (HystrixCachedObservable<T>) cacheInstance.get(key); } return null; } /** * Put the Future in the cache if it does not already exist. * <p> * If this method returns a non-null value then another thread won the race and it should be returned instead of proceeding with execution of the new Future. * * @param cacheKey * key as defined by {@link HystrixCommand#getCacheKey()} * @param f * Future to be cached * * @return null if nothing else was in the cache (or this {@link HystrixCommand} does not have a cacheKey) or previous value if another thread beat us to adding to the cache */ // suppressing warnings because we are using a raw Future since it's in a heterogeneous ConcurrentHashMap cache @SuppressWarnings({ "unchecked" }) /* package */<T> HystrixCachedObservable<T> putIfAbsent(String cacheKey, HystrixCachedObservable<T> f) { ValueCacheKey key = getRequestCacheKey(cacheKey); if (key != null) { /* look for the stored value */ ConcurrentHashMap<ValueCacheKey, HystrixCachedObservable<?>> cacheInstance = requestVariableForCache.get(concurrencyStrategy); if (cacheInstance == null) { throw new IllegalStateException("Request caching is not available. Maybe you need to initialize the HystrixRequestContext?"); } HystrixCachedObservable<T> alreadySet = (HystrixCachedObservable<T>) cacheInstance.putIfAbsent(key, f); if (alreadySet != null) { // someone beat us so we didn't cache this return alreadySet; } } // we either set it in the cache or do not have a cache key return null; } /** * Clear the cache for a given cacheKey. * * @param cacheKey * key as defined by {@link HystrixCommand#getCacheKey()} */ public void clear(String cacheKey) { ValueCacheKey key = getRequestCacheKey(cacheKey); if (key != null) { ConcurrentHashMap<ValueCacheKey, HystrixCachedObservable<?>> cacheInstance = requestVariableForCache.get(concurrencyStrategy); if (cacheInstance == null) { throw new IllegalStateException("Request caching is not available. Maybe you need to initialize the HystrixRequestContext?"); } /* remove this cache key */ cacheInstance.remove(key); } } /** * Request CacheKey: HystrixRequestCache.prefix + concurrencyStrategy + HystrixCommand.getCacheKey (as injected via get/put to this class) * <p> * We prefix with {@link HystrixCommandKey} or {@link HystrixCollapserKey} since the cache is heterogeneous and we don't want to accidentally return cached Futures from different * types. * * @return ValueCacheKey */ private ValueCacheKey getRequestCacheKey(String cacheKey) { if (cacheKey != null) { /* create the cache key we will use to retrieve/store that include the type key prefix */ return new ValueCacheKey(rcKey, cacheKey); } return null; } private static class ValueCacheKey { private final RequestCacheKey rvKey; private final String valueCacheKey; private ValueCacheKey(RequestCacheKey rvKey, String valueCacheKey) { this.rvKey = rvKey; this.valueCacheKey = valueCacheKey; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((rvKey == null) ? 0 : rvKey.hashCode()); result = prime * result + ((valueCacheKey == null) ? 0 : valueCacheKey.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ValueCacheKey other = (ValueCacheKey) obj; if (rvKey == null) { if (other.rvKey != null) return false; } else if (!rvKey.equals(other.rvKey)) return false; if (valueCacheKey == null) { if (other.valueCacheKey != null) return false; } else if (!valueCacheKey.equals(other.valueCacheKey)) return false; return true; } } private static class RequestCacheKey { private final short type; // used to differentiate between Collapser/Command if key is same between them private final String key; private final HystrixConcurrencyStrategy concurrencyStrategy; private RequestCacheKey(HystrixCommandKey commandKey, HystrixConcurrencyStrategy concurrencyStrategy) { type = 1; if (commandKey == null) { this.key = null; } else { this.key = commandKey.name(); } this.concurrencyStrategy = concurrencyStrategy; } private RequestCacheKey(HystrixCollapserKey collapserKey, HystrixConcurrencyStrategy concurrencyStrategy) { type = 2; if (collapserKey == null) { this.key = null; } else { this.key = collapserKey.name(); } this.concurrencyStrategy = concurrencyStrategy; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((concurrencyStrategy == null) ? 0 : concurrencyStrategy.hashCode()); result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + type; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RequestCacheKey other = (RequestCacheKey) obj; if (type != other.type) return false; if (key == null) { if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (concurrencyStrategy == null) { if (other.concurrencyStrategy != null) return false; } else if (!concurrencyStrategy.equals(other.concurrencyStrategy)) return false; return true; } } }
4,630
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixCounters.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 java.util.concurrent.atomic.AtomicInteger; /** * Class with global statistics on Hystrix runtime behavior. * All of the data available via this class is static and scoped at the JVM level */ public class HystrixCounters { private static final AtomicInteger concurrentThreadsExecuting = new AtomicInteger(0); /* package-private */ static int incrementGlobalConcurrentThreads() { return concurrentThreadsExecuting.incrementAndGet(); } /* package-private */ static int decrementGlobalConcurrentThreads() { return concurrentThreadsExecuting.decrementAndGet(); } /** * Return the number of currently-executing Hystrix threads * @return number of currently-executing Hystrix threads */ public static int getGlobalConcurrentThreadsExecuting() { return concurrentThreadsExecuting.get(); } /** * Return the number of unique {@link HystrixCommand}s that have been registered * @return number of unique {@link HystrixCommand}s that have been registered */ public static int getCommandCount() { return HystrixCommandKey.Factory.getCommandCount(); } /** * Return the number of unique {@link HystrixThreadPool}s that have been registered * @return number of unique {@link HystrixThreadPool}s that have been registered */ public static int getThreadPoolCount() { return HystrixThreadPoolKey.Factory.getThreadPoolCount(); } /** * Return the number of unique {@link HystrixCommandGroupKey}s that have been registered * @return number of unique {@link HystrixCommandGroupKey}s that have been registered */ public static int getGroupCount() { return HystrixCommandGroupKey.Factory.getGroupCount(); } }
4,631
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixCircuitBreaker.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; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import com.netflix.hystrix.HystrixCommandMetrics.HealthCounts; import rx.Subscriber; import rx.Subscription; /** * Circuit-breaker logic that is hooked into {@link HystrixCommand} execution and will stop allowing executions if failures have gone past the defined threshold. * <p> * The default (and only) implementation will then allow a single retry after a defined sleepWindow until the execution * succeeds at which point it will again close the circuit and allow executions again. */ public interface HystrixCircuitBreaker { /** * Every {@link HystrixCommand} requests asks this if it is allowed to proceed or not. It is idempotent and does * not modify any internal state, and takes into account the half-open logic which allows some requests through * after the circuit has been opened * * @return boolean whether a request should be permitted */ boolean allowRequest(); /** * Whether the circuit is currently open (tripped). * * @return boolean state of circuit breaker */ boolean isOpen(); /** * Invoked on successful executions from {@link HystrixCommand} as part of feedback mechanism when in a half-open state. */ void markSuccess(); /** * Invoked on unsuccessful executions from {@link HystrixCommand} as part of feedback mechanism when in a half-open state. */ void markNonSuccess(); /** * Invoked at start of command execution to attempt an execution. This is non-idempotent - it may modify internal * state. */ boolean attemptExecution(); /** * @ExcludeFromJavadoc * @ThreadSafe */ class Factory { // String is HystrixCommandKey.name() (we can't use HystrixCommandKey directly as we can't guarantee it implements hashcode/equals correctly) private static ConcurrentHashMap<String, HystrixCircuitBreaker> circuitBreakersByCommand = new ConcurrentHashMap<String, HystrixCircuitBreaker>(); /** * Get the {@link HystrixCircuitBreaker} instance for a given {@link HystrixCommandKey}. * <p> * This is thread-safe and ensures only 1 {@link HystrixCircuitBreaker} per {@link HystrixCommandKey}. * * @param key * {@link HystrixCommandKey} of {@link HystrixCommand} instance requesting the {@link HystrixCircuitBreaker} * @param group * Pass-thru to {@link HystrixCircuitBreaker} * @param properties * Pass-thru to {@link HystrixCircuitBreaker} * @param metrics * Pass-thru to {@link HystrixCircuitBreaker} * @return {@link HystrixCircuitBreaker} for {@link HystrixCommandKey} */ public static HystrixCircuitBreaker getInstance(HystrixCommandKey key, HystrixCommandGroupKey group, HystrixCommandProperties properties, HystrixCommandMetrics metrics) { // this should find it for all but the first time HystrixCircuitBreaker previouslyCached = circuitBreakersByCommand.get(key.name()); if (previouslyCached != null) { return previouslyCached; } // if we get here this is the first time so we need to initialize // Create and add to the map ... use putIfAbsent to atomically handle the possible race-condition of // 2 threads hitting this point at the same time and let ConcurrentHashMap provide us our thread-safety // If 2 threads hit here only one will get added and the other will get a non-null response instead. HystrixCircuitBreaker cbForCommand = circuitBreakersByCommand.putIfAbsent(key.name(), new HystrixCircuitBreakerImpl(key, group, properties, metrics)); if (cbForCommand == null) { // this means the putIfAbsent step just created a new one so let's retrieve and return it return circuitBreakersByCommand.get(key.name()); } else { // this means a race occurred and while attempting to 'put' another one got there before // and we instead retrieved it and will now return it return cbForCommand; } } /** * Get the {@link HystrixCircuitBreaker} instance for a given {@link HystrixCommandKey} or null if none exists. * * @param key * {@link HystrixCommandKey} of {@link HystrixCommand} instance requesting the {@link HystrixCircuitBreaker} * @return {@link HystrixCircuitBreaker} for {@link HystrixCommandKey} */ public static HystrixCircuitBreaker getInstance(HystrixCommandKey key) { return circuitBreakersByCommand.get(key.name()); } /** * Clears all circuit breakers. If new requests come in instances will be recreated. */ /* package */static void reset() { circuitBreakersByCommand.clear(); } } /** * The default production implementation of {@link HystrixCircuitBreaker}. * * @ExcludeFromJavadoc * @ThreadSafe */ /* package */class HystrixCircuitBreakerImpl implements HystrixCircuitBreaker { private final HystrixCommandProperties properties; private final HystrixCommandMetrics metrics; enum Status { CLOSED, OPEN, HALF_OPEN; } private final AtomicReference<Status> status = new AtomicReference<Status>(Status.CLOSED); private final AtomicLong circuitOpened = new AtomicLong(-1); private final AtomicReference<Subscription> activeSubscription = new AtomicReference<Subscription>(null); protected HystrixCircuitBreakerImpl(HystrixCommandKey key, HystrixCommandGroupKey commandGroup, final HystrixCommandProperties properties, HystrixCommandMetrics metrics) { this.properties = properties; this.metrics = metrics; //On a timer, this will set the circuit between OPEN/CLOSED as command executions occur Subscription s = subscribeToStream(); activeSubscription.set(s); } private Subscription subscribeToStream() { /* * This stream will recalculate the OPEN/CLOSED status on every onNext from the health stream */ return metrics.getHealthCountsStream() .observe() .subscribe(new Subscriber<HealthCounts>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(HealthCounts hc) { // check if we are past the statisticalWindowVolumeThreshold if (hc.getTotalRequests() < properties.circuitBreakerRequestVolumeThreshold().get()) { // we are not past the minimum volume threshold for the stat window, // so no change to circuit status. // if it was CLOSED, it stays CLOSED // if it was half-open, we need to wait for a successful command execution // if it was open, we need to wait for sleep window to elapse } else { if (hc.getErrorPercentage() < properties.circuitBreakerErrorThresholdPercentage().get()) { //we are not past the minimum error threshold for the stat window, // so no change to circuit status. // if it was CLOSED, it stays CLOSED // if it was half-open, we need to wait for a successful command execution // if it was open, we need to wait for sleep window to elapse } else { // our failure rate is too high, we need to set the state to OPEN if (status.compareAndSet(Status.CLOSED, Status.OPEN)) { circuitOpened.set(System.currentTimeMillis()); } } } } }); } @Override public void markSuccess() { if (status.compareAndSet(Status.HALF_OPEN, Status.CLOSED)) { //This thread wins the race to close the circuit - it resets the stream to start it over from 0 metrics.resetStream(); Subscription previousSubscription = activeSubscription.get(); if (previousSubscription != null) { previousSubscription.unsubscribe(); } Subscription newSubscription = subscribeToStream(); activeSubscription.set(newSubscription); circuitOpened.set(-1L); } } @Override public void markNonSuccess() { if (status.compareAndSet(Status.HALF_OPEN, Status.OPEN)) { //This thread wins the race to re-open the circuit - it resets the start time for the sleep window circuitOpened.set(System.currentTimeMillis()); } } @Override public boolean isOpen() { if (properties.circuitBreakerForceOpen().get()) { return true; } if (properties.circuitBreakerForceClosed().get()) { return false; } return circuitOpened.get() >= 0; } @Override public boolean allowRequest() { if (properties.circuitBreakerForceOpen().get()) { return false; } if (properties.circuitBreakerForceClosed().get()) { return true; } if (circuitOpened.get() == -1) { return true; } else { if (status.get().equals(Status.HALF_OPEN)) { return false; } else { return isAfterSleepWindow(); } } } private boolean isAfterSleepWindow() { final long circuitOpenTime = circuitOpened.get(); final long currentTime = System.currentTimeMillis(); final long sleepWindowTime = properties.circuitBreakerSleepWindowInMilliseconds().get(); return currentTime > circuitOpenTime + sleepWindowTime; } @Override public boolean attemptExecution() { if (properties.circuitBreakerForceOpen().get()) { return false; } if (properties.circuitBreakerForceClosed().get()) { return true; } if (circuitOpened.get() == -1) { return true; } else { if (isAfterSleepWindow()) { //only the first request after sleep window should execute //if the executing command succeeds, the status will transition to CLOSED //if the executing command fails, the status will transition to OPEN //if the executing command gets unsubscribed, the status will transition to OPEN if (status.compareAndSet(Status.OPEN, Status.HALF_OPEN)) { return true; } else { return false; } } else { return false; } } } } /** * An implementation of the circuit breaker that does nothing. * * @ExcludeFromJavadoc */ /* package */static class NoOpCircuitBreaker implements HystrixCircuitBreaker { @Override public boolean allowRequest() { return true; } @Override public boolean isOpen() { return false; } @Override public void markSuccess() { } @Override public void markNonSuccess() { } @Override public boolean attemptExecution() { return true; } } }
4,632
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixThreadPoolKey.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; import com.netflix.hystrix.util.InternMap; /** * A key to represent a {@link HystrixThreadPool} for monitoring, metrics publishing, caching and other such uses. * <p> * This interface is intended to work natively with Enums so that implementing code can be an enum that implements this interface. */ public interface HystrixThreadPoolKey extends HystrixKey { class Factory { private Factory() { } // used to intern instances so we don't keep re-creating them millions of times for the same key private static final InternMap<String, HystrixThreadPoolKey> intern = new InternMap<String, HystrixThreadPoolKey>( new InternMap.ValueConstructor<String, HystrixThreadPoolKey>() { @Override public HystrixThreadPoolKey create(String key) { return new HystrixThreadPoolKeyDefault(key); } }); /** * Retrieve (or create) an interned HystrixThreadPoolKey instance for a given name. * * @param name thread pool name * @return HystrixThreadPoolKey instance that is interned (cached) so a given name will always retrieve the same instance. */ public static HystrixThreadPoolKey asKey(String name) { return intern.interned(name); } private static class HystrixThreadPoolKeyDefault extends HystrixKeyDefault implements HystrixThreadPoolKey { public HystrixThreadPoolKeyDefault(String name) { super(name); } } /* package-private */ static int getThreadPoolCount() { return intern.size(); } } }
4,633
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixObservable.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 rx.Observable; import rx.schedulers.Schedulers; import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy; import com.netflix.hystrix.exception.HystrixBadRequestException; import com.netflix.hystrix.exception.HystrixRuntimeException; /** * Common interface for executables that implement the Observable methods {@link #observe()} and {@link #toObservable()} so client code can treat them the same and combine in typed collections if desired. * * @param <R> */ public interface HystrixObservable<R> extends HystrixInvokable<R> { /** * Used for asynchronous execution of command with a callback by subscribing to the {@link Observable}. * <p> * This eagerly starts execution of the command the same as {@link HystrixCommand#queue()} and {@link HystrixCommand#execute()}. * <p> * A lazy {@link Observable} can be obtained from {@link #toObservable()}. * <p> * <b>Callback Scheduling</b> * <p> * <ul> * <li>When using {@link ExecutionIsolationStrategy#THREAD} this defaults to using {@link Schedulers#computation()} for callbacks.</li> * <li>When using {@link ExecutionIsolationStrategy#SEMAPHORE} this defaults to using {@link Schedulers#immediate()} for callbacks.</li> * </ul> * <p> * See https://github.com/ReactiveX/RxJava/wiki for more information. * * @return {@code Observable<R>} that executes and calls back with the result of the command execution or a fallback if the command execution fails for any reason. * @throws HystrixRuntimeException * if a fallback does not exist * <p> * <ul> * <li>via {@code Observer#onError} if a failure occurs</li> * <li>or immediately if the command can not be queued (such as short-circuited, thread-pool/semaphore rejected)</li> * </ul> * @throws HystrixBadRequestException * via {@code Observer#onError} if invalid arguments or state were used representing a user failure, not a system failure * @throws IllegalStateException * if invoked more than once */ public Observable<R> observe(); /** * Used for asynchronous execution of command with a callback by subscribing to the {@link Observable}. * <p> * This lazily starts execution of the command only once the {@link Observable} is subscribed to. * <p> * An eager {@link Observable} can be obtained from {@link #observe()} * <p> * <b>Callback Scheduling</b> * <p> * <ul> * <li>When using {@link ExecutionIsolationStrategy#THREAD} this defaults to using {@link Schedulers#computation()} for callbacks.</li> * <li>When using {@link ExecutionIsolationStrategy#SEMAPHORE} this defaults to using {@link Schedulers#immediate()} for callbacks.</li> * </ul> * <p> * See https://github.com/ReactiveX/RxJava/wiki for more information. * * @return {@code Observable<R>} that executes and calls back with the result of the command execution or a fallback if the command execution fails for any reason. * @throws HystrixRuntimeException * if a fallback does not exist * <p> * <ul> * <li>via {@code Observer#onError} if a failure occurs</li> * <li>or immediately if the command can not be queued (such as short-circuited, thread-pool/semaphore rejected)</li> * </ul> * @throws HystrixBadRequestException * via {@code Observer#onError} if invalid arguments or state were used representing a user failure, not a system failure * @throws IllegalStateException * if invoked more than once */ public Observable<R> toObservable(); }
4,634
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixCommandKey.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; import com.netflix.hystrix.util.InternMap; /** * A key to represent a {@link HystrixCommand} for monitoring, circuit-breakers, metrics publishing, caching and other such uses. * <p> * This interface is intended to work natively with Enums so that implementing code can be an enum that implements this interface. */ public interface HystrixCommandKey extends HystrixKey { class Factory { private Factory() { } // used to intern instances so we don't keep re-creating them millions of times for the same key private static final InternMap<String, HystrixCommandKeyDefault> intern = new InternMap<String, HystrixCommandKeyDefault>( new InternMap.ValueConstructor<String, HystrixCommandKeyDefault>() { @Override public HystrixCommandKeyDefault create(String key) { return new HystrixCommandKeyDefault(key); } }); /** * Retrieve (or create) an interned HystrixCommandKey instance for a given name. * * @param name command name * @return HystrixCommandKey instance that is interned (cached) so a given name will always retrieve the same instance. */ public static HystrixCommandKey asKey(String name) { return intern.interned(name); } private static class HystrixCommandKeyDefault extends HystrixKey.HystrixKeyDefault implements HystrixCommandKey { public HystrixCommandKeyDefault(String name) { super(name); } } /* package-private */ static int getCommandCount() { return intern.size(); } } }
4,635
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixTimerThreadPoolProperties.java
package com.netflix.hystrix; import static com.netflix.hystrix.strategy.properties.HystrixPropertiesChainedProperty.forInteger; import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy; import com.netflix.hystrix.strategy.properties.HystrixProperty; /** * Properties for Hystrix timer thread pool. * <p> * Default implementation of methods uses Archaius (https://github.com/Netflix/archaius) */ public abstract class HystrixTimerThreadPoolProperties { private final HystrixProperty<Integer> corePoolSize; protected HystrixTimerThreadPoolProperties() { this(new Setter().withCoreSize(Runtime.getRuntime().availableProcessors())); } protected HystrixTimerThreadPoolProperties(Setter setter) { this.corePoolSize = getProperty("hystrix", "coreSize", setter.getCoreSize()); } private static HystrixProperty<Integer> getProperty(String propertyPrefix, String instanceProperty, Integer defaultValue) { return forInteger() .add(propertyPrefix + ".timer.threadpool.default." + instanceProperty, defaultValue) .build(); } public HystrixProperty<Integer> getCorePoolSize() { return corePoolSize; } /** * Factory method to retrieve the default Setter. */ public static Setter Setter() { return new Setter(); } /** * Fluent interface that allows chained setting of properties. * <p> * See {@link HystrixPropertiesStrategy} for more information on order of precedence. * <p> * Example: * <p> * <pre> {@code * HystrixTimerThreadPoolProperties.Setter() * .withCoreSize(10); * } </pre> * * @NotThreadSafe */ public static class Setter { private Integer coreSize = null; private Setter() { } public Integer getCoreSize() { return coreSize; } public Setter withCoreSize(int value) { this.coreSize = value; return this; } } }
4,636
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/Hystrix.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 java.util.NoSuchElementException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import com.netflix.hystrix.strategy.HystrixPlugins; import com.netflix.hystrix.strategy.properties.HystrixPropertiesFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.functions.Action0; /** * Lifecycle management of Hystrix. */ public class Hystrix { private static final Logger logger = LoggerFactory.getLogger(Hystrix.class); /** * Reset state and release resources in use (such as thread-pools). * <p> * NOTE: This can result in race conditions if HystrixCommands are concurrently being executed. * </p> */ public static void reset() { // shutdown thread-pools HystrixThreadPool.Factory.shutdown(); _reset(); } /** * Reset state and release resources in use (such as threadpools) and wait for completion. * <p> * NOTE: This can result in race conditions if HystrixCommands are concurrently being executed. * </p> * * @param time * time to wait for thread-pools to shutdown * @param unit * {@link TimeUnit} for <pre>time</pre> to wait for thread-pools to shutdown */ public static void reset(long time, TimeUnit unit) { // shutdown thread-pools HystrixThreadPool.Factory.shutdown(time, unit); _reset(); } /** * Reset logic that doesn't have time/TimeUnit arguments. */ private static void _reset() { // clear metrics HystrixCommandMetrics.reset(); HystrixThreadPoolMetrics.reset(); HystrixCollapserMetrics.reset(); // clear collapsers HystrixCollapser.reset(); // clear circuit breakers HystrixCircuitBreaker.Factory.reset(); HystrixPlugins.reset(); HystrixPropertiesFactory.reset(); currentCommand.set(new ConcurrentStack<HystrixCommandKey>()); } private static ThreadLocal<ConcurrentStack<HystrixCommandKey>> currentCommand = new ThreadLocal<ConcurrentStack<HystrixCommandKey>>() { @Override protected ConcurrentStack<HystrixCommandKey> initialValue() { return new ConcurrentStack<HystrixCommandKey>(); } }; /** * Allows a thread to query whether it's current point of execution is within the scope of a HystrixCommand. * <p> * When ExecutionIsolationStrategy is THREAD then this applies to the isolation (child/worker) thread not the calling thread. * <p> * When ExecutionIsolationStrategy is SEMAPHORE this applies to the calling thread. * * @return HystrixCommandKey of current command being executed or null if none. */ public static HystrixCommandKey getCurrentThreadExecutingCommand() { if (currentCommand == null) { // statics do "interesting" things across classloaders apparently so this can somehow be null ... return null; } return currentCommand.get().peek(); } /** * * @return Action0 to perform the same work as `endCurrentThreadExecutingCommand()` but can be done from any thread */ /* package */static Action0 startCurrentThreadExecutingCommand(HystrixCommandKey key) { final ConcurrentStack<HystrixCommandKey> list = currentCommand.get(); try { list.push(key); } catch (Exception e) { logger.warn("Unable to record command starting", e); } return new Action0() { @Override public void call() { endCurrentThreadExecutingCommand(list); } }; } /* package */static void endCurrentThreadExecutingCommand() { endCurrentThreadExecutingCommand(currentCommand.get()); } private static void endCurrentThreadExecutingCommand(ConcurrentStack<HystrixCommandKey> list) { try { if (!list.isEmpty()) { list.pop(); } } catch (NoSuchElementException e) { // this shouldn't be possible since we check for empty above and this is thread-isolated logger.debug("No command found to end.", e); } catch (Exception e) { logger.warn("Unable to end command.", e); } } /* package-private */ static int getCommandCount() { return currentCommand.get().size(); } /** * Trieber's algorithm for a concurrent stack * @param <E> */ private static class ConcurrentStack<E> { AtomicReference<Node<E>> top = new AtomicReference<Node<E>>(); public void push(E item) { Node<E> newHead = new Node<E>(item); Node<E> oldHead; do { oldHead = top.get(); newHead.next = oldHead; } while (!top.compareAndSet(oldHead, newHead)); } public E pop() { Node<E> oldHead; Node<E> newHead; do { oldHead = top.get(); if (oldHead == null) { return null; } newHead = oldHead.next; } while (!top.compareAndSet(oldHead, newHead)); return oldHead.item; } public boolean isEmpty() { return top.get() == null; } public int size() { int currentSize = 0; Node<E> current = top.get(); while (current != null) { currentSize++; current = current.next; } return currentSize; } public E peek() { Node<E> eNode = top.get(); if (eNode == null) { return null; } else { return eNode.item; } } private class Node<E> { public final E item; public Node<E> next; public Node(E item) { this.item = item; } } } }
4,637
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixRequestLog.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; import com.netflix.hystrix.metric.HystrixRequestEventsStream; 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.HystrixRequestVariableHolder; import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableLifecycle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.LinkedBlockingQueue; /** * Log of {@link HystrixCommand} executions and events during the current request. */ public class HystrixRequestLog { private static final Logger logger = LoggerFactory.getLogger(HystrixRequestLog.class); /** * RequestLog: Reduce Chance of Memory Leak * https://github.com/Netflix/Hystrix/issues/53 * * Upper limit on RequestLog before ignoring further additions and logging warnings. * * Intended to help prevent memory leaks when someone isn't aware of the * HystrixRequestContext lifecycle or enabling/disabling RequestLog. */ /* package */static final int MAX_STORAGE = 1000; private static final HystrixRequestVariableHolder<HystrixRequestLog> currentRequestLog = new HystrixRequestVariableHolder<HystrixRequestLog>(new HystrixRequestVariableLifecycle<HystrixRequestLog>() { @Override public HystrixRequestLog initialValue() { return new HystrixRequestLog(); } public void shutdown(HystrixRequestLog value) { //write this value to the Request stream HystrixRequestEventsStream.getInstance().write(value.getAllExecutedCommands()); } }); /** * History of {@link HystrixCommand} executed in this request. */ private LinkedBlockingQueue<HystrixCommand<?>> executedCommands = new LinkedBlockingQueue<HystrixCommand<?>>(MAX_STORAGE); /** * History of {@link HystrixInvokableInfo} executed in this request. */ private LinkedBlockingQueue<HystrixInvokableInfo<?>> allExecutedCommands = new LinkedBlockingQueue<HystrixInvokableInfo<?>>(MAX_STORAGE); // prevent public instantiation private HystrixRequestLog() { } /** * {@link HystrixRequestLog} for current request as defined by {@link HystrixRequestContext}. * * @return {@link HystrixRequestLog} */ public static HystrixRequestLog getCurrentRequest(HystrixConcurrencyStrategy concurrencyStrategy) { return currentRequestLog.get(concurrencyStrategy); } /** * {@link HystrixRequestLog} for current request as defined by {@link HystrixRequestContext}. * <p> * NOTE: This uses the default {@link HystrixConcurrencyStrategy} or global override. If an injected strategy is being used by commands you must instead use * {@link #getCurrentRequest(HystrixConcurrencyStrategy)}. * * @return {@link HystrixRequestLog} */ public static HystrixRequestLog getCurrentRequest() { return currentRequestLog.get(HystrixPlugins.getInstance().getConcurrencyStrategy()); } /** * Retrieve {@link HystrixCommand} instances that were executed during this {@link HystrixRequestContext}. * * @return {@code Collection<HystrixCommand<?>>} */ @Deprecated public Collection<HystrixCommand<?>> getExecutedCommands() { return Collections.unmodifiableCollection(executedCommands); } /** * Retrieve {@link HystrixCommand} instances that were executed during this {@link HystrixRequestContext}. * * @return {@code Collection<HystrixCommand<?>>} */ public Collection<HystrixInvokableInfo<?>> getAllExecutedCommands() { return Collections.unmodifiableCollection(allExecutedCommands); } /** * Add {@link HystrixCommand} instance to the request log. * * @param command * {@code HystrixCommand<?>} */ /* package */void addExecutedCommand(HystrixInvokableInfo<?> command) { if (!allExecutedCommands.offer(command)) { // see RequestLog: Reduce Chance of Memory Leak https://github.com/Netflix/Hystrix/issues/53 logger.warn("RequestLog ignoring command after reaching limit of " + MAX_STORAGE + ". See https://github.com/Netflix/Hystrix/issues/53 for more information."); } // TODO remove this when deprecation completed if (command instanceof HystrixCommand) { @SuppressWarnings("rawtypes") HystrixCommand<?> _c = (HystrixCommand) command; if (!executedCommands.offer(_c)) { // see RequestLog: Reduce Chance of Memory Leak https://github.com/Netflix/Hystrix/issues/53 logger.warn("RequestLog ignoring command after reaching limit of " + MAX_STORAGE + ". See https://github.com/Netflix/Hystrix/issues/53 for more information."); } } } /** * Formats the log of executed commands into a string usable for logging purposes. * <p> * Examples: * <ul> * <li>TestCommand[SUCCESS][1ms]</li> * <li>TestCommand[SUCCESS][1ms], TestCommand[SUCCESS, RESPONSE_FROM_CACHE][1ms]x4</li> * <li>TestCommand[TIMEOUT][1ms]</li> * <li>TestCommand[FAILURE][1ms]</li> * <li>TestCommand[THREAD_POOL_REJECTED][1ms]</li> * <li>TestCommand[THREAD_POOL_REJECTED, FALLBACK_SUCCESS][1ms]</li> * <li>TestCommand[EMIT, SUCCESS][1ms]</li> * <li>TestCommand[EMITx5, SUCCESS][1ms]</li> * <li>TestCommand[EMITx5, FAILURE, FALLBACK_EMITx6, FALLBACK_FAILURE][100ms]</li> * <li>TestCommand[FAILURE, FALLBACK_SUCCESS][1ms], TestCommand[FAILURE, FALLBACK_SUCCESS, RESPONSE_FROM_CACHE][1ms]x4</li> * <li>GetData[SUCCESS][1ms], PutData[SUCCESS][1ms], GetValues[SUCCESS][1ms], GetValues[SUCCESS, RESPONSE_FROM_CACHE][1ms], TestCommand[FAILURE, FALLBACK_FAILURE][1ms], TestCommand[FAILURE, * FALLBACK_FAILURE, RESPONSE_FROM_CACHE][1ms]</li> * </ul> * <p> * If a command has a multiplier such as <code>x4</code>, that means this command was executed 4 times with the same events. The time in milliseconds is the sum of the 4 executions. * <p> * For example, <code>TestCommand[SUCCESS][15ms]x4</code> represents TestCommand being executed 4 times and the sum of those 4 executions was 15ms. These 4 each executed the run() method since * <code>RESPONSE_FROM_CACHE</code> was not present as an event. * * If an EMIT or FALLBACK_EMIT has a multiplier such as <code>x5</code>, that means a <code>HystrixObservableCommand</code> was used and it emitted that number of <code>OnNext</code>s. * <p> * For example, <code>TestCommand[EMITx5, FAILURE, FALLBACK_EMITx6, FALLBACK_FAILURE][100ms]</code> represents TestCommand executing observably, emitted 5 <code>OnNext</code>s, then an <code>OnError</code>. * This command also has an Observable fallback, and it emits 6 <code>OnNext</code>s, then an <code>OnCompleted</code>. * * @return String request log or "Unknown" if unable to instead of throwing an exception. */ public String getExecutedCommandsAsString() { try { LinkedHashMap<String, Integer> aggregatedCommandsExecuted = new LinkedHashMap<String, Integer>(); Map<String, Integer> aggregatedCommandExecutionTime = new HashMap<String, Integer>(); StringBuilder builder = new StringBuilder(); int estimatedLength = 0; for (HystrixInvokableInfo<?> command : allExecutedCommands) { builder.setLength(0); builder.append(command.getCommandKey().name()); List<HystrixEventType> events = new ArrayList<HystrixEventType>(command.getExecutionEvents()); if (events.size() > 0) { Collections.sort(events); //replicate functionality of Arrays.toString(events.toArray()) to append directly to existing StringBuilder builder.append("["); for (HystrixEventType event : events) { switch (event) { case EMIT: int numEmissions = command.getNumberEmissions(); if (numEmissions > 1) { builder.append(event).append("x").append(numEmissions).append(", "); } else { builder.append(event).append(", "); } break; case FALLBACK_EMIT: int numFallbackEmissions = command.getNumberFallbackEmissions(); if (numFallbackEmissions > 1) { builder.append(event).append("x").append(numFallbackEmissions).append(", "); } else { builder.append(event).append(", "); } break; default: builder.append(event).append(", "); } } builder.setCharAt(builder.length() - 2, ']'); builder.setLength(builder.length() - 1); } else { builder.append("[Executed]"); } String display = builder.toString(); estimatedLength += display.length() + 12; //add 12 chars to display length for appending totalExecutionTime and count below Integer counter = aggregatedCommandsExecuted.get(display); if( counter != null){ aggregatedCommandsExecuted.put(display, counter + 1); } else { // add it aggregatedCommandsExecuted.put(display, 1); } int executionTime = command.getExecutionTimeInMilliseconds(); if (executionTime < 0) { // do this so we don't create negative values or subtract values executionTime = 0; } counter = aggregatedCommandExecutionTime.get(display); if( counter != null && executionTime > 0){ // add to the existing executionTime (sum of executionTimes for duplicate command displayNames) aggregatedCommandExecutionTime.put(display, aggregatedCommandExecutionTime.get(display) + executionTime); } else { // add it aggregatedCommandExecutionTime.put(display, executionTime); } } builder.setLength(0); builder.ensureCapacity(estimatedLength); for (String displayString : aggregatedCommandsExecuted.keySet()) { if (builder.length() > 0) { builder.append(", "); } builder.append(displayString); int totalExecutionTime = aggregatedCommandExecutionTime.get(displayString); builder.append("[").append(totalExecutionTime).append("ms]"); int count = aggregatedCommandsExecuted.get(displayString); if (count > 1) { builder.append("x").append(count); } } return builder.toString(); } catch (Exception e) { logger.error("Failed to create HystrixRequestLog response header string.", e); // don't let this cause the entire app to fail so just return "Unknown" return "Unknown"; } } }
4,638
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixThreadPool.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; import com.netflix.hystrix.strategy.HystrixPlugins; import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; import com.netflix.hystrix.strategy.concurrency.HystrixContextScheduler; import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherFactory; import com.netflix.hystrix.strategy.properties.HystrixPropertiesFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Scheduler; import rx.functions.Func0; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * ThreadPool used to executed {@link HystrixCommand#run()} on separate threads when configured to do so with {@link HystrixCommandProperties#executionIsolationStrategy()}. * <p> * Typically each {@link HystrixCommandGroupKey} has its own thread-pool so that any one group of commands can not starve others from being able to run. * <p> * A {@link HystrixCommand} can be configured with a thread-pool explicitly by injecting a {@link HystrixThreadPoolKey} or via the * {@link HystrixCommandProperties#executionIsolationThreadPoolKeyOverride()} otherwise it * will derive a {@link HystrixThreadPoolKey} from the injected {@link HystrixCommandGroupKey}. * <p> * The pool should be sized large enough to handle normal healthy traffic but small enough that it will constrain concurrent execution if backend calls become latent. * <p> * For more information see the Github Wiki: https://github.com/Netflix/Hystrix/wiki/Configuration#wiki-ThreadPool and https://github.com/Netflix/Hystrix/wiki/How-it-Works#wiki-Isolation */ public interface HystrixThreadPool { /** * Implementation of {@link ThreadPoolExecutor}. * * @return ThreadPoolExecutor */ public ExecutorService getExecutor(); public Scheduler getScheduler(); public Scheduler getScheduler(Func0<Boolean> shouldInterruptThread); /** * Mark when a thread begins executing a command. */ public void markThreadExecution(); /** * Mark when a thread completes executing a command. */ public void markThreadCompletion(); /** * Mark when a command gets rejected from the threadpool */ public void markThreadRejection(); /** * Whether the queue will allow adding an item to it. * <p> * This allows dynamic control of the max queueSize versus whatever the actual max queueSize is so that dynamic changes can be done via property changes rather than needing an app * restart to adjust when commands should be rejected from queuing up. * * @return boolean whether there is space on the queue */ public boolean isQueueSpaceAvailable(); /** * @ExcludeFromJavadoc */ /* package */static class Factory { /* * Use the String from HystrixThreadPoolKey.name() instead of the HystrixThreadPoolKey instance as it's just an interface and we can't ensure the object * we receive implements hashcode/equals correctly and do not want the default hashcode/equals which would create a new threadpool for every object we get even if the name is the same */ /* package */final static ConcurrentHashMap<String, HystrixThreadPool> threadPools = new ConcurrentHashMap<String, HystrixThreadPool>(); /** * Get the {@link HystrixThreadPool} instance for a given {@link HystrixThreadPoolKey}. * <p> * This is thread-safe and ensures only 1 {@link HystrixThreadPool} per {@link HystrixThreadPoolKey}. * * @return {@link HystrixThreadPool} instance */ /* package */static HystrixThreadPool getInstance(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties.Setter propertiesBuilder) { // get the key to use instead of using the object itself so that if people forget to implement equals/hashcode things will still work String key = threadPoolKey.name(); // this should find it for all but the first time HystrixThreadPool previouslyCached = threadPools.get(key); if (previouslyCached != null) { return previouslyCached; } // if we get here this is the first time so we need to initialize synchronized (HystrixThreadPool.class) { if (!threadPools.containsKey(key)) { threadPools.put(key, new HystrixThreadPoolDefault(threadPoolKey, propertiesBuilder)); } } return threadPools.get(key); } /** * Initiate the shutdown of all {@link HystrixThreadPool} instances. * <p> * NOTE: This is NOT thread-safe if HystrixCommands are concurrently being executed * and causing thread-pools to initialize while also trying to shutdown. * </p> */ /* package */static synchronized void shutdown() { for (HystrixThreadPool pool : threadPools.values()) { pool.getExecutor().shutdown(); } threadPools.clear(); } /** * Initiate the shutdown of all {@link HystrixThreadPool} instances and wait up to the given time on each pool to complete. * <p> * NOTE: This is NOT thread-safe if HystrixCommands are concurrently being executed * and causing thread-pools to initialize while also trying to shutdown. * </p> */ /* package */static synchronized void shutdown(long timeout, TimeUnit unit) { for (HystrixThreadPool pool : threadPools.values()) { pool.getExecutor().shutdown(); } for (HystrixThreadPool pool : threadPools.values()) { try { while (! pool.getExecutor().awaitTermination(timeout, unit)) { } } catch (InterruptedException e) { throw new RuntimeException("Interrupted while waiting for thread-pools to terminate. Pools may not be correctly shutdown or cleared.", e); } } threadPools.clear(); } } /** * @ExcludeFromJavadoc * @ThreadSafe */ /* package */static class HystrixThreadPoolDefault implements HystrixThreadPool { private static final Logger logger = LoggerFactory.getLogger(HystrixThreadPoolDefault.class); private final HystrixThreadPoolProperties properties; private final BlockingQueue<Runnable> queue; private final ThreadPoolExecutor threadPool; private final HystrixThreadPoolMetrics metrics; private final int queueSize; public HystrixThreadPoolDefault(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties.Setter propertiesDefaults) { this.properties = HystrixPropertiesFactory.getThreadPoolProperties(threadPoolKey, propertiesDefaults); HystrixConcurrencyStrategy concurrencyStrategy = HystrixPlugins.getInstance().getConcurrencyStrategy(); this.queueSize = properties.maxQueueSize().get(); this.metrics = HystrixThreadPoolMetrics.getInstance(threadPoolKey, concurrencyStrategy.getThreadPool(threadPoolKey, properties), properties); this.threadPool = this.metrics.getThreadPool(); this.queue = this.threadPool.getQueue(); /* strategy: HystrixMetricsPublisherThreadPool */ HystrixMetricsPublisherFactory.createOrRetrievePublisherForThreadPool(threadPoolKey, this.metrics, this.properties); } @Override public ThreadPoolExecutor getExecutor() { touchConfig(); return threadPool; } @Override public Scheduler getScheduler() { //by default, interrupt underlying threads on timeout return getScheduler(new Func0<Boolean>() { @Override public Boolean call() { return true; } }); } @Override public Scheduler getScheduler(Func0<Boolean> shouldInterruptThread) { touchConfig(); return new HystrixContextScheduler(HystrixPlugins.getInstance().getConcurrencyStrategy(), this, shouldInterruptThread); } // allow us to change things via fast-properties by setting it each time private void touchConfig() { final int dynamicCoreSize = properties.coreSize().get(); final int configuredMaximumSize = properties.maximumSize().get(); int dynamicMaximumSize = properties.actualMaximumSize(); final boolean allowSizesToDiverge = properties.getAllowMaximumSizeToDivergeFromCoreSize().get(); boolean maxTooLow = false; if (allowSizesToDiverge && configuredMaximumSize < dynamicCoreSize) { //if user sets maximum < core (or defaults get us there), we need to maintain invariant of core <= maximum dynamicMaximumSize = dynamicCoreSize; maxTooLow = true; } // In JDK 6, setCorePoolSize and setMaximumPoolSize will execute a lock operation. Avoid them if the pool size is not changed. if (threadPool.getCorePoolSize() != dynamicCoreSize || (allowSizesToDiverge && threadPool.getMaximumPoolSize() != dynamicMaximumSize)) { if (maxTooLow) { logger.error("Hystrix ThreadPool configuration for : " + metrics.getThreadPoolKey().name() + " is trying to set coreSize = " + dynamicCoreSize + " and maximumSize = " + configuredMaximumSize + ". Maximum size will be set to " + dynamicMaximumSize + ", the coreSize value, since it must be equal to or greater than the coreSize value"); } threadPool.setCorePoolSize(dynamicCoreSize); threadPool.setMaximumPoolSize(dynamicMaximumSize); } threadPool.setKeepAliveTime(properties.keepAliveTimeMinutes().get(), TimeUnit.MINUTES); } @Override public void markThreadExecution() { metrics.markThreadExecution(); } @Override public void markThreadCompletion() { metrics.markThreadCompletion(); } @Override public void markThreadRejection() { metrics.markThreadRejection(); } /** * Whether the threadpool queue has space available according to the <code>queueSizeRejectionThreshold</code> settings. * * Note that the <code>queueSize</code> is an final instance variable on HystrixThreadPoolDefault, and not looked up dynamically. * The data structure is static, so this does not make sense as a dynamic lookup. * The <code>queueSizeRejectionThreshold</code> can be dynamic (up to <code>queueSize</code>), so that should * still get checked on each invocation. * <p> * If a SynchronousQueue implementation is used (<code>maxQueueSize</code> <= 0), it always returns 0 as the size so this would always return true. */ @Override public boolean isQueueSpaceAvailable() { if (queueSize <= 0) { // we don't have a queue so we won't look for space but instead // let the thread-pool reject or not return true; } else { return threadPool.getQueue().size() < properties.queueSizeRejectionThreshold().get(); } } } }
4,639
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixInvokable.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; /** * Marker interface for Hystrix commands that can be invoked. */ public interface HystrixInvokable<R> { }
4,640
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixObservableCollapser.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.netflix.hystrix.HystrixCollapser.CollapsedRequest; import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy; import com.netflix.hystrix.collapser.CollapserTimer; import com.netflix.hystrix.collapser.HystrixCollapserBridge; 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.HystrixRequestContext; import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherFactory; import com.netflix.hystrix.strategy.properties.HystrixPropertiesFactory; import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Scheduler; import rx.Subscription; import rx.functions.Action0; import rx.functions.Action1; import rx.functions.Func0; import rx.functions.Func1; import rx.schedulers.Schedulers; import rx.subjects.ReplaySubject; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * Collapse multiple requests into a single {@link HystrixCommand} execution based on a time window and optionally a max batch size. * <p> * This allows an object model to have multiple calls to the command that execute/queue many times in a short period (milliseconds) and have them all get batched into a single backend call. * <p> * Typically the time window is something like 10ms give or take. * <p> * NOTE: Do NOT retain any state within instances of this class. * <p> * It must be stateless or else it will be non-deterministic because most instances are discarded while some are retained and become the * "collapsers" for all the ones that are discarded. * * @param <K> * The key used to match BatchReturnType and RequestArgumentType * @param <BatchReturnType> * The type returned from the {@link HystrixCommand} that will be invoked on batch executions. * @param <ResponseType> * The type returned from this command. * @param <RequestArgumentType> * The type of the request argument. If multiple arguments are needed, wrap them in another object or a Tuple. */ public abstract class HystrixObservableCollapser<K, BatchReturnType, ResponseType, RequestArgumentType> implements HystrixObservable<ResponseType> { static final Logger logger = LoggerFactory.getLogger(HystrixObservableCollapser.class); private final RequestCollapserFactory<BatchReturnType, ResponseType, RequestArgumentType> collapserFactory; private final HystrixRequestCache requestCache; private final HystrixCollapserBridge<BatchReturnType, ResponseType, RequestArgumentType> collapserInstanceWrapper; private final HystrixCollapserMetrics metrics; /** * The scope of request collapsing. * <ul> * <li>REQUEST: Requests within the scope of a {@link HystrixRequestContext} will be collapsed. * <p> * Typically this means that requests within a single user-request (ie. HTTP request) are collapsed. No interaction with other user requests. 1 queue per user request. * </li> * <li>GLOBAL: Requests from any thread (ie. all HTTP requests) within the JVM will be collapsed. 1 queue for entire app.</li> * </ul> */ public static enum Scope implements RequestCollapserFactory.Scope { REQUEST, GLOBAL } /** * Collapser with default {@link HystrixCollapserKey} derived from the implementing class name and scoped to {@link Scope#REQUEST} and default configuration. */ protected HystrixObservableCollapser() { this(Setter.withCollapserKey(null).andScope(Scope.REQUEST)); } /** * Collapser scoped to {@link Scope#REQUEST} and default configuration. * * @param collapserKey * {@link HystrixCollapserKey} that identifies this collapser and provides the key used for retrieving properties, request caches, publishing metrics etc. */ protected HystrixObservableCollapser(HystrixCollapserKey collapserKey) { this(Setter.withCollapserKey(collapserKey).andScope(Scope.REQUEST)); } /** * Construct a {@link HystrixObservableCollapser} with defined {@link Setter} that allows * injecting property and strategy overrides and other optional arguments. * <p> * Null values will result in the default being used. * * @param setter * Fluent interface for constructor arguments */ protected HystrixObservableCollapser(Setter setter) { this(setter.collapserKey, setter.scope, new RealCollapserTimer(), setter.propertiesSetter, null); } /* package for tests */HystrixObservableCollapser(HystrixCollapserKey collapserKey, Scope scope, CollapserTimer timer, HystrixCollapserProperties.Setter propertiesBuilder, HystrixCollapserMetrics metrics) { if (collapserKey == null || collapserKey.name().trim().equals("")) { String defaultKeyName = getDefaultNameFromClass(getClass()); collapserKey = HystrixCollapserKey.Factory.asKey(defaultKeyName); } HystrixCollapserProperties properties = HystrixPropertiesFactory.getCollapserProperties(collapserKey, propertiesBuilder); this.collapserFactory = new RequestCollapserFactory<BatchReturnType, ResponseType, RequestArgumentType>(collapserKey, scope, timer, properties); this.requestCache = HystrixRequestCache.getInstance(collapserKey, HystrixPlugins.getInstance().getConcurrencyStrategy()); if (metrics == null) { this.metrics = HystrixCollapserMetrics.getInstance(collapserKey, properties); } else { this.metrics = metrics; } final HystrixObservableCollapser<K, BatchReturnType, ResponseType, RequestArgumentType> self = this; /* strategy: HystrixMetricsPublisherCollapser */ HystrixMetricsPublisherFactory.createOrRetrievePublisherForCollapser(collapserKey, this.metrics, properties); /** * Used to pass public method invocation to the underlying implementation in a separate package while leaving the methods 'protected' in this class. */ collapserInstanceWrapper = new HystrixCollapserBridge<BatchReturnType, ResponseType, RequestArgumentType>() { @Override public Collection<Collection<CollapsedRequest<ResponseType, RequestArgumentType>>> shardRequests(Collection<CollapsedRequest<ResponseType, RequestArgumentType>> requests) { Collection<Collection<CollapsedRequest<ResponseType, RequestArgumentType>>> shards = self.shardRequests(requests); self.metrics.markShards(shards.size()); return shards; } @Override public Observable<BatchReturnType> createObservableCommand(Collection<CollapsedRequest<ResponseType, RequestArgumentType>> requests) { HystrixObservableCommand<BatchReturnType> command = self.createCommand(requests); // mark the number of requests being collapsed together command.markAsCollapsedCommand(this.getCollapserKey(), requests.size()); self.metrics.markBatch(requests.size()); return command.toObservable(); } @Override public Observable<Void> mapResponseToRequests(Observable<BatchReturnType> batchResponse, Collection<CollapsedRequest<ResponseType, RequestArgumentType>> requests) { Func1<RequestArgumentType, K> requestKeySelector = self.getRequestArgumentKeySelector(); final Func1<BatchReturnType, K> batchResponseKeySelector = self.getBatchReturnTypeKeySelector(); final Func1<BatchReturnType, ResponseType> mapBatchTypeToResponseType = self.getBatchReturnTypeToResponseTypeMapper(); // index the requests by key final Map<K, CollapsedRequest<ResponseType, RequestArgumentType>> requestsByKey = new HashMap<K, CollapsedRequest<ResponseType, RequestArgumentType>>(requests.size()); for (CollapsedRequest<ResponseType, RequestArgumentType> cr : requests) { K requestArg = requestKeySelector.call(cr.getArgument()); requestsByKey.put(requestArg, cr); } final Set<K> seenKeys = new HashSet<K>(); // observe the responses and join with the requests by key return batchResponse .doOnNext(new Action1<BatchReturnType>() { @Override public void call(BatchReturnType batchReturnType) { try { K responseKey = batchResponseKeySelector.call(batchReturnType); CollapsedRequest<ResponseType, RequestArgumentType> requestForResponse = requestsByKey.get(responseKey); if (requestForResponse != null) { requestForResponse.emitResponse(mapBatchTypeToResponseType.call(batchReturnType)); // now add this to seenKeys, so we can later check what was seen, and what was unseen seenKeys.add(responseKey); } else { logger.warn("Batch Response contained a response key not in request batch : {}", responseKey); } } catch (Throwable ex) { logger.warn("Uncaught error during demultiplexing of BatchResponse", ex); } } }) .doOnError(new Action1<Throwable>() { @Override public void call(Throwable t) { Exception ex = getExceptionFromThrowable(t); for (CollapsedRequest<ResponseType, RequestArgumentType> collapsedReq : requestsByKey.values()) { collapsedReq.setException(ex); } } }) .doOnCompleted(new Action0() { @Override public void call() { for (Map.Entry<K, CollapsedRequest<ResponseType, RequestArgumentType>> entry : requestsByKey.entrySet()) { K key = entry.getKey(); CollapsedRequest<ResponseType, RequestArgumentType> collapsedReq = entry.getValue(); if (!seenKeys.contains(key)) { try { onMissingResponse(collapsedReq); } catch (Throwable ex) { collapsedReq.setException(new RuntimeException("Error in HystrixObservableCollapser.onMissingResponse handler", ex)); } } //then unconditionally issue an onCompleted. this ensures the downstream gets a terminal, regardless of how onMissingResponse was implemented collapsedReq.setComplete(); } } }).ignoreElements().cast(Void.class); } @Override public HystrixCollapserKey getCollapserKey() { return self.getCollapserKey(); } }; } protected Exception getExceptionFromThrowable(Throwable t) { Exception e; if (t instanceof Exception) { e = (Exception) t; } else { // Hystrix 1.x uses Exception, not Throwable so to prevent a breaking change Throwable will be wrapped in Exception e = new Exception("Throwable caught while executing.", t); } return e; } private HystrixCollapserProperties getProperties() { return collapserFactory.getProperties(); } /** * Key of the {@link HystrixObservableCollapser} used for properties, metrics, caches, reporting etc. * * @return {@link HystrixCollapserKey} identifying this {@link HystrixObservableCollapser} instance */ public HystrixCollapserKey getCollapserKey() { return collapserFactory.getCollapserKey(); } /** * Scope of collapsing. * <p> * <ul> * <li>REQUEST: Requests within the scope of a {@link HystrixRequestContext} will be collapsed. * <p> * Typically this means that requests within a single user-request (ie. HTTP request) are collapsed. No interaction with other user requests. 1 queue per user request. * </li> * <li>GLOBAL: Requests from any thread (ie. all HTTP requests) within the JVM will be collapsed. 1 queue for entire app.</li> * </ul> * <p> * Default: {@link Scope#REQUEST} (defined via constructor) * * @return {@link Scope} that collapsing should be performed within. */ public Scope getScope() { return Scope.valueOf(collapserFactory.getScope().name()); } /** * Return the {@link HystrixCollapserMetrics} for this collapser * @return {@link HystrixCollapserMetrics} for this collapser */ public HystrixCollapserMetrics getMetrics() { return metrics; } /** * The request arguments to be passed to the {@link HystrixCommand}. * <p> * Typically this means to take the argument(s) provided to the constructor and return it here. * <p> * If there are multiple arguments that need to be bundled, create a single object to contain them, or use a Tuple. * * @return RequestArgumentType */ public abstract RequestArgumentType getRequestArgument(); /** * Factory method to create a new {@link HystrixObservableCommand}{@code <BatchReturnType>} command object each time a batch needs to be executed. * <p> * Do not return the same instance each time. Return a new instance on each invocation. * <p> * Process the 'requests' argument into the arguments the command object needs to perform its work. * <p> * If a batch or requests needs to be split (sharded) into multiple commands, see {@link #shardRequests} <p> * IMPLEMENTATION NOTE: Be fast (ie. <1ms) in this method otherwise it can block the Timer from executing subsequent batches. Do not do any processing beyond constructing the command and returning * it. * * @param requests * {@code Collection<CollapsedRequest<ResponseType, RequestArgumentType>>} containing {@link CollapsedRequest} objects containing the arguments of each request collapsed in this batch. * @return {@link HystrixObservableCommand}{@code <BatchReturnType>} which when executed will retrieve results for the batch of arguments as found in the Collection of {@link CollapsedRequest} * objects */ protected abstract HystrixObservableCommand<BatchReturnType> createCommand(Collection<CollapsedRequest<ResponseType, RequestArgumentType>> requests); /** * Override to split (shard) a batch of requests into multiple batches that will each call <code>createCommand</code> separately. * <p> * The purpose of this is to allow collapsing to work for services that have sharded backends and batch executions that need to be shard-aware. * <p> * For example, a batch of 100 requests could be split into 4 different batches sharded on name (ie. a-g, h-n, o-t, u-z) that each result in a separate {@link HystrixCommand} being created and * executed for them. * <p> * By default this method does nothing to the Collection and is a pass-thru. * * @param requests * {@code Collection<CollapsedRequest<ResponseType, RequestArgumentType>>} containing {@link CollapsedRequest} objects containing the arguments of each request collapsed in this batch. * @return Collection of {@code Collection<CollapsedRequest<ResponseType, RequestArgumentType>>} objects sharded according to business rules. * <p>The CollapsedRequest instances should not be modified or wrapped as the CollapsedRequest instance object contains state information needed to complete the execution. */ protected Collection<Collection<CollapsedRequest<ResponseType, RequestArgumentType>>> shardRequests(Collection<CollapsedRequest<ResponseType, RequestArgumentType>> requests) { return Collections.singletonList(requests); } /** * Function that returns the key used for matching returned objects against request argument types. * <p> * The key returned from this function should match up with the key returned from {@link #getRequestArgumentKeySelector()}; * * @return key selector function */ protected abstract Func1<BatchReturnType, K> getBatchReturnTypeKeySelector(); /** * Function that returns the key used for matching request arguments against returned objects. * <p> * The key returned from this function should match up with the key returned from {@link #getBatchReturnTypeKeySelector()}; * * @return key selector function */ protected abstract Func1<RequestArgumentType, K> getRequestArgumentKeySelector(); /** * Invoked if a {@link CollapsedRequest} in the batch does not have a response set on it. * <p> * This allows setting an exception (via {@link CollapsedRequest#setException(Exception)}) or a fallback response (via {@link CollapsedRequest#setResponse(Object)}). * * @param r {@link CollapsedRequest} * that needs a response or exception set on it. */ protected abstract void onMissingResponse(CollapsedRequest<ResponseType, RequestArgumentType> r); /** * Function for mapping from BatchReturnType to ResponseType. * <p> * Often these two types are exactly the same so it's just a pass-thru. * * @return function for mapping from BatchReturnType to ResponseType */ protected abstract Func1<BatchReturnType, ResponseType> getBatchReturnTypeToResponseTypeMapper(); /** * Used for asynchronous execution with a callback by subscribing to the {@link Observable}. * <p> * This eagerly starts execution the same as {@link HystrixCollapser#queue()} and {@link HystrixCollapser#execute()}. * A lazy {@link Observable} can be obtained from {@link #toObservable()}. * <p> * <b>Callback Scheduling</b> * <p> * <ul> * <li>When using {@link ExecutionIsolationStrategy#THREAD} this defaults to using {@link Schedulers#computation()} for callbacks.</li> * <li>When using {@link ExecutionIsolationStrategy#SEMAPHORE} this defaults to using {@link Schedulers#immediate()} for callbacks.</li> * </ul> * Use {@link #toObservable(rx.Scheduler)} to schedule the callback differently. * <p> * See https://github.com/Netflix/RxJava/wiki for more information. * * @return {@code Observable<R>} that executes and calls back with the result of of {@link HystrixCommand}{@code <BatchReturnType>} execution after mapping * the {@code <BatchReturnType>} into {@code <ResponseType>} */ public Observable<ResponseType> observe() { // use a ReplaySubject to buffer the eagerly subscribed-to Observable ReplaySubject<ResponseType> subject = ReplaySubject.create(); // eagerly kick off subscription final Subscription underlyingSubscription = toObservable().subscribe(subject); // return the subject that can be subscribed to later while the execution has already started return subject.doOnUnsubscribe(new Action0() { @Override public void call() { underlyingSubscription.unsubscribe(); } }); } /** * A lazy {@link Observable} that will execute when subscribed to. * <p> * <b>Callback Scheduling</b> * <p> * <ul> * <li>When using {@link ExecutionIsolationStrategy#THREAD} this defaults to using {@link Schedulers#computation()} for callbacks.</li> * <li>When using {@link ExecutionIsolationStrategy#SEMAPHORE} this defaults to using {@link Schedulers#immediate()} for callbacks.</li> * </ul> * <p> * See https://github.com/Netflix/RxJava/wiki for more information. * * @return {@code Observable<R>} that lazily executes and calls back with the result of of {@link HystrixCommand}{@code <BatchReturnType>} execution after mapping the * {@code <BatchReturnType>} into {@code <ResponseType>} */ public Observable<ResponseType> toObservable() { // when we callback with the data we want to do the work // on a separate thread than the one giving us the callback return toObservable(Schedulers.computation()); } /** * A lazy {@link Observable} that will execute when subscribed to. * <p> * See https://github.com/Netflix/RxJava/wiki for more information. * * @param observeOn * The {@link Scheduler} to execute callbacks on. * @return {@code Observable<R>} that lazily executes and calls back with the result of of {@link HystrixCommand}{@code <BatchReturnType>} execution after mapping the * {@code <BatchReturnType>} into {@code <ResponseType>} */ public Observable<ResponseType> toObservable(Scheduler observeOn) { return Observable.defer(new Func0<Observable<ResponseType>>() { @Override public Observable<ResponseType> call() { final boolean isRequestCacheEnabled = getProperties().requestCacheEnabled().get(); /* try from cache first */ if (isRequestCacheEnabled) { HystrixCachedObservable<ResponseType> fromCache = requestCache.get(getCacheKey()); if (fromCache != null) { metrics.markResponseFromCache(); return fromCache.toObservable(); } } RequestCollapser<BatchReturnType, ResponseType, RequestArgumentType> requestCollapser = collapserFactory.getRequestCollapser(collapserInstanceWrapper); Observable<ResponseType> response = requestCollapser.submitRequest(getRequestArgument()); metrics.markRequestBatched(); if (isRequestCacheEnabled) { /* * A race can occur here with multiple threads queuing but only one will be cached. * This means we can have some duplication of requests in a thread-race but we're okay * with having some inefficiency in duplicate requests in the same batch * and then subsequent requests will retrieve a previously cached Observable. * * If this is an issue we can make a lazy-future that gets set in the cache * then only the winning 'put' will be invoked to actually call 'submitRequest' */ HystrixCachedObservable<ResponseType> toCache = HystrixCachedObservable.from(response); HystrixCachedObservable<ResponseType> fromCache = requestCache.putIfAbsent(getCacheKey(), toCache); if (fromCache == null) { return toCache.toObservable(); } else { return fromCache.toObservable(); } } return response; } }); } /** * Key to be used for request caching. * <p> * By default this returns null which means "do not cache". * <p> * To enable caching override this method and return a string key uniquely representing the state of a command instance. * <p> * If multiple command instances in the same request scope match keys then only the first will be executed and all others returned from cache. * * @return String cacheKey or null if not to cache */ protected String getCacheKey() { return null; } /** * Clears all state. If new requests come in instances will be recreated and metrics started from scratch. */ /* package */static void reset() { RequestCollapserFactory.reset(); } private static String getDefaultNameFromClass(@SuppressWarnings("rawtypes") Class<? extends HystrixObservableCollapser> cls) { String fromCache = defaultNameCache.get(cls); if (fromCache != null) { return fromCache; } // generate the default // default HystrixCommandKey to use if the method is not overridden String name = cls.getSimpleName(); if (name.equals("")) { // we don't have a SimpleName (anonymous inner class) so use the full class name name = cls.getName(); name = name.substring(name.lastIndexOf('.') + 1, name.length()); } defaultNameCache.put(cls, name); return name; } /** * Fluent interface for arguments to the {@link HystrixObservableCollapser} constructor. * <p> * The required arguments are set via the 'with' factory method and optional arguments via the 'and' chained methods. * <p> * Example: * <pre> {@code * Setter.withCollapserKey(HystrixCollapserKey.Factory.asKey("CollapserName")) .andScope(Scope.REQUEST); * } </pre> * * @NotThreadSafe */ public static class Setter { private final HystrixCollapserKey collapserKey; private Scope scope = Scope.REQUEST; // default if nothing is set private HystrixCollapserProperties.Setter propertiesSetter; private Setter(HystrixCollapserKey collapserKey) { this.collapserKey = collapserKey; } /** * Setter factory method containing required values. * <p> * All optional arguments can be set via the chained methods. * * @param collapserKey * {@link HystrixCollapserKey} that identifies this collapser and provides the key used for retrieving properties, request caches, publishing metrics etc. * @return Setter for fluent interface via method chaining */ public static Setter withCollapserKey(HystrixCollapserKey collapserKey) { return new Setter(collapserKey); } /** * {@link Scope} defining what scope the collapsing should occur within * * @param scope collapser scope * * @return Setter for fluent interface via method chaining */ public Setter andScope(Scope scope) { this.scope = scope; return this; } /** * @param propertiesSetter * {@link HystrixCollapserProperties.Setter} that allows instance specific property overrides (which can then be overridden by dynamic properties, see * {@link HystrixPropertiesStrategy} for * information on order of precedence). * <p> * Will use defaults if left NULL. * @return Setter for fluent interface via method chaining */ public Setter andCollapserPropertiesDefaults(HystrixCollapserProperties.Setter propertiesSetter) { this.propertiesSetter = propertiesSetter; return this; } } // this is a micro-optimization but saves about 1-2microseconds (on 2011 MacBook Pro) // on the repetitive string processing that will occur on the same classes over and over again @SuppressWarnings("rawtypes") private static ConcurrentHashMap<Class<? extends HystrixObservableCollapser>, String> defaultNameCache = new ConcurrentHashMap<Class<? extends HystrixObservableCollapser>, String>(); }
4,641
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixEventType.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; import com.netflix.hystrix.util.HystrixRollingNumberEvent; import java.util.ArrayList; import java.util.List; /** * Various states/events that execution can result in or have tracked. * <p> * These are most often accessed via {@link HystrixRequestLog} or {@link HystrixCommand#getExecutionEvents()}. */ public enum HystrixEventType { EMIT(false), SUCCESS(true), FAILURE(false), TIMEOUT(false), BAD_REQUEST(true), SHORT_CIRCUITED(false), THREAD_POOL_REJECTED(false), SEMAPHORE_REJECTED(false), FALLBACK_EMIT(false), FALLBACK_SUCCESS(true), FALLBACK_FAILURE(true), FALLBACK_REJECTION(true), FALLBACK_DISABLED(true), FALLBACK_MISSING(true), EXCEPTION_THROWN(false), RESPONSE_FROM_CACHE(true), CANCELLED(true), COLLAPSED(false), COMMAND_MAX_ACTIVE(false); private final boolean isTerminal; HystrixEventType(boolean isTerminal) { this.isTerminal = isTerminal; } public boolean isTerminal() { return isTerminal; } public static HystrixEventType from(HystrixRollingNumberEvent event) { switch (event) { case EMIT: return EMIT; case SUCCESS: return SUCCESS; case FAILURE: return FAILURE; case TIMEOUT: return TIMEOUT; case SHORT_CIRCUITED: return SHORT_CIRCUITED; case THREAD_POOL_REJECTED: return THREAD_POOL_REJECTED; case SEMAPHORE_REJECTED: return SEMAPHORE_REJECTED; case FALLBACK_EMIT: return FALLBACK_EMIT; case FALLBACK_SUCCESS: return FALLBACK_SUCCESS; case FALLBACK_FAILURE: return FALLBACK_FAILURE; case FALLBACK_REJECTION: return FALLBACK_REJECTION; case FALLBACK_DISABLED: return FALLBACK_DISABLED; case FALLBACK_MISSING: return FALLBACK_MISSING; case EXCEPTION_THROWN: return EXCEPTION_THROWN; case RESPONSE_FROM_CACHE: return RESPONSE_FROM_CACHE; case COLLAPSED: return COLLAPSED; case BAD_REQUEST: return BAD_REQUEST; case COMMAND_MAX_ACTIVE: return COMMAND_MAX_ACTIVE; default: throw new RuntimeException("Not an event that can be converted to HystrixEventType : " + event); } } /** * List of events that throw an Exception to the caller */ public final static List<HystrixEventType> EXCEPTION_PRODUCING_EVENT_TYPES = new ArrayList<HystrixEventType>(); /** * List of events that are terminal */ public final static List<HystrixEventType> TERMINAL_EVENT_TYPES = new ArrayList<HystrixEventType>(); static { EXCEPTION_PRODUCING_EVENT_TYPES.add(BAD_REQUEST); EXCEPTION_PRODUCING_EVENT_TYPES.add(FALLBACK_FAILURE); EXCEPTION_PRODUCING_EVENT_TYPES.add(FALLBACK_DISABLED); EXCEPTION_PRODUCING_EVENT_TYPES.add(FALLBACK_MISSING); EXCEPTION_PRODUCING_EVENT_TYPES.add(FALLBACK_REJECTION); for (HystrixEventType eventType: HystrixEventType.values()) { if (eventType.isTerminal()) { TERMINAL_EVENT_TYPES.add(eventType); } } } public enum ThreadPool { EXECUTED, REJECTED; public static ThreadPool from(HystrixRollingNumberEvent event) { switch (event) { case THREAD_EXECUTION: return EXECUTED; case THREAD_POOL_REJECTED: return REJECTED; default: throw new RuntimeException("Not an event that can be converted to HystrixEventType.ThreadPool : " + event); } } public static ThreadPool from(HystrixEventType eventType) { switch (eventType) { case SUCCESS: return EXECUTED; case FAILURE: return EXECUTED; case TIMEOUT: return EXECUTED; case BAD_REQUEST: return EXECUTED; case THREAD_POOL_REJECTED: return REJECTED; default: return null; } } } public enum Collapser { BATCH_EXECUTED, ADDED_TO_BATCH, RESPONSE_FROM_CACHE; public static Collapser from(HystrixRollingNumberEvent event) { switch (event) { case COLLAPSER_BATCH: return BATCH_EXECUTED; case COLLAPSER_REQUEST_BATCHED: return ADDED_TO_BATCH; case RESPONSE_FROM_CACHE: return RESPONSE_FROM_CACHE; default: throw new RuntimeException("Not an event that can be converted to HystrixEventType.Collapser : " + event); } } } }
4,642
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/ExecutionResult.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 java.util.ArrayList; import java.util.BitSet; import java.util.List; /** * Immutable holder class for the status of command execution. * <p> * This object can be referenced and "modified" by parent and child threads as well as by different instances of HystrixCommand since * 1 instance could create an ExecutionResult, cache a Future that refers to it, a 2nd instance execution then retrieves a Future * from cache and wants to append RESPONSE_FROM_CACHE to whatever the ExecutionResult was from the first command execution. * <p> * This being immutable forces and ensure thread-safety instead of using AtomicInteger/ConcurrentLinkedQueue and determining * when it's safe to mutate the object directly versus needing to deep-copy clone to a new instance. */ public class ExecutionResult { private final EventCounts eventCounts; private final Exception failedExecutionException; private final Exception executionException; private final long startTimestamp; private final int executionLatency; //time spent in run() method private final int userThreadLatency; //time elapsed between caller thread submitting request and response being visible to it private final boolean executionOccurred; private final boolean isExecutedInThread; private final HystrixCollapserKey collapserKey; private static final HystrixEventType[] ALL_EVENT_TYPES = HystrixEventType.values(); private static final int NUM_EVENT_TYPES = ALL_EVENT_TYPES.length; private static final BitSet EXCEPTION_PRODUCING_EVENTS = new BitSet(NUM_EVENT_TYPES); private static final BitSet TERMINAL_EVENTS = new BitSet(NUM_EVENT_TYPES); static { for (HystrixEventType eventType: HystrixEventType.EXCEPTION_PRODUCING_EVENT_TYPES) { EXCEPTION_PRODUCING_EVENTS.set(eventType.ordinal()); } for (HystrixEventType eventType: HystrixEventType.TERMINAL_EVENT_TYPES) { TERMINAL_EVENTS.set(eventType.ordinal()); } } public static class EventCounts { private final BitSet events; private final int numEmissions; private final int numFallbackEmissions; private final int numCollapsed; EventCounts() { this.events = new BitSet(NUM_EVENT_TYPES); this.numEmissions = 0; this.numFallbackEmissions = 0; this.numCollapsed = 0; } EventCounts(BitSet events, int numEmissions, int numFallbackEmissions, int numCollapsed) { this.events = events; this.numEmissions = numEmissions; this.numFallbackEmissions = numFallbackEmissions; this.numCollapsed = numCollapsed; } EventCounts(HystrixEventType... eventTypes) { BitSet newBitSet = new BitSet(NUM_EVENT_TYPES); int localNumEmits = 0; int localNumFallbackEmits = 0; int localNumCollapsed = 0; for (HystrixEventType eventType: eventTypes) { switch (eventType) { case EMIT: newBitSet.set(HystrixEventType.EMIT.ordinal()); localNumEmits++; break; case FALLBACK_EMIT: newBitSet.set(HystrixEventType.FALLBACK_EMIT.ordinal()); localNumFallbackEmits++; break; case COLLAPSED: newBitSet.set(HystrixEventType.COLLAPSED.ordinal()); localNumCollapsed++; break; default: newBitSet.set(eventType.ordinal()); break; } } this.events = newBitSet; this.numEmissions = localNumEmits; this.numFallbackEmissions = localNumFallbackEmits; this.numCollapsed = localNumCollapsed; } EventCounts plus(HystrixEventType eventType) { return plus(eventType, 1); } EventCounts plus(HystrixEventType eventType, int count) { BitSet newBitSet = (BitSet) events.clone(); int localNumEmits = numEmissions; int localNumFallbackEmits = numFallbackEmissions; int localNumCollapsed = numCollapsed; switch (eventType) { case EMIT: newBitSet.set(HystrixEventType.EMIT.ordinal()); localNumEmits += count; break; case FALLBACK_EMIT: newBitSet.set(HystrixEventType.FALLBACK_EMIT.ordinal()); localNumFallbackEmits += count; break; case COLLAPSED: newBitSet.set(HystrixEventType.COLLAPSED.ordinal()); localNumCollapsed += count; break; default: newBitSet.set(eventType.ordinal()); break; } return new EventCounts(newBitSet, localNumEmits, localNumFallbackEmits, localNumCollapsed); } public boolean contains(HystrixEventType eventType) { return events.get(eventType.ordinal()); } public boolean containsAnyOf(BitSet other) { return events.intersects(other); } public int getCount(HystrixEventType eventType) { switch (eventType) { case EMIT: return numEmissions; case FALLBACK_EMIT: return numFallbackEmissions; case EXCEPTION_THROWN: return containsAnyOf(EXCEPTION_PRODUCING_EVENTS) ? 1 : 0; case COLLAPSED: return numCollapsed; default: return contains(eventType) ? 1 : 0; } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EventCounts that = (EventCounts) o; if (numEmissions != that.numEmissions) return false; if (numFallbackEmissions != that.numFallbackEmissions) return false; if (numCollapsed != that.numCollapsed) return false; return events.equals(that.events); } @Override public int hashCode() { int result = events.hashCode(); result = 31 * result + numEmissions; result = 31 * result + numFallbackEmissions; result = 31 * result + numCollapsed; return result; } @Override public String toString() { return "EventCounts{" + "events=" + events + ", numEmissions=" + numEmissions + ", numFallbackEmissions=" + numFallbackEmissions + ", numCollapsed=" + numCollapsed + '}'; } } private ExecutionResult(EventCounts eventCounts, long startTimestamp, int executionLatency, int userThreadLatency, Exception failedExecutionException, Exception executionException, boolean executionOccurred, boolean isExecutedInThread, HystrixCollapserKey collapserKey) { this.eventCounts = eventCounts; this.startTimestamp = startTimestamp; this.executionLatency = executionLatency; this.userThreadLatency = userThreadLatency; this.failedExecutionException = failedExecutionException; this.executionException = executionException; this.executionOccurred = executionOccurred; this.isExecutedInThread = isExecutedInThread; this.collapserKey = collapserKey; } // we can return a static version since it's immutable static ExecutionResult EMPTY = ExecutionResult.from(); public static ExecutionResult from(HystrixEventType... eventTypes) { boolean didExecutionOccur = false; for (HystrixEventType eventType: eventTypes) { if (didExecutionOccur(eventType)) { didExecutionOccur = true; } } return new ExecutionResult(new EventCounts(eventTypes), -1L, -1, -1, null, null, didExecutionOccur, false, null); } private static boolean didExecutionOccur(HystrixEventType eventType) { switch (eventType) { case SUCCESS: return true; case FAILURE: return true; case BAD_REQUEST: return true; case TIMEOUT: return true; case CANCELLED: return true; default: return false; } } public ExecutionResult setExecutionOccurred() { return new ExecutionResult(eventCounts, startTimestamp, executionLatency, userThreadLatency, failedExecutionException, executionException, true, isExecutedInThread, collapserKey); } public ExecutionResult setExecutionLatency(int executionLatency) { return new ExecutionResult(eventCounts, startTimestamp, executionLatency, userThreadLatency, failedExecutionException, executionException, executionOccurred, isExecutedInThread, collapserKey); } public ExecutionResult setException(Exception e) { return new ExecutionResult(eventCounts, startTimestamp, executionLatency, userThreadLatency, e, executionException, executionOccurred, isExecutedInThread, collapserKey); } public ExecutionResult setExecutionException(Exception executionException) { return new ExecutionResult(eventCounts, startTimestamp, executionLatency, userThreadLatency, failedExecutionException, executionException, executionOccurred, isExecutedInThread, collapserKey); } public ExecutionResult setInvocationStartTime(long startTimestamp) { return new ExecutionResult(eventCounts, startTimestamp, executionLatency, userThreadLatency, failedExecutionException, executionException, executionOccurred, isExecutedInThread, collapserKey); } public ExecutionResult setExecutedInThread() { return new ExecutionResult(eventCounts, startTimestamp, executionLatency, userThreadLatency, failedExecutionException, executionException, executionOccurred, true, collapserKey); } public ExecutionResult setNotExecutedInThread() { return new ExecutionResult(eventCounts, startTimestamp, executionLatency, userThreadLatency, failedExecutionException, executionException, executionOccurred, false, collapserKey); } public ExecutionResult markCollapsed(HystrixCollapserKey collapserKey, int sizeOfBatch) { return new ExecutionResult(eventCounts.plus(HystrixEventType.COLLAPSED, sizeOfBatch), startTimestamp, executionLatency, userThreadLatency, failedExecutionException, executionException, executionOccurred, isExecutedInThread, collapserKey); } public ExecutionResult markUserThreadCompletion(long userThreadLatency) { if (startTimestamp > 0 && !isResponseRejected()) { /* execution time (must occur before terminal state otherwise a race condition can occur if requested by client) */ return new ExecutionResult(eventCounts, startTimestamp, executionLatency, (int) userThreadLatency, failedExecutionException, executionException, executionOccurred, isExecutedInThread, collapserKey); } else { return this; } } /** * Creates a new ExecutionResult by adding the defined 'event' to the ones on the current instance. * * @param eventType event to add * @return new {@link ExecutionResult} with event added */ public ExecutionResult addEvent(HystrixEventType eventType) { return new ExecutionResult(eventCounts.plus(eventType), startTimestamp, executionLatency, userThreadLatency, failedExecutionException, executionException, executionOccurred, isExecutedInThread, collapserKey); } public ExecutionResult addEvent(int executionLatency, HystrixEventType eventType) { if (startTimestamp >= 0 && !isResponseRejected()) { return new ExecutionResult(eventCounts.plus(eventType), startTimestamp, executionLatency, userThreadLatency, failedExecutionException, executionException, executionOccurred, isExecutedInThread, collapserKey); } else { return addEvent(eventType); } } public EventCounts getEventCounts() { return eventCounts; } public long getStartTimestamp() { return startTimestamp; } public int getExecutionLatency() { return executionLatency; } public int getUserThreadLatency() { return userThreadLatency; } public long getCommandRunStartTimeInNanos() { return startTimestamp * 1000 * 1000; } public Exception getException() { return failedExecutionException; } public Exception getExecutionException() { return executionException; } public HystrixCollapserKey getCollapserKey() { return collapserKey; } public boolean isResponseSemaphoreRejected() { return eventCounts.contains(HystrixEventType.SEMAPHORE_REJECTED); } public boolean isResponseThreadPoolRejected() { return eventCounts.contains(HystrixEventType.THREAD_POOL_REJECTED); } public boolean isResponseRejected() { return isResponseThreadPoolRejected() || isResponseSemaphoreRejected(); } public List<HystrixEventType> getOrderedList() { List<HystrixEventType> eventList = new ArrayList<HystrixEventType>(); for (HystrixEventType eventType: ALL_EVENT_TYPES) { if (eventCounts.contains(eventType)) { eventList.add(eventType); } } return eventList; } public boolean isExecutedInThread() { return isExecutedInThread; } public boolean executionOccurred() { return executionOccurred; } public boolean containsTerminalEvent() { return eventCounts.containsAnyOf(TERMINAL_EVENTS); } @Override public String toString() { return "ExecutionResult{" + "eventCounts=" + eventCounts + ", failedExecutionException=" + failedExecutionException + ", executionException=" + executionException + ", startTimestamp=" + startTimestamp + ", executionLatency=" + executionLatency + ", userThreadLatency=" + userThreadLatency + ", executionOccurred=" + executionOccurred + ", isExecutedInThread=" + isExecutedInThread + ", collapserKey=" + collapserKey + '}'; } }
4,643
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixMetrics.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; import com.netflix.hystrix.util.HystrixRollingNumber; import com.netflix.hystrix.util.HystrixRollingNumberEvent; /** * Abstract base class for Hystrix metrics */ public abstract class HystrixMetrics { protected final HystrixRollingNumber counter; protected HystrixMetrics(HystrixRollingNumber counter) { this.counter = counter; } /** * Get the cumulative count since the start of the application for the given {@link HystrixRollingNumberEvent}. * * @param event * {@link HystrixRollingNumberEvent} of the event to retrieve a sum for * @return long cumulative count */ public long getCumulativeCount(HystrixRollingNumberEvent event) { return counter.getCumulativeSum(event); } /** * Get the rolling count for the given {@link HystrixRollingNumberEvent}. * <p> * The rolling window is defined by {@link HystrixCommandProperties#metricsRollingStatisticalWindowInMilliseconds()}. * * @param event * {@link HystrixRollingNumberEvent} of the event to retrieve a sum for * @return long rolling count */ public long getRollingCount(HystrixRollingNumberEvent event) { return counter.getRollingSum(event); } }
4,644
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixThreadPoolMetrics.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; import com.netflix.hystrix.metric.HystrixCommandCompletion; import com.netflix.hystrix.metric.consumer.CumulativeThreadPoolEventCounterStream; import com.netflix.hystrix.metric.consumer.RollingThreadPoolMaxConcurrencyStream; import com.netflix.hystrix.metric.consumer.RollingThreadPoolEventCounterStream; import com.netflix.hystrix.util.HystrixRollingNumberEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.functions.Func0; import rx.functions.Func2; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicInteger; /** * Used by {@link HystrixThreadPool} to record metrics. */ public class HystrixThreadPoolMetrics extends HystrixMetrics { private static final HystrixEventType[] ALL_COMMAND_EVENT_TYPES = HystrixEventType.values(); private static final HystrixEventType.ThreadPool[] ALL_THREADPOOL_EVENT_TYPES = HystrixEventType.ThreadPool.values(); private static final int NUMBER_THREADPOOL_EVENT_TYPES = ALL_THREADPOOL_EVENT_TYPES.length; // String is HystrixThreadPoolKey.name() (we can't use HystrixThreadPoolKey directly as we can't guarantee it implements hashcode/equals correctly) private static final ConcurrentHashMap<String, HystrixThreadPoolMetrics> metrics = new ConcurrentHashMap<String, HystrixThreadPoolMetrics>(); /** * Get or create the {@link HystrixThreadPoolMetrics} instance for a given {@link HystrixThreadPoolKey}. * <p> * This is thread-safe and ensures only 1 {@link HystrixThreadPoolMetrics} per {@link HystrixThreadPoolKey}. * * @param key * {@link HystrixThreadPoolKey} of {@link HystrixThreadPool} instance requesting the {@link HystrixThreadPoolMetrics} * @param threadPool * Pass-thru of ThreadPoolExecutor to {@link HystrixThreadPoolMetrics} instance on first time when constructed * @param properties * Pass-thru to {@link HystrixThreadPoolMetrics} instance on first time when constructed * @return {@link HystrixThreadPoolMetrics} */ public static HystrixThreadPoolMetrics getInstance(HystrixThreadPoolKey key, ThreadPoolExecutor threadPool, HystrixThreadPoolProperties properties) { // attempt to retrieve from cache first HystrixThreadPoolMetrics threadPoolMetrics = metrics.get(key.name()); if (threadPoolMetrics != null) { return threadPoolMetrics; } else { synchronized (HystrixThreadPoolMetrics.class) { HystrixThreadPoolMetrics existingMetrics = metrics.get(key.name()); if (existingMetrics != null) { return existingMetrics; } else { HystrixThreadPoolMetrics newThreadPoolMetrics = new HystrixThreadPoolMetrics(key, threadPool, properties); metrics.putIfAbsent(key.name(), newThreadPoolMetrics); return newThreadPoolMetrics; } } } } /** * Get the {@link HystrixThreadPoolMetrics} instance for a given {@link HystrixThreadPoolKey} or null if one does not exist. * * @param key * {@link HystrixThreadPoolKey} of {@link HystrixThreadPool} instance requesting the {@link HystrixThreadPoolMetrics} * @return {@link HystrixThreadPoolMetrics} */ public static HystrixThreadPoolMetrics getInstance(HystrixThreadPoolKey key) { return metrics.get(key.name()); } /** * All registered instances of {@link HystrixThreadPoolMetrics} * * @return {@code Collection<HystrixThreadPoolMetrics>} */ public static Collection<HystrixThreadPoolMetrics> getInstances() { List<HystrixThreadPoolMetrics> threadPoolMetrics = new ArrayList<HystrixThreadPoolMetrics>(); for (HystrixThreadPoolMetrics tpm: metrics.values()) { if (hasExecutedCommandsOnThread(tpm)) { threadPoolMetrics.add(tpm); } } return Collections.unmodifiableCollection(threadPoolMetrics); } private static boolean hasExecutedCommandsOnThread(HystrixThreadPoolMetrics threadPoolMetrics) { return threadPoolMetrics.getCurrentCompletedTaskCount().intValue() > 0; } public static final Func2<long[], HystrixCommandCompletion, long[]> appendEventToBucket = new Func2<long[], HystrixCommandCompletion, long[]>() { @Override public long[] call(long[] initialCountArray, HystrixCommandCompletion execution) { ExecutionResult.EventCounts eventCounts = execution.getEventCounts(); for (HystrixEventType eventType: ALL_COMMAND_EVENT_TYPES) { long eventCount = eventCounts.getCount(eventType); HystrixEventType.ThreadPool threadPoolEventType = HystrixEventType.ThreadPool.from(eventType); if (threadPoolEventType != null) { initialCountArray[threadPoolEventType.ordinal()] += eventCount; } } return initialCountArray; } }; public static final Func2<long[], long[], long[]> counterAggregator = new Func2<long[], long[], long[]>() { @Override public long[] call(long[] cumulativeEvents, long[] bucketEventCounts) { for (int i = 0; i < NUMBER_THREADPOOL_EVENT_TYPES; i++) { cumulativeEvents[i] += bucketEventCounts[i]; } return cumulativeEvents; } }; /** * Clears all state from metrics. If new requests come in instances will be recreated and metrics started from scratch. * */ /* package */ static void reset() { metrics.clear(); } private final HystrixThreadPoolKey threadPoolKey; private final ThreadPoolExecutor threadPool; private final HystrixThreadPoolProperties properties; private final AtomicInteger concurrentExecutionCount = new AtomicInteger(); private final RollingThreadPoolEventCounterStream rollingCounterStream; private final CumulativeThreadPoolEventCounterStream cumulativeCounterStream; private final RollingThreadPoolMaxConcurrencyStream rollingThreadPoolMaxConcurrencyStream; private HystrixThreadPoolMetrics(HystrixThreadPoolKey threadPoolKey, ThreadPoolExecutor threadPool, HystrixThreadPoolProperties properties) { super(null); this.threadPoolKey = threadPoolKey; this.threadPool = threadPool; this.properties = properties; rollingCounterStream = RollingThreadPoolEventCounterStream.getInstance(threadPoolKey, properties); cumulativeCounterStream = CumulativeThreadPoolEventCounterStream.getInstance(threadPoolKey, properties); rollingThreadPoolMaxConcurrencyStream = RollingThreadPoolMaxConcurrencyStream.getInstance(threadPoolKey, properties); } /** * {@link ThreadPoolExecutor} this executor represents. * * @return ThreadPoolExecutor */ public ThreadPoolExecutor getThreadPool() { return threadPool; } /** * {@link HystrixThreadPoolKey} these metrics represent. * * @return HystrixThreadPoolKey */ public HystrixThreadPoolKey getThreadPoolKey() { return threadPoolKey; } /** * {@link HystrixThreadPoolProperties} of the {@link HystrixThreadPool} these metrics represent. * * @return HystrixThreadPoolProperties */ public HystrixThreadPoolProperties getProperties() { return properties; } /** * Value from {@link ThreadPoolExecutor#getActiveCount()} * * @return Number */ public Number getCurrentActiveCount() { return threadPool.getActiveCount(); } /** * Value from {@link ThreadPoolExecutor#getCompletedTaskCount()} * * @return Number */ public Number getCurrentCompletedTaskCount() { return threadPool.getCompletedTaskCount(); } /** * Value from {@link ThreadPoolExecutor#getCorePoolSize()} * * @return Number */ public Number getCurrentCorePoolSize() { return threadPool.getCorePoolSize(); } /** * Value from {@link ThreadPoolExecutor#getLargestPoolSize()} * * @return Number */ public Number getCurrentLargestPoolSize() { return threadPool.getLargestPoolSize(); } /** * Value from {@link ThreadPoolExecutor#getMaximumPoolSize()} * * @return Number */ public Number getCurrentMaximumPoolSize() { return threadPool.getMaximumPoolSize(); } /** * Value from {@link ThreadPoolExecutor#getPoolSize()} * * @return Number */ public Number getCurrentPoolSize() { return threadPool.getPoolSize(); } /** * Value from {@link ThreadPoolExecutor#getTaskCount()} * * @return Number */ public Number getCurrentTaskCount() { return threadPool.getTaskCount(); } /** * Current size of {@link BlockingQueue} used by the thread-pool * * @return Number */ public Number getCurrentQueueSize() { return threadPool.getQueue().size(); } /** * Invoked each time a thread is executed. */ public void markThreadExecution() { concurrentExecutionCount.incrementAndGet(); } /** * Rolling count of number of threads executed during rolling statistical window. * <p> * The rolling window is defined by {@link HystrixThreadPoolProperties#metricsRollingStatisticalWindowInMilliseconds()}. * * @return rolling count of threads executed */ public long getRollingCountThreadsExecuted() { return rollingCounterStream.getLatestCount(HystrixEventType.ThreadPool.EXECUTED); } /** * Cumulative count of number of threads executed since the start of the application. * * @return cumulative count of threads executed */ public long getCumulativeCountThreadsExecuted() { return cumulativeCounterStream.getLatestCount(HystrixEventType.ThreadPool.EXECUTED); } /** * Rolling count of number of threads rejected during rolling statistical window. * <p> * The rolling window is defined by {@link HystrixThreadPoolProperties#metricsRollingStatisticalWindowInMilliseconds()}. * * @return rolling count of threads rejected */ public long getRollingCountThreadsRejected() { return rollingCounterStream.getLatestCount(HystrixEventType.ThreadPool.REJECTED); } /** * Cumulative count of number of threads rejected since the start of the application. * * @return cumulative count of threads rejected */ public long getCumulativeCountThreadsRejected() { return cumulativeCounterStream.getLatestCount(HystrixEventType.ThreadPool.REJECTED); } public long getRollingCount(HystrixEventType.ThreadPool event) { return rollingCounterStream.getLatestCount(event); } public long getCumulativeCount(HystrixEventType.ThreadPool event) { return cumulativeCounterStream.getLatestCount(event); } @Override public long getCumulativeCount(HystrixRollingNumberEvent event) { return cumulativeCounterStream.getLatestCount(HystrixEventType.ThreadPool.from(event)); } @Override public long getRollingCount(HystrixRollingNumberEvent event) { return rollingCounterStream.getLatestCount(HystrixEventType.ThreadPool.from(event)); } /** * Invoked each time a thread completes. */ public void markThreadCompletion() { concurrentExecutionCount.decrementAndGet(); } /** * Rolling max number of active threads during rolling statistical window. * <p> * The rolling window is defined by {@link HystrixThreadPoolProperties#metricsRollingStatisticalWindowInMilliseconds()}. * * @return rolling max active threads */ public long getRollingMaxActiveThreads() { return rollingThreadPoolMaxConcurrencyStream.getLatestRollingMax(); } /** * Invoked each time a command is rejected from the thread-pool */ public void markThreadRejection() { concurrentExecutionCount.decrementAndGet(); } public static Func0<Integer> getCurrentConcurrencyThunk(final HystrixThreadPoolKey threadPoolKey) { return new Func0<Integer>() { @Override public Integer call() { return HystrixThreadPoolMetrics.getInstance(threadPoolKey).concurrentExecutionCount.get(); } }; } }
4,645
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/package-info.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. */ /** * Core functionality of Hystrix including the HystrixCommand and HystrixCollapser to be extended from. * * @since 1.0.0 */ package com.netflix.hystrix;
4,646
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixInvokableInfo.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 java.util.List; public interface HystrixInvokableInfo<R> { HystrixCommandGroupKey getCommandGroup(); HystrixCommandKey getCommandKey(); HystrixThreadPoolKey getThreadPoolKey(); String getPublicCacheKey(); //have to use public in the name, as there's already a protected {@link AbstractCommand#getCacheKey()} method. HystrixCollapserKey getOriginatingCollapserKey(); HystrixCommandMetrics getMetrics(); HystrixCommandProperties getProperties(); boolean isCircuitBreakerOpen(); boolean isExecutionComplete(); boolean isExecutedInThread(); boolean isSuccessfulExecution(); boolean isFailedExecution(); Throwable getFailedExecutionException(); boolean isResponseFromFallback(); boolean isResponseTimedOut(); boolean isResponseShortCircuited(); boolean isResponseFromCache(); boolean isResponseRejected(); boolean isResponseSemaphoreRejected(); boolean isResponseThreadPoolRejected(); List<HystrixEventType> getExecutionEvents(); int getNumberEmissions(); int getNumberFallbackEmissions(); int getNumberCollapsed(); int getExecutionTimeInMilliseconds(); long getCommandRunStartTimeInNanos(); ExecutionResult.EventCounts getEventCounts(); }
4,647
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/HystrixCommandMetrics.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; import com.netflix.hystrix.metric.HystrixCommandCompletion; import com.netflix.hystrix.metric.HystrixThreadEventStream; import com.netflix.hystrix.metric.consumer.CumulativeCommandEventCounterStream; import com.netflix.hystrix.metric.consumer.HealthCountsStream; import com.netflix.hystrix.metric.consumer.RollingCommandEventCounterStream; import com.netflix.hystrix.metric.consumer.RollingCommandLatencyDistributionStream; import com.netflix.hystrix.metric.consumer.RollingCommandMaxConcurrencyStream; import com.netflix.hystrix.metric.consumer.RollingCommandUserLatencyDistributionStream; import com.netflix.hystrix.strategy.HystrixPlugins; import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier; import com.netflix.hystrix.util.HystrixRollingNumberEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.functions.Func0; import rx.functions.Func2; import java.util.Collection; import java.util.Collections; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; /** * Used by {@link HystrixCommand} to record metrics. */ public class HystrixCommandMetrics extends HystrixMetrics { @SuppressWarnings("unused") private static final Logger logger = LoggerFactory.getLogger(HystrixCommandMetrics.class); private static final HystrixEventType[] ALL_EVENT_TYPES = HystrixEventType.values(); public static final Func2<long[], HystrixCommandCompletion, long[]> appendEventToBucket = new Func2<long[], HystrixCommandCompletion, long[]>() { @Override public long[] call(long[] initialCountArray, HystrixCommandCompletion execution) { ExecutionResult.EventCounts eventCounts = execution.getEventCounts(); for (HystrixEventType eventType: ALL_EVENT_TYPES) { switch (eventType) { case EXCEPTION_THROWN: break; //this is just a sum of other anyway - don't do the work here default: initialCountArray[eventType.ordinal()] += eventCounts.getCount(eventType); break; } } return initialCountArray; } }; public static final Func2<long[], long[], long[]> bucketAggregator = new Func2<long[], long[], long[]>() { @Override public long[] call(long[] cumulativeEvents, long[] bucketEventCounts) { for (HystrixEventType eventType: ALL_EVENT_TYPES) { switch (eventType) { case EXCEPTION_THROWN: for (HystrixEventType exceptionEventType: HystrixEventType.EXCEPTION_PRODUCING_EVENT_TYPES) { cumulativeEvents[eventType.ordinal()] += bucketEventCounts[exceptionEventType.ordinal()]; } break; default: cumulativeEvents[eventType.ordinal()] += bucketEventCounts[eventType.ordinal()]; break; } } return cumulativeEvents; } }; // String is HystrixCommandKey.name() (we can't use HystrixCommandKey directly as we can't guarantee it implements hashcode/equals correctly) private static final ConcurrentHashMap<String, HystrixCommandMetrics> metrics = new ConcurrentHashMap<String, HystrixCommandMetrics>(); /** * Get or create the {@link HystrixCommandMetrics} instance for a given {@link HystrixCommandKey}. * <p> * This is thread-safe and ensures only 1 {@link HystrixCommandMetrics} per {@link HystrixCommandKey}. * * @param key * {@link HystrixCommandKey} of {@link HystrixCommand} instance requesting the {@link HystrixCommandMetrics} * @param commandGroup * Pass-thru to {@link HystrixCommandMetrics} instance on first time when constructed * @param properties * Pass-thru to {@link HystrixCommandMetrics} instance on first time when constructed * @return {@link HystrixCommandMetrics} */ public static HystrixCommandMetrics getInstance(HystrixCommandKey key, HystrixCommandGroupKey commandGroup, HystrixCommandProperties properties) { return getInstance(key, commandGroup, null, properties); } /** * Get or create the {@link HystrixCommandMetrics} instance for a given {@link HystrixCommandKey}. * <p> * This is thread-safe and ensures only 1 {@link HystrixCommandMetrics} per {@link HystrixCommandKey}. * * @param key * {@link HystrixCommandKey} of {@link HystrixCommand} instance requesting the {@link HystrixCommandMetrics} * @param commandGroup * Pass-thru to {@link HystrixCommandMetrics} instance on first time when constructed * @param properties * Pass-thru to {@link HystrixCommandMetrics} instance on first time when constructed * @return {@link HystrixCommandMetrics} */ public static HystrixCommandMetrics getInstance(HystrixCommandKey key, HystrixCommandGroupKey commandGroup, HystrixThreadPoolKey threadPoolKey, HystrixCommandProperties properties) { // attempt to retrieve from cache first HystrixCommandMetrics commandMetrics = metrics.get(key.name()); if (commandMetrics != null) { return commandMetrics; } else { synchronized (HystrixCommandMetrics.class) { HystrixCommandMetrics existingMetrics = metrics.get(key.name()); if (existingMetrics != null) { return existingMetrics; } else { HystrixThreadPoolKey nonNullThreadPoolKey; if (threadPoolKey == null) { nonNullThreadPoolKey = HystrixThreadPoolKey.Factory.asKey(commandGroup.name()); } else { nonNullThreadPoolKey = threadPoolKey; } HystrixCommandMetrics newCommandMetrics = new HystrixCommandMetrics(key, commandGroup, nonNullThreadPoolKey, properties, HystrixPlugins.getInstance().getEventNotifier()); metrics.putIfAbsent(key.name(), newCommandMetrics); return newCommandMetrics; } } } } /** * Get the {@link HystrixCommandMetrics} instance for a given {@link HystrixCommandKey} or null if one does not exist. * * @param key * {@link HystrixCommandKey} of {@link HystrixCommand} instance requesting the {@link HystrixCommandMetrics} * @return {@link HystrixCommandMetrics} */ public static HystrixCommandMetrics getInstance(HystrixCommandKey key) { return metrics.get(key.name()); } /** * All registered instances of {@link HystrixCommandMetrics} * * @return {@code Collection<HystrixCommandMetrics>} */ public static Collection<HystrixCommandMetrics> getInstances() { return Collections.unmodifiableCollection(metrics.values()); } /** * Clears all state from metrics. If new requests come in instances will be recreated and metrics started from scratch. */ /* package */ static void reset() { for (HystrixCommandMetrics metricsInstance: getInstances()) { metricsInstance.unsubscribeAll(); } metrics.clear(); } private final HystrixCommandProperties properties; private final HystrixCommandKey key; private final HystrixCommandGroupKey group; private final HystrixThreadPoolKey threadPoolKey; private final AtomicInteger concurrentExecutionCount = new AtomicInteger(); private HealthCountsStream healthCountsStream; private final RollingCommandEventCounterStream rollingCommandEventCounterStream; private final CumulativeCommandEventCounterStream cumulativeCommandEventCounterStream; private final RollingCommandLatencyDistributionStream rollingCommandLatencyDistributionStream; private final RollingCommandUserLatencyDistributionStream rollingCommandUserLatencyDistributionStream; private final RollingCommandMaxConcurrencyStream rollingCommandMaxConcurrencyStream; /* package */HystrixCommandMetrics(final HystrixCommandKey key, HystrixCommandGroupKey commandGroup, HystrixThreadPoolKey threadPoolKey, HystrixCommandProperties properties, HystrixEventNotifier eventNotifier) { super(null); this.key = key; this.group = commandGroup; this.threadPoolKey = threadPoolKey; this.properties = properties; healthCountsStream = HealthCountsStream.getInstance(key, properties); rollingCommandEventCounterStream = RollingCommandEventCounterStream.getInstance(key, properties); cumulativeCommandEventCounterStream = CumulativeCommandEventCounterStream.getInstance(key, properties); rollingCommandLatencyDistributionStream = RollingCommandLatencyDistributionStream.getInstance(key, properties); rollingCommandUserLatencyDistributionStream = RollingCommandUserLatencyDistributionStream.getInstance(key, properties); rollingCommandMaxConcurrencyStream = RollingCommandMaxConcurrencyStream.getInstance(key, properties); } /* package */ synchronized void resetStream() { healthCountsStream.unsubscribe(); HealthCountsStream.removeByKey(key); healthCountsStream = HealthCountsStream.getInstance(key, properties); } /** * {@link HystrixCommandKey} these metrics represent. * * @return HystrixCommandKey */ public HystrixCommandKey getCommandKey() { return key; } /** * {@link HystrixCommandGroupKey} of the {@link HystrixCommand} these metrics represent. * * @return HystrixCommandGroupKey */ public HystrixCommandGroupKey getCommandGroup() { return group; } /** * {@link HystrixThreadPoolKey} used by {@link HystrixCommand} these metrics represent. * * @return HystrixThreadPoolKey */ public HystrixThreadPoolKey getThreadPoolKey() { return threadPoolKey; } /** * {@link HystrixCommandProperties} of the {@link HystrixCommand} these metrics represent. * * @return HystrixCommandProperties */ public HystrixCommandProperties getProperties() { return properties; } public long getRollingCount(HystrixEventType eventType) { return rollingCommandEventCounterStream.getLatest(eventType); } public long getCumulativeCount(HystrixEventType eventType) { return cumulativeCommandEventCounterStream.getLatest(eventType); } @Override public long getCumulativeCount(HystrixRollingNumberEvent event) { return getCumulativeCount(HystrixEventType.from(event)); } @Override public long getRollingCount(HystrixRollingNumberEvent event) { return getRollingCount(HystrixEventType.from(event)); } /** * Retrieve the execution time (in milliseconds) for the {@link HystrixCommand#run()} method being invoked at a given percentile. * <p> * Percentile capture and calculation is configured via {@link HystrixCommandProperties#metricsRollingStatisticalWindowInMilliseconds()} and other related properties. * * @param percentile * Percentile such as 50, 99, or 99.5. * @return int time in milliseconds */ public int getExecutionTimePercentile(double percentile) { return rollingCommandLatencyDistributionStream.getLatestPercentile(percentile); } /** * The mean (average) execution time (in milliseconds) for the {@link HystrixCommand#run()}. * <p> * This uses the same backing data as {@link #getExecutionTimePercentile}; * * @return int time in milliseconds */ public int getExecutionTimeMean() { return rollingCommandLatencyDistributionStream.getLatestMean(); } /** * Retrieve the total end-to-end execution time (in milliseconds) for {@link HystrixCommand#execute()} or {@link HystrixCommand#queue()} at a given percentile. * <p> * When execution is successful this would include time from {@link #getExecutionTimePercentile} but when execution * is being rejected, short-circuited, or timed-out then the time will differ. * <p> * This time can be lower than {@link #getExecutionTimePercentile} when a timeout occurs and the backing * thread that calls {@link HystrixCommand#run()} is still running. * <p> * When rejections or short-circuits occur then {@link HystrixCommand#run()} will not be executed and thus * not contribute time to {@link #getExecutionTimePercentile} but time will still show up in this metric for the end-to-end time. * <p> * This metric gives visibility into the total cost of {@link HystrixCommand} execution including * the overhead of queuing, executing and waiting for a thread to invoke {@link HystrixCommand#run()} . * <p> * Percentile capture and calculation is configured via {@link HystrixCommandProperties#metricsRollingStatisticalWindowInMilliseconds()} and other related properties. * * @param percentile * Percentile such as 50, 99, or 99.5. * @return int time in milliseconds */ public int getTotalTimePercentile(double percentile) { return rollingCommandUserLatencyDistributionStream.getLatestPercentile(percentile); } /** * The mean (average) execution time (in milliseconds) for {@link HystrixCommand#execute()} or {@link HystrixCommand#queue()}. * <p> * This uses the same backing data as {@link #getTotalTimePercentile}; * * @return int time in milliseconds */ public int getTotalTimeMean() { return rollingCommandUserLatencyDistributionStream.getLatestMean(); } public long getRollingMaxConcurrentExecutions() { return rollingCommandMaxConcurrencyStream.getLatestRollingMax(); } /** * Current number of concurrent executions of {@link HystrixCommand#run()}; * * @return int */ public int getCurrentConcurrentExecutionCount() { return concurrentExecutionCount.get(); } /* package-private */ void markCommandStart(HystrixCommandKey commandKey, HystrixThreadPoolKey threadPoolKey, HystrixCommandProperties.ExecutionIsolationStrategy isolationStrategy) { int currentCount = concurrentExecutionCount.incrementAndGet(); HystrixThreadEventStream.getInstance().commandExecutionStarted(commandKey, threadPoolKey, isolationStrategy, currentCount); } /* package-private */ void markCommandDone(ExecutionResult executionResult, HystrixCommandKey commandKey, HystrixThreadPoolKey threadPoolKey, boolean executionStarted) { HystrixThreadEventStream.getInstance().executionDone(executionResult, commandKey, threadPoolKey); if (executionStarted) { concurrentExecutionCount.decrementAndGet(); } } /* package-private */ HealthCountsStream getHealthCountsStream() { return healthCountsStream; } /** * Retrieve a snapshot of total requests, error count and error percentage. * * This metrics should measure the actual health of a {@link HystrixCommand}. For that reason, the following are included: * <p><ul> * <li>{@link HystrixEventType#SUCCESS} * <li>{@link HystrixEventType#FAILURE} * <li>{@link HystrixEventType#TIMEOUT} * <li>{@link HystrixEventType#THREAD_POOL_REJECTED} * <li>{@link HystrixEventType#SEMAPHORE_REJECTED} * </ul><p> * The following are not included in either attempts/failures: * <p><ul> * <li>{@link HystrixEventType#BAD_REQUEST} - this event denotes bad arguments to the command and not a problem with the command * <li>{@link HystrixEventType#SHORT_CIRCUITED} - this event measures a health problem in the past, not a problem with the current state * <li>{@link HystrixEventType#CANCELLED} - this event denotes a user-cancelled command. It's not known if it would have been a success or failure, so it shouldn't count for either * <li>All Fallback metrics * <li>{@link HystrixEventType#EMIT} - this event is not a terminal state for the command * <li>{@link HystrixEventType#COLLAPSED} - this event is about the batching process, not the command execution * </ul><p> * * @return {@link HealthCounts} */ public HealthCounts getHealthCounts() { return healthCountsStream.getLatest(); } private void unsubscribeAll() { healthCountsStream.unsubscribe(); rollingCommandEventCounterStream.unsubscribe(); cumulativeCommandEventCounterStream.unsubscribe(); rollingCommandLatencyDistributionStream.unsubscribe(); rollingCommandUserLatencyDistributionStream.unsubscribe(); rollingCommandMaxConcurrencyStream.unsubscribe(); } /** * Number of requests during rolling window. * Number that failed (failure + success + timeout + threadPoolRejected + semaphoreRejected). * Error percentage; */ public static class HealthCounts { private final long totalCount; private final long errorCount; private final int errorPercentage; HealthCounts(long total, long error) { this.totalCount = total; this.errorCount = error; if (totalCount > 0) { this.errorPercentage = (int) ((double) errorCount / totalCount * 100); } else { this.errorPercentage = 0; } } private static final HealthCounts EMPTY = new HealthCounts(0, 0); public long getTotalRequests() { return totalCount; } public long getErrorCount() { return errorCount; } public int getErrorPercentage() { return errorPercentage; } public HealthCounts plus(long[] eventTypeCounts) { long updatedTotalCount = totalCount; long updatedErrorCount = errorCount; long successCount = eventTypeCounts[HystrixEventType.SUCCESS.ordinal()]; long failureCount = eventTypeCounts[HystrixEventType.FAILURE.ordinal()]; long timeoutCount = eventTypeCounts[HystrixEventType.TIMEOUT.ordinal()]; long threadPoolRejectedCount = eventTypeCounts[HystrixEventType.THREAD_POOL_REJECTED.ordinal()]; long semaphoreRejectedCount = eventTypeCounts[HystrixEventType.SEMAPHORE_REJECTED.ordinal()]; updatedTotalCount += (successCount + failureCount + timeoutCount + threadPoolRejectedCount + semaphoreRejectedCount); updatedErrorCount += (failureCount + timeoutCount + threadPoolRejectedCount + semaphoreRejectedCount); return new HealthCounts(updatedTotalCount, updatedErrorCount); } public static HealthCounts empty() { return EMPTY; } public String toString() { return "HealthCounts[" + errorCount + " / " + totalCount + " : " + getErrorPercentage() + "%]"; } } }
4,648
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/util/InternMap.java
package com.netflix.hystrix.util; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Utility to have 'intern' - like functionality, which holds single instance of wrapper for a given key */ public class InternMap<K, V> { private final ConcurrentMap<K, V> storage = new ConcurrentHashMap<K, V>(); private final ValueConstructor<K, V> valueConstructor; public interface ValueConstructor<K, V> { V create(K key); } public InternMap(ValueConstructor<K, V> valueConstructor) { this.valueConstructor = valueConstructor; } public V interned(K key) { V existingKey = storage.get(key); V newKey = null; if (existingKey == null) { newKey = valueConstructor.create(key); existingKey = storage.putIfAbsent(key, newKey); } return existingKey != null ? existingKey : newKey; } public int size() { return storage.size(); } }
4,649
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/util/LongMaxUpdater.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.util; /* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ * * From http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/ */ import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; /** * One or more variables that together maintain a running {@code long} * maximum with initial value {@code Long.MIN_VALUE}. When updates * (method {@link #update}) are contended across threads, the set of * variables may grow dynamically to reduce contention. Method {@link * #max} (or, equivalently, {@link #longValue}) returns the current * maximum across the variables maintaining updates. * * <p>This class extends {@link Number}, but does <em>not</em> define * methods such as {@code hashCode} and {@code compareTo} because * instances are expected to be mutated, and so are not useful as * collection keys. * * <p><em>jsr166e note: This class is targeted to be placed in * java.util.concurrent.atomic<em> * * @since 1.8 * @author Doug Lea */ public class LongMaxUpdater extends Striped64 implements Serializable { private static final long serialVersionUID = 7249069246863182397L; /** * Version of max for use in retryUpdate */ final long fn(long v, long x) { return v > x ? v : x; } /** * Creates a new instance with initial maximum of {@code * Long.MIN_VALUE}. */ public LongMaxUpdater() { base = Long.MIN_VALUE; } /** * Updates the maximum to be at least the given value. * * @param x the value to update */ public void update(long x) { Cell[] as; long b, v; HashCode hc; Cell a; int n; if ((as = cells) != null || (b = base) < x && !casBase(b, x)) { boolean uncontended = true; int h = (hc = threadHashCode.get()).code; if (as == null || (n = as.length) < 1 || (a = as[(n - 1) & h]) == null || ((v = a.value) < x && !(uncontended = a.cas(v, x)))) retryUpdate(x, hc, uncontended); } } /** * Returns the current maximum. The returned value is * <em>NOT</em> an atomic snapshot: Invocation in the absence of * concurrent updates returns an accurate result, but concurrent * updates that occur while the value is being calculated might * not be incorporated. * * @return the maximum */ public long max() { Cell[] as = cells; long max = base; if (as != null) { int n = as.length; long v; for (int i = 0; i < n; ++i) { Cell a = as[i]; if (a != null && (v = a.value) > max) max = v; } } return max; } /** * Resets variables maintaining updates to {@code Long.MIN_VALUE}. * This method may be a useful alternative to creating a new * updater, but is only effective if there are no concurrent * updates. Because this method is intrinsically racy, it should * only be used when it is known that no threads are concurrently * updating. */ public void reset() { internalReset(Long.MIN_VALUE); } /** * Equivalent in effect to {@link #max} followed by {@link * #reset}. This method may apply for example during quiescent * points between multithreaded computations. If there are * updates concurrent with this method, the returned value is * <em>not</em> guaranteed to be the final value occurring before * the reset. * * @return the maximum */ public long maxThenReset() { Cell[] as = cells; long max = base; base = Long.MIN_VALUE; if (as != null) { int n = as.length; for (int i = 0; i < n; ++i) { Cell a = as[i]; if (a != null) { long v = a.value; a.value = Long.MIN_VALUE; if (v > max) max = v; } } } return max; } /** * Returns the String representation of the {@link #max}. * @return the String representation of the {@link #max} */ public String toString() { return Long.toString(max()); } /** * Equivalent to {@link #max}. * * @return the maximum */ public long longValue() { return max(); } /** * Returns the {@link #max} as an {@code int} after a narrowing * primitive conversion. */ public int intValue() { return (int)max(); } /** * Returns the {@link #max} as a {@code float} * after a widening primitive conversion. */ public float floatValue() { return (float)max(); } /** * Returns the {@link #max} as a {@code double} after a widening * primitive conversion. */ public double doubleValue() { return (double)max(); } private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { s.defaultWriteObject(); s.writeLong(max()); } private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); busy = 0; cells = null; base = s.readLong(); } }
4,650
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/util/LongAdder.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.util; /* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ * * From http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/ */ import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.concurrent.atomic.AtomicLong; /** * One or more variables that together maintain an initially zero * {@code long} sum. When updates (method {@link #add}) are contended * across threads, the set of variables may grow dynamically to reduce * contention. Method {@link #sum} (or, equivalently, {@link * #longValue}) returns the current total combined across the * variables maintaining the sum. * * <p> This class is usually preferable to {@link AtomicLong} when * multiple threads update a common sum that is used for purposes such * as collecting statistics, not for fine-grained synchronization * control. Under low update contention, the two classes have similar * characteristics. But under high contention, expected throughput of * this class is significantly higher, at the expense of higher space * consumption. * * <p>This class extends {@link Number}, but does <em>not</em> define * methods such as {@code hashCode} and {@code compareTo} because * instances are expected to be mutated, and so are not useful as * collection keys. * * <p><em>jsr166e note: This class is targeted to be placed in * java.util.concurrent.atomic<em> * * @since 1.8 * @author Doug Lea */ public class LongAdder extends Striped64 implements Serializable { private static final long serialVersionUID = 7249069246863182397L; /** * Version of plus for use in retryUpdate */ final long fn(long v, long x) { return v + x; } /** * Creates a new adder with initial sum of zero. */ public LongAdder() { } /** * Adds the given value. * * @param x the value to add */ public void add(long x) { Cell[] as; long b, v; HashCode hc; Cell a; int n; if ((as = cells) != null || !casBase(b = base, b + x)) { boolean uncontended = true; int h = (hc = threadHashCode.get()).code; if (as == null || (n = as.length) < 1 || (a = as[(n - 1) & h]) == null || !(uncontended = a.cas(v = a.value, v + x))) retryUpdate(x, hc, uncontended); } } /** * Equivalent to {@code add(1)}. */ public void increment() { add(1L); } /** * Equivalent to {@code add(-1)}. */ public void decrement() { add(-1L); } /** * Returns the current sum. The returned value is <em>NOT</em> an * atomic snapshot: Invocation in the absence of concurrent * updates returns an accurate result, but concurrent updates that * occur while the sum is being calculated might not be * incorporated. * * @return the sum */ public long sum() { long sum = base; Cell[] as = cells; if (as != null) { int n = as.length; for (int i = 0; i < n; ++i) { Cell a = as[i]; if (a != null) sum += a.value; } } return sum; } /** * Resets variables maintaining the sum to zero. This method may * be a useful alternative to creating a new adder, but is only * effective if there are no concurrent updates. Because this * method is intrinsically racy, it should only be used when it is * known that no threads are concurrently updating. */ public void reset() { internalReset(0L); } /** * Equivalent in effect to {@link #sum} followed by {@link * #reset}. This method may apply for example during quiescent * points between multithreaded computations. If there are * updates concurrent with this method, the returned value is * <em>not</em> guaranteed to be the final value occurring before * the reset. * * @return the sum */ public long sumThenReset() { long sum = base; Cell[] as = cells; base = 0L; if (as != null) { int n = as.length; for (int i = 0; i < n; ++i) { Cell a = as[i]; if (a != null) { sum += a.value; a.value = 0L; } } } return sum; } /** * Returns the String representation of the {@link #sum}. * @return the String representation of the {@link #sum} */ public String toString() { return Long.toString(sum()); } /** * Equivalent to {@link #sum}. * * @return the sum */ public long longValue() { return sum(); } /** * Returns the {@link #sum} as an {@code int} after a narrowing * primitive conversion. */ public int intValue() { return (int)sum(); } /** * Returns the {@link #sum} as a {@code float} * after a widening primitive conversion. */ public float floatValue() { return (float)sum(); } /** * Returns the {@link #sum} as a {@code double} after a widening * primitive conversion. */ public double doubleValue() { return (double)sum(); } private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { s.defaultWriteObject(); s.writeLong(sum()); } private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); busy = 0; cells = null; base = s.readLong(); } }
4,651
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/util/HystrixTimer.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.util; import com.netflix.hystrix.HystrixCollapser; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.strategy.HystrixPlugins; import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.ref.Reference; import java.lang.ref.SoftReference; 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.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; /** * Timer used by {@link HystrixCommand} to timeout async executions and {@link HystrixCollapser} to trigger batch executions. */ public class HystrixTimer { private static final Logger logger = LoggerFactory.getLogger(HystrixTimer.class); private static HystrixTimer INSTANCE = new HystrixTimer(); private HystrixTimer() { // private to prevent public instantiation } /** * Retrieve the global instance. */ public static HystrixTimer getInstance() { return INSTANCE; } /** * Clears all listeners. * <p> * NOTE: This will result in race conditions if {@link #addTimerListener(com.netflix.hystrix.util.HystrixTimer.TimerListener)} is being concurrently called. * </p> */ public static void reset() { ScheduledExecutor ex = INSTANCE.executor.getAndSet(null); if (ex != null && ex.getThreadPool() != null) { ex.getThreadPool().shutdownNow(); } } /* package */ AtomicReference<ScheduledExecutor> executor = new AtomicReference<ScheduledExecutor>(); /** * Add a {@link TimerListener} that will be executed until it is garbage collected or removed by clearing the returned {@link Reference}. * <p> * NOTE: It is the responsibility of code that adds a listener via this method to clear this listener when completed. * <p> * <blockquote> * * <pre> {@code * // add a TimerListener * Reference<TimerListener> listener = HystrixTimer.getInstance().addTimerListener(listenerImpl); * * // sometime later, often in a thread shutdown, request cleanup, servlet filter or something similar the listener must be shutdown via the clear() method * listener.clear(); * }</pre> * </blockquote> * * * @param listener * TimerListener implementation that will be triggered according to its <code>getIntervalTimeInMilliseconds()</code> method implementation. * @return reference to the TimerListener that allows cleanup via the <code>clear()</code> method */ public Reference<TimerListener> addTimerListener(final TimerListener listener) { startThreadIfNeeded(); // add the listener Runnable r = new Runnable() { @Override public void run() { try { listener.tick(); } catch (Exception e) { logger.error("Failed while ticking TimerListener", e); } } }; ScheduledFuture<?> f = executor.get().getThreadPool().scheduleAtFixedRate(r, listener.getIntervalTimeInMilliseconds(), listener.getIntervalTimeInMilliseconds(), TimeUnit.MILLISECONDS); return new TimerReference(listener, f); } private static class TimerReference extends SoftReference<TimerListener> { private final ScheduledFuture<?> f; TimerReference(TimerListener referent, ScheduledFuture<?> f) { super(referent); this.f = f; } @Override public void clear() { super.clear(); // stop this ScheduledFuture from any further executions f.cancel(false); } } /** * Since we allow resetting the timer (shutting down the thread) we need to lazily re-start it if it starts being used again. * <p> * This does the lazy initialization and start of the thread in a thread-safe manner while having little cost the rest of the time. */ protected void startThreadIfNeeded() { // create and start thread if one doesn't exist while (executor.get() == null || ! executor.get().isInitialized()) { if (executor.compareAndSet(null, new ScheduledExecutor())) { // initialize the executor that we 'won' setting executor.get().initialize(); } } } /* package */ static class ScheduledExecutor { /* package */ volatile ScheduledThreadPoolExecutor executor; private volatile boolean initialized; /** * We want this only done once when created in compareAndSet so use an initialize method */ public void initialize() { HystrixPropertiesStrategy propertiesStrategy = HystrixPlugins.getInstance().getPropertiesStrategy(); int coreSize = propertiesStrategy.getTimerThreadPoolProperties().getCorePoolSize().get(); ThreadFactory threadFactory = null; if (!PlatformSpecific.isAppEngineStandardEnvironment()) { threadFactory = new ThreadFactory() { final AtomicInteger counter = new AtomicInteger(); @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r, "HystrixTimer-" + counter.incrementAndGet()); thread.setDaemon(true); return thread; } }; } else { threadFactory = PlatformSpecific.getAppEngineThreadFactory(); } executor = new ScheduledThreadPoolExecutor(coreSize, threadFactory); initialized = true; } public ScheduledThreadPoolExecutor getThreadPool() { return executor; } public boolean isInitialized() { return initialized; } } public static interface TimerListener { /** * The 'tick' is called each time the interval occurs. * <p> * This method should NOT block or do any work but instead fire its work asynchronously to perform on another thread otherwise it will prevent the Timer from functioning. * <p> * This contract is used to keep this implementation single-threaded and simplistic. * <p> * If you need a ThreadLocal set, you can store the state in the TimerListener, then when tick() is called, set the ThreadLocal to your desired value. */ public void tick(); /** * How often this TimerListener should 'tick' defined in milliseconds. */ public int getIntervalTimeInMilliseconds(); } }
4,652
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/util/Exceptions.java
package com.netflix.hystrix.util; import java.util.LinkedList; import java.util.List; public class Exceptions { private Exceptions() { } /** * Throws the argument, return-type is RuntimeException so the caller can use a throw statement break out of the method */ public static RuntimeException sneakyThrow(Throwable t) { return Exceptions.<RuntimeException>doThrow(t); } private static <T extends Throwable> T doThrow(Throwable ex) throws T { throw (T) ex; } }
4,653
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/util/ExceptionThreadingUtility.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.util; @Deprecated public class ExceptionThreadingUtility { @Deprecated //this functionality is no longer supported public static void attachCallingThreadStack(Throwable e) { //no-op now } @Deprecated //this functionality is no longer supported public static void assignCallingThread(Thread callingThread) { //no-op now } }
4,654
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/util/HystrixRollingNumber.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.util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReferenceArray; import java.util.concurrent.locks.ReentrantLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.hystrix.strategy.properties.HystrixProperty; /** * A number which can be used to track counters (increment) or set values over time. * <p> * It is "rolling" in the sense that a 'timeInMilliseconds' is given that you want to track (such as 10 seconds) and then that is broken into buckets (defaults to 10) so that the 10 second window * doesn't empty out and restart every 10 seconds, but instead every 1 second you have a new bucket added and one dropped so that 9 of the buckets remain and only the newest starts from scratch. * <p> * This is done so that the statistics are gathered over a rolling 10 second window with data being added/dropped in 1 second intervals (or whatever granularity is defined by the arguments) rather * than each 10 second window starting at 0 again. * <p> * Performance-wise this class is optimized for writes, not reads. This is done because it expects far higher write volume (thousands/second) than reads (a few per second). * <p> * For example, on each read to getSum/getCount it will iterate buckets to sum the data so that on writes we don't need to maintain the overall sum and pay the synchronization cost at each write to * ensure the sum is up-to-date when the read can easily iterate each bucket to get the sum when it needs it. * <p> * See UnitTest for usage and expected behavior examples. * * @ThreadSafe */ public class HystrixRollingNumber { private static final Time ACTUAL_TIME = new ActualTime(); private final Time time; final int timeInMilliseconds; final int numberOfBuckets; final int bucketSizeInMillseconds; final BucketCircularArray buckets; private final CumulativeSum cumulativeSum = new CumulativeSum(); /** * Construct a counter, with configurable properties for how many buckets, and how long of an interval to track * @param timeInMilliseconds length of time to report metrics over * @param numberOfBuckets number of buckets to use * * @deprecated Please use {@link HystrixRollingNumber(int, int) instead}. These values are no longer allowed to * be updated at runtime. */ @Deprecated public HystrixRollingNumber(HystrixProperty<Integer> timeInMilliseconds, HystrixProperty<Integer> numberOfBuckets) { this(timeInMilliseconds.get(), numberOfBuckets.get()); } public HystrixRollingNumber(int timeInMilliseconds, int numberOfBuckets) { this(ACTUAL_TIME, timeInMilliseconds, numberOfBuckets); } /* package for testing */ HystrixRollingNumber(Time time, int timeInMilliseconds, int numberOfBuckets) { this.time = time; this.timeInMilliseconds = timeInMilliseconds; this.numberOfBuckets = numberOfBuckets; if (timeInMilliseconds % numberOfBuckets != 0) { throw new IllegalArgumentException("The timeInMilliseconds must divide equally into numberOfBuckets. For example 1000/10 is ok, 1000/11 is not."); } this.bucketSizeInMillseconds = timeInMilliseconds / numberOfBuckets; buckets = new BucketCircularArray(numberOfBuckets); } /** * Increment the counter in the current bucket by one for the given {@link HystrixRollingNumberEvent} type. * <p> * The {@link HystrixRollingNumberEvent} must be a "counter" type <code>HystrixRollingNumberEvent.isCounter() == true</code>. * * @param type * HystrixRollingNumberEvent defining which counter to increment */ public void increment(HystrixRollingNumberEvent type) { getCurrentBucket().getAdder(type).increment(); } /** * Add to the counter in the current bucket for the given {@link HystrixRollingNumberEvent} type. * <p> * The {@link HystrixRollingNumberEvent} must be a "counter" type <code>HystrixRollingNumberEvent.isCounter() == true</code>. * * @param type * HystrixRollingNumberEvent defining which counter to add to * @param value * long value to be added to the current bucket */ public void add(HystrixRollingNumberEvent type, long value) { getCurrentBucket().getAdder(type).add(value); } /** * Update a value and retain the max value. * <p> * The {@link HystrixRollingNumberEvent} must be a "max updater" type <code>HystrixRollingNumberEvent.isMaxUpdater() == true</code>. * * @param type HystrixRollingNumberEvent defining which counter to retrieve values from * @param value long value to be given to the max updater */ public void updateRollingMax(HystrixRollingNumberEvent type, long value) { getCurrentBucket().getMaxUpdater(type).update(value); } /** * Force a reset of all rolling counters (clear all buckets) so that statistics start being gathered from scratch. * <p> * This does NOT reset the CumulativeSum values. */ public void reset() { // if we are resetting, that means the lastBucket won't have a chance to be captured in CumulativeSum, so let's do it here Bucket lastBucket = buckets.peekLast(); if (lastBucket != null) { cumulativeSum.addBucket(lastBucket); } // clear buckets so we start over again buckets.clear(); } /** * Get the cumulative sum of all buckets ever since the JVM started without rolling for the given {@link HystrixRollingNumberEvent} type. * <p> * See {@link #getRollingSum(HystrixRollingNumberEvent)} for the rolling sum. * <p> * The {@link HystrixRollingNumberEvent} must be a "counter" type <code>HystrixRollingNumberEvent.isCounter() == true</code>. * * @param type HystrixRollingNumberEvent defining which counter to retrieve values from * @return cumulative sum of all increments and adds for the given {@link HystrixRollingNumberEvent} counter type */ public long getCumulativeSum(HystrixRollingNumberEvent type) { // this isn't 100% atomic since multiple threads can be affecting latestBucket & cumulativeSum independently // but that's okay since the count is always a moving target and we're accepting a "point in time" best attempt // we are however putting 'getValueOfLatestBucket' first since it can have side-affects on cumulativeSum whereas the inverse is not true return getValueOfLatestBucket(type) + cumulativeSum.get(type); } /** * Get the sum of all buckets in the rolling counter for the given {@link HystrixRollingNumberEvent} type. * <p> * The {@link HystrixRollingNumberEvent} must be a "counter" type <code>HystrixRollingNumberEvent.isCounter() == true</code>. * * @param type * HystrixRollingNumberEvent defining which counter to retrieve values from * @return * value from the given {@link HystrixRollingNumberEvent} counter type */ public long getRollingSum(HystrixRollingNumberEvent type) { Bucket lastBucket = getCurrentBucket(); if (lastBucket == null) return 0; long sum = 0; for (Bucket b : buckets) { sum += b.getAdder(type).sum(); } return sum; } /** * Get the value of the latest (current) bucket in the rolling counter for the given {@link HystrixRollingNumberEvent} type. * <p> * The {@link HystrixRollingNumberEvent} must be a "counter" type <code>HystrixRollingNumberEvent.isCounter() == true</code>. * * @param type * HystrixRollingNumberEvent defining which counter to retrieve value from * @return * value from latest bucket for given {@link HystrixRollingNumberEvent} counter type */ public long getValueOfLatestBucket(HystrixRollingNumberEvent type) { Bucket lastBucket = getCurrentBucket(); if (lastBucket == null) return 0; // we have bucket data so we'll return the lastBucket return lastBucket.get(type); } /** * Get an array of values for all buckets in the rolling counter for the given {@link HystrixRollingNumberEvent} type. * <p> * Index 0 is the oldest bucket. * <p> * The {@link HystrixRollingNumberEvent} must be a "counter" type <code>HystrixRollingNumberEvent.isCounter() == true</code>. * * @param type * HystrixRollingNumberEvent defining which counter to retrieve values from * @return array of values from each of the rolling buckets for given {@link HystrixRollingNumberEvent} counter type */ public long[] getValues(HystrixRollingNumberEvent type) { Bucket lastBucket = getCurrentBucket(); if (lastBucket == null) return new long[0]; // get buckets as an array (which is a copy of the current state at this point in time) Bucket[] bucketArray = buckets.getArray(); // we have bucket data so we'll return an array of values for all buckets long values[] = new long[bucketArray.length]; int i = 0; for (Bucket bucket : bucketArray) { if (type.isCounter()) { values[i++] = bucket.getAdder(type).sum(); } else if (type.isMaxUpdater()) { values[i++] = bucket.getMaxUpdater(type).max(); } } return values; } /** * Get the max value of values in all buckets for the given {@link HystrixRollingNumberEvent} type. * <p> * The {@link HystrixRollingNumberEvent} must be a "max updater" type <code>HystrixRollingNumberEvent.isMaxUpdater() == true</code>. * * @param type * HystrixRollingNumberEvent defining which "max updater" to retrieve values from * @return max value for given {@link HystrixRollingNumberEvent} type during rolling window */ public long getRollingMaxValue(HystrixRollingNumberEvent type) { long values[] = getValues(type); if (values.length == 0) { return 0; } else { Arrays.sort(values); return values[values.length - 1]; } } private ReentrantLock newBucketLock = new ReentrantLock(); /* package for testing */Bucket getCurrentBucket() { long currentTime = time.getCurrentTimeInMillis(); /* a shortcut to try and get the most common result of immediately finding the current bucket */ /** * Retrieve the latest bucket if the given time is BEFORE the end of the bucket window, otherwise it returns NULL. * * NOTE: This is thread-safe because it's accessing 'buckets' which is a LinkedBlockingDeque */ Bucket currentBucket = buckets.peekLast(); if (currentBucket != null && currentTime < currentBucket.windowStart + this.bucketSizeInMillseconds) { // if we're within the bucket 'window of time' return the current one // NOTE: We do not worry if we are BEFORE the window in a weird case of where thread scheduling causes that to occur, // we'll just use the latest as long as we're not AFTER the window return currentBucket; } /* if we didn't find the current bucket above, then we have to create one */ /** * The following needs to be synchronized/locked even with a synchronized/thread-safe data structure such as LinkedBlockingDeque because * the logic involves multiple steps to check existence, create an object then insert the object. The 'check' or 'insertion' themselves * are thread-safe by themselves but not the aggregate algorithm, thus we put this entire block of logic inside synchronized. * * I am using a tryLock if/then (http://download.oracle.com/javase/6/docs/api/java/util/concurrent/locks/Lock.html#tryLock()) * so that a single thread will get the lock and as soon as one thread gets the lock all others will go the 'else' block * and just return the currentBucket until the newBucket is created. This should allow the throughput to be far higher * and only slow down 1 thread instead of blocking all of them in each cycle of creating a new bucket based on some testing * (and it makes sense that it should as well). * * This means the timing won't be exact to the millisecond as to what data ends up in a bucket, but that's acceptable. * It's not critical to have exact precision to the millisecond, as long as it's rolling, if we can instead reduce the impact synchronization. * * More importantly though it means that the 'if' block within the lock needs to be careful about what it changes that can still * be accessed concurrently in the 'else' block since we're not completely synchronizing access. * * For example, we can't have a multi-step process to add a bucket, remove a bucket, then update the sum since the 'else' block of code * can retrieve the sum while this is all happening. The trade-off is that we don't maintain the rolling sum and let readers just iterate * bucket to calculate the sum themselves. This is an example of favoring write-performance instead of read-performance and how the tryLock * versus a synchronized block needs to be accommodated. */ if (newBucketLock.tryLock()) { try { if (buckets.peekLast() == null) { // the list is empty so create the first bucket Bucket newBucket = new Bucket(currentTime); buckets.addLast(newBucket); return newBucket; } else { // We go into a loop so that it will create as many buckets as needed to catch up to the current time // as we want the buckets complete even if we don't have transactions during a period of time. for (int i = 0; i < numberOfBuckets; i++) { // we have at least 1 bucket so retrieve it Bucket lastBucket = buckets.peekLast(); if (currentTime < lastBucket.windowStart + this.bucketSizeInMillseconds) { // if we're within the bucket 'window of time' return the current one // NOTE: We do not worry if we are BEFORE the window in a weird case of where thread scheduling causes that to occur, // we'll just use the latest as long as we're not AFTER the window return lastBucket; } else if (currentTime - (lastBucket.windowStart + this.bucketSizeInMillseconds) > timeInMilliseconds) { // the time passed is greater than the entire rolling counter so we want to clear it all and start from scratch reset(); // recursively call getCurrentBucket which will create a new bucket and return it return getCurrentBucket(); } else { // we're past the window so we need to create a new bucket // create a new bucket and add it as the new 'last' buckets.addLast(new Bucket(lastBucket.windowStart + this.bucketSizeInMillseconds)); // add the lastBucket values to the cumulativeSum cumulativeSum.addBucket(lastBucket); } } // we have finished the for-loop and created all of the buckets, so return the lastBucket now return buckets.peekLast(); } } finally { newBucketLock.unlock(); } } else { currentBucket = buckets.peekLast(); if (currentBucket != null) { // we didn't get the lock so just return the latest bucket while another thread creates the next one return currentBucket; } else { // the rare scenario where multiple threads raced to create the very first bucket // wait slightly and then use recursion while the other thread finishes creating a bucket try { Thread.sleep(5); } catch (Exception e) { // ignore } return getCurrentBucket(); } } } /* package */static interface Time { public long getCurrentTimeInMillis(); } private static class ActualTime implements Time { @Override public long getCurrentTimeInMillis() { return System.currentTimeMillis(); } } /** * Counters for a given 'bucket' of time. */ /* package */static class Bucket { final long windowStart; final LongAdder[] adderForCounterType; final LongMaxUpdater[] updaterForCounterType; Bucket(long startTime) { this.windowStart = startTime; /* * We support both LongAdder and LongMaxUpdater in a bucket but don't want the memory allocation * of all types for each so we only allocate the objects if the HystrixRollingNumberEvent matches * the correct type - though we still have the allocation of empty arrays to the given length * as we want to keep using the type.ordinal() value for fast random access. */ // initialize the array of LongAdders adderForCounterType = new LongAdder[HystrixRollingNumberEvent.values().length]; for (HystrixRollingNumberEvent type : HystrixRollingNumberEvent.values()) { if (type.isCounter()) { adderForCounterType[type.ordinal()] = new LongAdder(); } } updaterForCounterType = new LongMaxUpdater[HystrixRollingNumberEvent.values().length]; for (HystrixRollingNumberEvent type : HystrixRollingNumberEvent.values()) { if (type.isMaxUpdater()) { updaterForCounterType[type.ordinal()] = new LongMaxUpdater(); // initialize to 0 otherwise it is Long.MIN_VALUE updaterForCounterType[type.ordinal()].update(0); } } } long get(HystrixRollingNumberEvent type) { if (type.isCounter()) { return adderForCounterType[type.ordinal()].sum(); } if (type.isMaxUpdater()) { return updaterForCounterType[type.ordinal()].max(); } throw new IllegalStateException("Unknown type of event: " + type.name()); } LongAdder getAdder(HystrixRollingNumberEvent type) { if (!type.isCounter()) { throw new IllegalStateException("Type is not a Counter: " + type.name()); } return adderForCounterType[type.ordinal()]; } LongMaxUpdater getMaxUpdater(HystrixRollingNumberEvent type) { if (!type.isMaxUpdater()) { throw new IllegalStateException("Type is not a MaxUpdater: " + type.name()); } return updaterForCounterType[type.ordinal()]; } } /** * Cumulative counters (from start of JVM) from each Type */ /* package */static class CumulativeSum { final LongAdder[] adderForCounterType; final LongMaxUpdater[] updaterForCounterType; CumulativeSum() { /* * We support both LongAdder and LongMaxUpdater in a bucket but don't want the memory allocation * of all types for each so we only allocate the objects if the HystrixRollingNumberEvent matches * the correct type - though we still have the allocation of empty arrays to the given length * as we want to keep using the type.ordinal() value for fast random access. */ // initialize the array of LongAdders adderForCounterType = new LongAdder[HystrixRollingNumberEvent.values().length]; for (HystrixRollingNumberEvent type : HystrixRollingNumberEvent.values()) { if (type.isCounter()) { adderForCounterType[type.ordinal()] = new LongAdder(); } } updaterForCounterType = new LongMaxUpdater[HystrixRollingNumberEvent.values().length]; for (HystrixRollingNumberEvent type : HystrixRollingNumberEvent.values()) { if (type.isMaxUpdater()) { updaterForCounterType[type.ordinal()] = new LongMaxUpdater(); // initialize to 0 otherwise it is Long.MIN_VALUE updaterForCounterType[type.ordinal()].update(0); } } } public void addBucket(Bucket lastBucket) { for (HystrixRollingNumberEvent type : HystrixRollingNumberEvent.values()) { if (type.isCounter()) { getAdder(type).add(lastBucket.getAdder(type).sum()); } if (type.isMaxUpdater()) { getMaxUpdater(type).update(lastBucket.getMaxUpdater(type).max()); } } } long get(HystrixRollingNumberEvent type) { if (type.isCounter()) { return adderForCounterType[type.ordinal()].sum(); } if (type.isMaxUpdater()) { return updaterForCounterType[type.ordinal()].max(); } throw new IllegalStateException("Unknown type of event: " + type.name()); } LongAdder getAdder(HystrixRollingNumberEvent type) { if (!type.isCounter()) { throw new IllegalStateException("Type is not a Counter: " + type.name()); } return adderForCounterType[type.ordinal()]; } LongMaxUpdater getMaxUpdater(HystrixRollingNumberEvent type) { if (!type.isMaxUpdater()) { throw new IllegalStateException("Type is not a MaxUpdater: " + type.name()); } return updaterForCounterType[type.ordinal()]; } } /** * This is a circular array acting as a FIFO queue. * <p> * It purposefully does NOT implement Deque or some other Collection interface as it only implements functionality necessary for this RollingNumber use case. * <p> * Important Thread-Safety Note: This is ONLY thread-safe within the context of RollingNumber and the protection it gives in the <code>getCurrentBucket</code> method. It uses AtomicReference * objects to ensure anything done outside of <code>getCurrentBucket</code> is thread-safe, and to ensure visibility of changes across threads (ie. volatility) but the addLast and removeFirst * methods are NOT thread-safe for external access they depend upon the lock.tryLock() protection in <code>getCurrentBucket</code> which ensures only a single thread will access them at at time. * <p> * benjchristensen => This implementation was chosen based on performance testing I did and documented at: http://benjchristensen.com/2011/10/08/atomiccirculararray/ */ /* package */static class BucketCircularArray implements Iterable<Bucket> { private final AtomicReference<ListState> state; private final int dataLength; // we don't resize, we always stay the same, so remember this private final int numBuckets; /** * Immutable object that is atomically set every time the state of the BucketCircularArray changes * <p> * This handles the compound operations */ private class ListState { /* * this is an AtomicReferenceArray and not a normal Array because we're copying the reference * between ListState objects and multiple threads could maintain references across these * compound operations so I want the visibility/concurrency guarantees */ private final AtomicReferenceArray<Bucket> data; private final int size; private final int tail; private final int head; private ListState(AtomicReferenceArray<Bucket> data, int head, int tail) { this.head = head; this.tail = tail; if (head == 0 && tail == 0) { size = 0; } else { this.size = (tail + dataLength - head) % dataLength; } this.data = data; } public Bucket tail() { if (size == 0) { return null; } else { // we want to get the last item, so size()-1 return data.get(convert(size - 1)); } } private Bucket[] getArray() { /* * this isn't technically thread-safe since it requires multiple reads on something that can change * but since we never clear the data directly, only increment/decrement head/tail we would never get a NULL * just potentially return stale data which we are okay with doing */ ArrayList<Bucket> array = new ArrayList<Bucket>(); for (int i = 0; i < size; i++) { array.add(data.get(convert(i))); } return array.toArray(new Bucket[array.size()]); } private ListState incrementTail() { /* if incrementing results in growing larger than 'length' which is the max we should be at, then also increment head (equivalent of removeFirst but done atomically) */ if (size == numBuckets) { // increment tail and head return new ListState(data, (head + 1) % dataLength, (tail + 1) % dataLength); } else { // increment only tail return new ListState(data, head, (tail + 1) % dataLength); } } public ListState clear() { return new ListState(new AtomicReferenceArray<Bucket>(dataLength), 0, 0); } public ListState addBucket(Bucket b) { /* * We could in theory have 2 threads addBucket concurrently and this compound operation would interleave. * <p> * This should NOT happen since getCurrentBucket is supposed to be executed by a single thread. * <p> * If it does happen, it's not a huge deal as incrementTail() will be protected by compareAndSet and one of the two addBucket calls will succeed with one of the Buckets. * <p> * In either case, a single Bucket will be returned as "last" and data loss should not occur and everything keeps in sync for head/tail. * <p> * Also, it's fine to set it before incrementTail because nothing else should be referencing that index position until incrementTail occurs. */ data.set(tail, b); return incrementTail(); } // The convert() method takes a logical index (as if head was // always 0) and calculates the index within elementData private int convert(int index) { return (index + head) % dataLength; } } BucketCircularArray(int size) { AtomicReferenceArray<Bucket> _buckets = new AtomicReferenceArray<Bucket>(size + 1); // + 1 as extra room for the add/remove; state = new AtomicReference<ListState>(new ListState(_buckets, 0, 0)); dataLength = _buckets.length(); numBuckets = size; } public void clear() { while (true) { /* * it should be very hard to not succeed the first pass thru since this is typically is only called from * a single thread protected by a tryLock, but there is at least 1 other place (at time of writing this comment) * where reset can be called from (CircuitBreaker.markSuccess after circuit was tripped) so it can * in an edge-case conflict. * * Instead of trying to determine if someone already successfully called clear() and we should skip * we will have both calls reset the circuit, even if that means losing data added in between the two * depending on thread scheduling. * * The rare scenario in which that would occur, we'll accept the possible data loss while clearing it * since the code has stated its desire to clear() anyways. */ ListState current = state.get(); ListState newState = current.clear(); if (state.compareAndSet(current, newState)) { return; } } } /** * Returns an iterator on a copy of the internal array so that the iterator won't fail by buckets being added/removed concurrently. */ public Iterator<Bucket> iterator() { return Collections.unmodifiableList(Arrays.asList(getArray())).iterator(); } public void addLast(Bucket o) { ListState currentState = state.get(); // create new version of state (what we want it to become) ListState newState = currentState.addBucket(o); /* * use compareAndSet to set in case multiple threads are attempting (which shouldn't be the case because since addLast will ONLY be called by a single thread at a time due to protection * provided in <code>getCurrentBucket</code>) */ if (state.compareAndSet(currentState, newState)) { // we succeeded return; } else { // we failed, someone else was adding or removing // instead of trying again and risking multiple addLast concurrently (which shouldn't be the case) // we'll just return and let the other thread 'win' and if the timing is off the next call to getCurrentBucket will fix things return; } } public Bucket getLast() { return peekLast(); } public int size() { // the size can also be worked out each time as: // return (tail + data.length() - head) % data.length(); return state.get().size; } public Bucket peekLast() { return state.get().tail(); } private Bucket[] getArray() { return state.get().getArray(); } } }
4,655
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/util/HystrixRollingPercentile.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.util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicIntegerArray; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReferenceArray; import java.util.concurrent.locks.ReentrantLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.hystrix.strategy.properties.HystrixProperty; /** * Add values to a rolling window and retrieve percentile calculations such as median, 90th, 99th, etc. * <p> * The underlying data structure contains a circular array of buckets that "roll" over time. * <p> * For example, if the time window is configured to 60 seconds with 12 buckets of 5 seconds each, values will be captured in each 5 second bucket and rotate each 5 seconds. * <p> * This means that percentile calculations are for the "rolling window" of 55-60 seconds up to 5 seconds ago. * <p> * Each bucket will contain a circular array of long values and if more than the configured amount (1000 values for example) it will wrap around and overwrite values until time passes and a new bucket * is allocated. This sampling approach for high volume metrics is done to conserve memory and reduce sorting time when calculating percentiles. */ public class HystrixRollingPercentile { private static final Logger logger = LoggerFactory.getLogger(HystrixRollingPercentile.class); private static final Time ACTUAL_TIME = new ActualTime(); private final Time time; /* package for testing */ final BucketCircularArray buckets; private final int timeInMilliseconds; private final int numberOfBuckets; private final int bucketDataLength; private final int bucketSizeInMilliseconds; private final HystrixProperty<Boolean> enabled; /* * This will get flipped each time a new bucket is created. */ /* package for testing */ volatile PercentileSnapshot currentPercentileSnapshot = new PercentileSnapshot(0); /** * * @param timeInMilliseconds * {@code HystrixProperty<Integer>} for number of milliseconds of data that should be tracked * Note that this value is represented as a {@link HystrixProperty}, but can not actually be modified * at runtime, to avoid data loss * <p> * Example: 60000 for 1 minute * @param numberOfBuckets * {@code HystrixProperty<Integer>} for number of buckets that the time window should be divided into * Note that this value is represented as a {@link HystrixProperty}, but can not actually be modified * at runtime, to avoid data loss * <p> * Example: 12 for 5 second buckets in a 1 minute window * @param bucketDataLength * {@code HystrixProperty<Integer>} for number of values stored in each bucket * Note that this value is represented as a {@link HystrixProperty}, but can not actually be modified * at runtime, to avoid data loss * <p> * Example: 1000 to store a max of 1000 values in each 5 second bucket * @param enabled * {@code HystrixProperty<Boolean>} whether data should be tracked and percentiles calculated. * <p> * If 'false' methods will do nothing. * @deprecated Please use the constructor with non-configurable properties {@link HystrixRollingPercentile(Time, int, int, int, HystrixProperty<Boolean>} */ @Deprecated public HystrixRollingPercentile(HystrixProperty<Integer> timeInMilliseconds, HystrixProperty<Integer> numberOfBuckets, HystrixProperty<Integer> bucketDataLength, HystrixProperty<Boolean> enabled) { this(timeInMilliseconds.get(), numberOfBuckets.get(), bucketDataLength.get(), enabled); } /** * * @param timeInMilliseconds * number of milliseconds of data that should be tracked * <p> * Example: 60000 for 1 minute * @param numberOfBuckets * number of buckets that the time window should be divided into * <p> * Example: 12 for 5 second buckets in a 1 minute window * @param bucketDataLength * number of values stored in each bucket * <p> * Example: 1000 to store a max of 1000 values in each 5 second bucket * @param enabled * {@code HystrixProperty<Boolean>} whether data should be tracked and percentiles calculated. * <p> * If 'false' methods will do nothing. */ public HystrixRollingPercentile(int timeInMilliseconds, int numberOfBuckets, int bucketDataLength, HystrixProperty<Boolean> enabled) { this(ACTUAL_TIME, timeInMilliseconds, numberOfBuckets, bucketDataLength, enabled); } /* package for testing */ HystrixRollingPercentile(Time time, int timeInMilliseconds, int numberOfBuckets, int bucketDataLength, HystrixProperty<Boolean> enabled) { this.time = time; this.timeInMilliseconds = timeInMilliseconds; this.numberOfBuckets = numberOfBuckets; this.bucketDataLength = bucketDataLength; this.enabled = enabled; if (this.timeInMilliseconds % this.numberOfBuckets != 0) { throw new IllegalArgumentException("The timeInMilliseconds must divide equally into numberOfBuckets. For example 1000/10 is ok, 1000/11 is not."); } this.bucketSizeInMilliseconds = this.timeInMilliseconds / this.numberOfBuckets; buckets = new BucketCircularArray(this.numberOfBuckets); } /** * Add value (or values) to current bucket. * * @param value * Value to be stored in current bucket such as execution latency in milliseconds */ public void addValue(int... value) { /* no-op if disabled */ if (!enabled.get()) return; for (int v : value) { try { getCurrentBucket().data.addValue(v); } catch (Exception e) { logger.error("Failed to add value: " + v, e); } } } /** * Compute a percentile from the underlying rolling buckets of values. * <p> * For performance reasons it maintains a single snapshot of the sorted values from all buckets that is re-generated each time the bucket rotates. * <p> * This means that if a bucket is 5000ms, then this method will re-compute a percentile at most once every 5000ms. * * @param percentile * value such as 99 (99th percentile), 99.5 (99.5th percentile), 50 (median, 50th percentile) to compute and retrieve percentile from rolling buckets. * @return int percentile value */ public int getPercentile(double percentile) { /* no-op if disabled */ if (!enabled.get()) return -1; // force logic to move buckets forward in case other requests aren't making it happen getCurrentBucket(); // fetch the current snapshot return getCurrentPercentileSnapshot().getPercentile(percentile); } /** * This returns the mean (average) of all values in the current snapshot. This is not a percentile but often desired so captured and exposed here. * * @return mean of all values */ public int getMean() { /* no-op if disabled */ if (!enabled.get()) return -1; // force logic to move buckets forward in case other requests aren't making it happen getCurrentBucket(); // fetch the current snapshot return getCurrentPercentileSnapshot().getMean(); } /** * This will retrieve the current snapshot or create a new one if one does not exist. * <p> * It will NOT include data from the current bucket, but all previous buckets. * <p> * It remains cached until the next bucket rotates at which point a new one will be created. */ private PercentileSnapshot getCurrentPercentileSnapshot() { return currentPercentileSnapshot; } private ReentrantLock newBucketLock = new ReentrantLock(); private Bucket getCurrentBucket() { long currentTime = time.getCurrentTimeInMillis(); /* a shortcut to try and get the most common result of immediately finding the current bucket */ /** * Retrieve the latest bucket if the given time is BEFORE the end of the bucket window, otherwise it returns NULL. * * NOTE: This is thread-safe because it's accessing 'buckets' which is a LinkedBlockingDeque */ Bucket currentBucket = buckets.peekLast(); if (currentBucket != null && currentTime < currentBucket.windowStart + this.bucketSizeInMilliseconds) { // if we're within the bucket 'window of time' return the current one // NOTE: We do not worry if we are BEFORE the window in a weird case of where thread scheduling causes that to occur, // we'll just use the latest as long as we're not AFTER the window return currentBucket; } /* if we didn't find the current bucket above, then we have to create one */ /** * The following needs to be synchronized/locked even with a synchronized/thread-safe data structure such as LinkedBlockingDeque because * the logic involves multiple steps to check existence, create an object then insert the object. The 'check' or 'insertion' themselves * are thread-safe by themselves but not the aggregate algorithm, thus we put this entire block of logic inside synchronized. * * I am using a tryLock if/then (http://download.oracle.com/javase/6/docs/api/java/util/concurrent/locks/Lock.html#tryLock()) * so that a single thread will get the lock and as soon as one thread gets the lock all others will go the 'else' block * and just return the currentBucket until the newBucket is created. This should allow the throughput to be far higher * and only slow down 1 thread instead of blocking all of them in each cycle of creating a new bucket based on some testing * (and it makes sense that it should as well). * * This means the timing won't be exact to the millisecond as to what data ends up in a bucket, but that's acceptable. * It's not critical to have exact precision to the millisecond, as long as it's rolling, if we can instead reduce the impact synchronization. * * More importantly though it means that the 'if' block within the lock needs to be careful about what it changes that can still * be accessed concurrently in the 'else' block since we're not completely synchronizing access. * * For example, we can't have a multi-step process to add a bucket, remove a bucket, then update the sum since the 'else' block of code * can retrieve the sum while this is all happening. The trade-off is that we don't maintain the rolling sum and let readers just iterate * bucket to calculate the sum themselves. This is an example of favoring write-performance instead of read-performance and how the tryLock * versus a synchronized block needs to be accommodated. */ if (newBucketLock.tryLock()) { try { if (buckets.peekLast() == null) { // the list is empty so create the first bucket Bucket newBucket = new Bucket(currentTime, bucketDataLength); buckets.addLast(newBucket); return newBucket; } else { // We go into a loop so that it will create as many buckets as needed to catch up to the current time // as we want the buckets complete even if we don't have transactions during a period of time. for (int i = 0; i < numberOfBuckets; i++) { // we have at least 1 bucket so retrieve it Bucket lastBucket = buckets.peekLast(); if (currentTime < lastBucket.windowStart + this.bucketSizeInMilliseconds) { // if we're within the bucket 'window of time' return the current one // NOTE: We do not worry if we are BEFORE the window in a weird case of where thread scheduling causes that to occur, // we'll just use the latest as long as we're not AFTER the window return lastBucket; } else if (currentTime - (lastBucket.windowStart + this.bucketSizeInMilliseconds) > timeInMilliseconds) { // the time passed is greater than the entire rolling counter so we want to clear it all and start from scratch reset(); // recursively call getCurrentBucket which will create a new bucket and return it return getCurrentBucket(); } else { // we're past the window so we need to create a new bucket Bucket[] allBuckets = buckets.getArray(); // create a new bucket and add it as the new 'last' (once this is done other threads will start using it on subsequent retrievals) buckets.addLast(new Bucket(lastBucket.windowStart + this.bucketSizeInMilliseconds, bucketDataLength)); // we created a new bucket so let's re-generate the PercentileSnapshot (not including the new bucket) currentPercentileSnapshot = new PercentileSnapshot(allBuckets); } } // we have finished the for-loop and created all of the buckets, so return the lastBucket now return buckets.peekLast(); } } finally { newBucketLock.unlock(); } } else { currentBucket = buckets.peekLast(); if (currentBucket != null) { // we didn't get the lock so just return the latest bucket while another thread creates the next one return currentBucket; } else { // the rare scenario where multiple threads raced to create the very first bucket // wait slightly and then use recursion while the other thread finishes creating a bucket try { Thread.sleep(5); } catch (Exception e) { // ignore } return getCurrentBucket(); } } } /** * Force a reset so that percentiles start being gathered from scratch. */ public void reset() { /* no-op if disabled */ if (!enabled.get()) return; // clear buckets so we start over again buckets.clear(); // and also make sure the percentile snapshot gets reset currentPercentileSnapshot = new PercentileSnapshot(buckets.getArray()); } /* package-private for testing */ static class PercentileBucketData { private final int length; private final AtomicIntegerArray list; private final AtomicInteger index = new AtomicInteger(); public PercentileBucketData(int dataLength) { this.length = dataLength; this.list = new AtomicIntegerArray(dataLength); } public void addValue(int... latency) { for (int l : latency) { /* We just wrap around the beginning and over-write if we go past 'dataLength' as that will effectively cause us to "sample" the most recent data */ list.set(index.getAndIncrement() % length, l); // TODO Alternative to AtomicInteger? The getAndIncrement may be a source of contention on high throughput circuits on large multi-core systems. // LongAdder isn't suited to this as it is not consistent. Perhaps a different data structure that doesn't need indexed adds? // A threadlocal data storage that only aggregates when fetched would be ideal. Similar to LongAdder except for accumulating lists of data. } } public int length() { if (index.get() > list.length()) { return list.length(); } else { return index.get(); } } } /** * @NotThreadSafe */ /* package for testing */ static class PercentileSnapshot { private final int[] data; private final int length; private int mean; /* package for testing */ PercentileSnapshot(Bucket[] buckets) { int lengthFromBuckets = 0; // we need to calculate it dynamically as it could have been changed by properties (rare, but possible) // also this way we capture the actual index size rather than the max so size the int[] to only what we need for (Bucket bd : buckets) { lengthFromBuckets += bd.data.length; } data = new int[lengthFromBuckets]; int index = 0; int sum = 0; for (Bucket bd : buckets) { PercentileBucketData pbd = bd.data; int length = pbd.length(); for (int i = 0; i < length; i++) { int v = pbd.list.get(i); this.data[index++] = v; sum += v; } } this.length = index; if (this.length == 0) { this.mean = 0; } else { this.mean = sum / this.length; } Arrays.sort(this.data, 0, length); } /* package for testing */ PercentileSnapshot(int... data) { this.data = data; this.length = data.length; int sum = 0; for (int v : data) { sum += v; } this.mean = sum / this.length; Arrays.sort(this.data, 0, length); } /* package for testing */ int getMean() { return mean; } /** * Provides percentile computation. */ public int getPercentile(double percentile) { if (length == 0) { return 0; } return computePercentile(percentile); } /** * @see <a href="http://en.wikipedia.org/wiki/Percentile">Percentile (Wikipedia)</a> * @see <a href="http://cnx.org/content/m10805/latest/">Percentile</a> * * @param percent percentile of data desired * @return data at the asked-for percentile. Interpolation is used if exactness is not possible */ private int computePercentile(double percent) { // Some just-in-case edge cases if (length <= 0) { return 0; } else if (percent <= 0.0) { return data[0]; } else if (percent >= 100.0) { return data[length - 1]; } // ranking (http://en.wikipedia.org/wiki/Percentile#Alternative_methods) double rank = (percent / 100.0) * length; // linear interpolation between closest ranks int iLow = (int) Math.floor(rank); int iHigh = (int) Math.ceil(rank); assert 0 <= iLow && iLow <= rank && rank <= iHigh && iHigh <= length; assert (iHigh - iLow) <= 1; if (iHigh >= length) { // Another edge case return data[length - 1]; } else if (iLow == iHigh) { return data[iLow]; } else { // Interpolate between the two bounding values return (int) (data[iLow] + (rank - iLow) * (data[iHigh] - data[iLow])); } } } /** * This is a circular array acting as a FIFO queue. * <p> * It purposefully does NOT implement Deque or some other Collection interface as it only implements functionality necessary for this RollingNumber use case. * <p> * Important Thread-Safety Note: This is ONLY thread-safe within the context of RollingNumber and the protection it gives in the <code>getCurrentBucket</code> method. It uses AtomicReference * objects to ensure anything done outside of <code>getCurrentBucket</code> is thread-safe, and to ensure visibility of changes across threads (ie. volatility) but the addLast and removeFirst * methods are NOT thread-safe for external access they depend upon the lock.tryLock() protection in <code>getCurrentBucket</code> which ensures only a single thread will access them at at time. * <p> * benjchristensen => This implementation was chosen based on performance testing I did and documented at: http://benjchristensen.com/2011/10/08/atomiccirculararray/ */ /* package for testing */ static class BucketCircularArray implements Iterable<Bucket> { private final AtomicReference<ListState> state; private final int dataLength; // we don't resize, we always stay the same, so remember this private final int numBuckets; /** * Immutable object that is atomically set every time the state of the BucketCircularArray changes * <p> * This handles the compound operations */ private class ListState { /* * this is an AtomicReferenceArray and not a normal Array because we're copying the reference * between ListState objects and multiple threads could maintain references across these * compound operations so I want the visibility/concurrency guarantees */ private final AtomicReferenceArray<Bucket> data; private final int size; private final int tail; private final int head; private ListState(AtomicReferenceArray<Bucket> data, int head, int tail) { this.head = head; this.tail = tail; if (head == 0 && tail == 0) { size = 0; } else { this.size = (tail + dataLength - head) % dataLength; } this.data = data; } public Bucket tail() { if (size == 0) { return null; } else { // we want to get the last item, so size()-1 return data.get(convert(size - 1)); } } private Bucket[] getArray() { /* * this isn't technically thread-safe since it requires multiple reads on something that can change * but since we never clear the data directly, only increment/decrement head/tail we would never get a NULL * just potentially return stale data which we are okay with doing */ ArrayList<Bucket> array = new ArrayList<Bucket>(); for (int i = 0; i < size; i++) { array.add(data.get(convert(i))); } return array.toArray(new Bucket[array.size()]); } private ListState incrementTail() { /* if incrementing results in growing larger than 'length' which is the max we should be at, then also increment head (equivalent of removeFirst but done atomically) */ if (size == numBuckets) { // increment tail and head return new ListState(data, (head + 1) % dataLength, (tail + 1) % dataLength); } else { // increment only tail return new ListState(data, head, (tail + 1) % dataLength); } } public ListState clear() { return new ListState(new AtomicReferenceArray<Bucket>(dataLength), 0, 0); } public ListState addBucket(Bucket b) { /* * We could in theory have 2 threads addBucket concurrently and this compound operation would interleave. * <p> * This should NOT happen since getCurrentBucket is supposed to be executed by a single thread. * <p> * If it does happen, it's not a huge deal as incrementTail() will be protected by compareAndSet and one of the two addBucket calls will succeed with one of the Buckets. * <p> * In either case, a single Bucket will be returned as "last" and data loss should not occur and everything keeps in sync for head/tail. * <p> * Also, it's fine to set it before incrementTail because nothing else should be referencing that index position until incrementTail occurs. */ data.set(tail, b); return incrementTail(); } // The convert() method takes a logical index (as if head was // always 0) and calculates the index within elementData private int convert(int index) { return (index + head) % dataLength; } } BucketCircularArray(int size) { AtomicReferenceArray<Bucket> _buckets = new AtomicReferenceArray<Bucket>(size + 1); // + 1 as extra room for the add/remove; state = new AtomicReference<ListState>(new ListState(_buckets, 0, 0)); dataLength = _buckets.length(); numBuckets = size; } public void clear() { while (true) { /* * it should be very hard to not succeed the first pass thru since this is typically is only called from * a single thread protected by a tryLock, but there is at least 1 other place (at time of writing this comment) * where reset can be called from (CircuitBreaker.markSuccess after circuit was tripped) so it can * in an edge-case conflict. * * Instead of trying to determine if someone already successfully called clear() and we should skip * we will have both calls reset the circuit, even if that means losing data added in between the two * depending on thread scheduling. * * The rare scenario in which that would occur, we'll accept the possible data loss while clearing it * since the code has stated its desire to clear() anyways. */ ListState current = state.get(); ListState newState = current.clear(); if (state.compareAndSet(current, newState)) { return; } } } /** * Returns an iterator on a copy of the internal array so that the iterator won't fail by buckets being added/removed concurrently. */ public Iterator<Bucket> iterator() { return Collections.unmodifiableList(Arrays.asList(getArray())).iterator(); } public void addLast(Bucket o) { ListState currentState = state.get(); // create new version of state (what we want it to become) ListState newState = currentState.addBucket(o); /* * use compareAndSet to set in case multiple threads are attempting (which shouldn't be the case because since addLast will ONLY be called by a single thread at a time due to protection * provided in <code>getCurrentBucket</code>) */ if (state.compareAndSet(currentState, newState)) { // we succeeded return; } else { // we failed, someone else was adding or removing // instead of trying again and risking multiple addLast concurrently (which shouldn't be the case) // we'll just return and let the other thread 'win' and if the timing is off the next call to getCurrentBucket will fix things return; } } public int size() { // the size can also be worked out each time as: // return (tail + data.length() - head) % data.length(); return state.get().size; } public Bucket peekLast() { return state.get().tail(); } private Bucket[] getArray() { return state.get().getArray(); } } /** * Counters for a given 'bucket' of time. */ /* package for testing */ static class Bucket { final long windowStart; final PercentileBucketData data; Bucket(long startTime, int bucketDataLength) { this.windowStart = startTime; this.data = new PercentileBucketData(bucketDataLength); } } /* package for testing */ static interface Time { public long getCurrentTimeInMillis(); } private static class ActualTime implements Time { @Override public long getCurrentTimeInMillis() { return System.currentTimeMillis(); } } }
4,656
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/util/HystrixRollingNumberEvent.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.util; import com.netflix.hystrix.HystrixEventType; /** * Various states/events that can be captured in the {@link HystrixRollingNumber}. * <p> * Note that events are defined as different types: * <ul> * <li>Counter: <code>isCounter() == true</code></li> * <li>MaxUpdater: <code>isMaxUpdater() == true</code></li> * </ul> * <p> * The Counter type events can be used with {@link HystrixRollingNumber#increment}, {@link HystrixRollingNumber#add}, {@link HystrixRollingNumber#getRollingSum} and others. * <p> * The MaxUpdater type events can be used with {@link HystrixRollingNumber#updateRollingMax} and {@link HystrixRollingNumber#getRollingMaxValue}. */ public enum HystrixRollingNumberEvent { SUCCESS(1), FAILURE(1), TIMEOUT(1), SHORT_CIRCUITED(1), THREAD_POOL_REJECTED(1), SEMAPHORE_REJECTED(1), BAD_REQUEST(1), FALLBACK_SUCCESS(1), FALLBACK_FAILURE(1), FALLBACK_REJECTION(1), FALLBACK_DISABLED(1), FALLBACK_MISSING(1), EXCEPTION_THROWN(1), COMMAND_MAX_ACTIVE(2), EMIT(1), FALLBACK_EMIT(1), THREAD_EXECUTION(1), THREAD_MAX_ACTIVE(2), COLLAPSED(1), RESPONSE_FROM_CACHE(1), COLLAPSER_REQUEST_BATCHED(1), COLLAPSER_BATCH(1); private final int type; private HystrixRollingNumberEvent(int type) { this.type = type; } public boolean isCounter() { return type == 1; } public boolean isMaxUpdater() { return type == 2; } public static HystrixRollingNumberEvent from(HystrixEventType eventType) { switch (eventType) { case BAD_REQUEST: return HystrixRollingNumberEvent.BAD_REQUEST; case COLLAPSED: return HystrixRollingNumberEvent.COLLAPSED; case EMIT: return HystrixRollingNumberEvent.EMIT; case EXCEPTION_THROWN: return HystrixRollingNumberEvent.EXCEPTION_THROWN; case FAILURE: return HystrixRollingNumberEvent.FAILURE; case FALLBACK_EMIT: return HystrixRollingNumberEvent.FALLBACK_EMIT; case FALLBACK_FAILURE: return HystrixRollingNumberEvent.FALLBACK_FAILURE; case FALLBACK_DISABLED: return HystrixRollingNumberEvent.FALLBACK_DISABLED; case FALLBACK_MISSING: return HystrixRollingNumberEvent.FALLBACK_MISSING; case FALLBACK_REJECTION: return HystrixRollingNumberEvent.FALLBACK_REJECTION; case FALLBACK_SUCCESS: return HystrixRollingNumberEvent.FALLBACK_SUCCESS; case RESPONSE_FROM_CACHE: return HystrixRollingNumberEvent.RESPONSE_FROM_CACHE; case SEMAPHORE_REJECTED: return HystrixRollingNumberEvent.SEMAPHORE_REJECTED; case SHORT_CIRCUITED: return HystrixRollingNumberEvent.SHORT_CIRCUITED; case SUCCESS: return HystrixRollingNumberEvent.SUCCESS; case THREAD_POOL_REJECTED: return HystrixRollingNumberEvent.THREAD_POOL_REJECTED; case TIMEOUT: return HystrixRollingNumberEvent.TIMEOUT; default: throw new RuntimeException("Unknown HystrixEventType : " + eventType); } } }
4,657
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/util/PlatformSpecific.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.util; import java.lang.reflect.InvocationTargetException; import java.util.concurrent.ThreadFactory; public class PlatformSpecific { private final Platform platform; private enum Platform { STANDARD, APPENGINE_STANDARD, APPENGINE_FLEXIBLE } private static PlatformSpecific INSTANCE = new PlatformSpecific(); private PlatformSpecific() { platform = determinePlatformReflectively(); } public static boolean isAppEngineStandardEnvironment() { return INSTANCE.platform == Platform.APPENGINE_STANDARD; } public static boolean isAppEngine() { return INSTANCE.platform == Platform.APPENGINE_FLEXIBLE || INSTANCE.platform == Platform.APPENGINE_STANDARD; } /* * This detection mechanism is from Guava - specifically * http://docs.guava-libraries.googlecode.com/git/javadoc/src-html/com/google/common/util/concurrent/MoreExecutors.html#line.766 * Added GAE_LONG_APP_ID check to detect only AppEngine Standard Environment */ private static Platform determinePlatformReflectively() { if (System.getProperty("com.google.appengine.runtime.environment") == null) { return Platform.STANDARD; } // GAE_LONG_APP_ID is only set in the GAE Flexible Environment, where we want standard threading if (System.getenv("GAE_LONG_APP_ID") != null) { return Platform.APPENGINE_FLEXIBLE; } try { // If the current environment is null, we're not inside AppEngine. boolean isInsideAppengine = Class.forName("com.google.apphosting.api.ApiProxy") .getMethod("getCurrentEnvironment") .invoke(null) != null; return isInsideAppengine ? Platform.APPENGINE_STANDARD : Platform.STANDARD; } catch (ClassNotFoundException e) { // If ApiProxy doesn't exist, we're not on AppEngine at all. return Platform.STANDARD; } catch (InvocationTargetException e) { // If ApiProxy throws an exception, we're not in a proper AppEngine environment. return Platform.STANDARD; } catch (IllegalAccessException e) { // If the method isn't accessible, we're not on a supported version of AppEngine; return Platform.STANDARD; } catch (NoSuchMethodException e) { // If the method doesn't exist, we're not on a supported version of AppEngine; return Platform.STANDARD; } } public static ThreadFactory getAppEngineThreadFactory() { try { return (ThreadFactory) Class.forName("com.google.appengine.api.ThreadManager") .getMethod("currentRequestThreadFactory") .invoke(null); } catch (IllegalAccessException e) { throw new RuntimeException("Couldn't invoke ThreadManager.currentRequestThreadFactory", e); } catch (ClassNotFoundException e) { throw new RuntimeException("Couldn't invoke ThreadManager.currentRequestThreadFactory", e); } catch (NoSuchMethodException e) { throw new RuntimeException("Couldn't invoke ThreadManager.currentRequestThreadFactory", e); } catch (InvocationTargetException e) { throw new RuntimeException(e.getCause()); } } }
4,658
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/util/package-info.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. */ /** * Common utility classes. * * @since 1.0.0 */ package com.netflix.hystrix.util;
4,659
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/util/Striped64.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.util; /* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ * * From http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/ */ import java.util.Random; /** * A package-local class holding common representation and mechanics * for classes supporting dynamic striping on 64bit values. The class * extends Number so that concrete subclasses must publicly do so. */ abstract class Striped64 extends Number { /* * This class maintains a lazily-initialized table of atomically * updated variables, plus an extra "base" field. The table size * is a power of two. Indexing uses masked per-thread hash codes. * Nearly all declarations in this class are package-private, * accessed directly by subclasses. * * Table entries are of class Cell; a variant of AtomicLong padded * to reduce cache contention on most processors. Padding is * overkill for most Atomics because they are usually irregularly * scattered in memory and thus don't interfere much with each * other. But Atomic objects residing in arrays will tend to be * placed adjacent to each other, and so will most often share * cache lines (with a huge negative performance impact) without * this precaution. * * In part because Cells are relatively large, we avoid creating * them until they are needed. When there is no contention, all * updates are made to the base field. Upon first contention (a * failed CAS on base update), the table is initialized to size 2. * The table size is doubled upon further contention until * reaching the nearest power of two greater than or equal to the * number of CPUS. Table slots remain empty (null) until they are * needed. * * A single spinlock ("busy") is used for initializing and * resizing the table, as well as populating slots with new Cells. * There is no need for a blocking lock: When the lock is not * available, threads try other slots (or the base). During these * retries, there is increased contention and reduced locality, * which is still better than alternatives. * * Per-thread hash codes are initialized to random values. * Contention and/or table collisions are indicated by failed * CASes when performing an update operation (see method * retryUpdate). Upon a collision, if the table size is less than * the capacity, it is doubled in size unless some other thread * holds the lock. If a hashed slot is empty, and lock is * available, a new Cell is created. Otherwise, if the slot * exists, a CAS is tried. Retries proceed by "double hashing", * using a secondary hash (Marsaglia XorShift) to try to find a * free slot. * * The table size is capped because, when there are more threads * than CPUs, supposing that each thread were bound to a CPU, * there would exist a perfect hash function mapping threads to * slots that eliminates collisions. When we reach capacity, we * search for this mapping by randomly varying the hash codes of * colliding threads. Because search is random, and collisions * only become known via CAS failures, convergence can be slow, * and because threads are typically not bound to CPUS forever, * may not occur at all. However, despite these limitations, * observed contention rates are typically low in these cases. * * It is possible for a Cell to become unused when threads that * once hashed to it terminate, as well as in the case where * doubling the table causes no thread to hash to it under * expanded mask. We do not try to detect or remove such cells, * under the assumption that for long-running instances, observed * contention levels will recur, so the cells will eventually be * needed again; and for short-lived ones, it does not matter. */ private static final long serialVersionUID = -3403386352761423917L; /** * Padded variant of AtomicLong supporting only raw accesses plus CAS. * The value field is placed between pads, hoping that the JVM doesn't * reorder them. * * JVM intrinsics note: It would be possible to use a release-only * form of CAS here, if it were provided. */ static final class Cell { volatile long p0, p1, p2, p3, p4, p5, p6; volatile long value; volatile long q0, q1, q2, q3, q4, q5, q6; Cell(long x) { value = x; } final boolean cas(long cmp, long val) { return UNSAFE.compareAndSwapLong(this, valueOffset, cmp, val); } // Unsafe mechanics private static final sun.misc.Unsafe UNSAFE; private static final long valueOffset; static { try { UNSAFE = getUnsafe(); Class<?> ak = Cell.class; valueOffset = UNSAFE.objectFieldOffset (ak.getDeclaredField("value")); } catch (Exception e) { throw new Error(e); } } } /** * Holder for the thread-local hash code. The code is initially * random, but may be set to a different value upon collisions. */ static final class HashCode { static final Random rng = new Random(); int code; HashCode() { int h = rng.nextInt(); // Avoid zero to allow xorShift rehash code = (h == 0) ? 1 : h; } } /** * The corresponding ThreadLocal class */ static final class ThreadHashCode extends ThreadLocal<HashCode> { public HashCode initialValue() { return new HashCode(); } } /** * Static per-thread hash codes. Shared across all instances to * reduce ThreadLocal pollution and because adjustments due to * collisions in one table are likely to be appropriate for * others. */ static final ThreadHashCode threadHashCode = new ThreadHashCode(); /** Number of CPUS, to place bound on table size */ static final int NCPU = Runtime.getRuntime().availableProcessors(); /** * Table of cells. When non-null, size is a power of 2. */ transient volatile Cell[] cells; /** * Base value, used mainly when there is no contention, but also as * a fallback during table initialization races. Updated via CAS. */ transient volatile long base; /** * Spinlock (locked via CAS) used when resizing and/or creating Cells. */ transient volatile int busy; /** * Package-private default constructor */ Striped64() { } /** * CASes the base field. */ final boolean casBase(long cmp, long val) { return UNSAFE.compareAndSwapLong(this, baseOffset, cmp, val); } /** * CASes the busy field from 0 to 1 to acquire lock. */ final boolean casBusy() { return UNSAFE.compareAndSwapInt(this, busyOffset, 0, 1); } /** * Computes the function of current and new value. Subclasses * should open-code this update function for most uses, but the * virtualized form is needed within retryUpdate. * * @param currentValue the current value (of either base or a cell) * @param newValue the argument from a user update call * @return result of the update function */ abstract long fn(long currentValue, long newValue); /** * Handles cases of updates involving initialization, resizing, * creating new Cells, and/or contention. See above for * explanation. This method suffers the usual non-modularity * problems of optimistic retry code, relying on rechecked sets of * reads. * * @param x the value * @param hc the hash code holder * @param wasUncontended false if CAS failed before call */ final void retryUpdate(long x, HashCode hc, boolean wasUncontended) { int h = hc.code; boolean collide = false; // True if last slot nonempty for (;;) { Cell[] as; Cell a; int n; long v; if ((as = cells) != null && (n = as.length) > 0) { if ((a = as[(n - 1) & h]) == null) { if (busy == 0) { // Try to attach new Cell Cell r = new Cell(x); // Optimistically create if (busy == 0 && casBusy()) { boolean created = false; try { // Recheck under lock Cell[] rs; int m, j; if ((rs = cells) != null && (m = rs.length) > 0 && rs[j = (m - 1) & h] == null) { rs[j] = r; created = true; } } finally { busy = 0; } if (created) break; continue; // Slot is now non-empty } } collide = false; } else if (!wasUncontended) // CAS already known to fail wasUncontended = true; // Continue after rehash else if (a.cas(v = a.value, fn(v, x))) break; else if (n >= NCPU || cells != as) collide = false; // At max size or stale else if (!collide) collide = true; else if (busy == 0 && casBusy()) { try { if (cells == as) { // Expand table unless stale Cell[] rs = new Cell[n << 1]; for (int i = 0; i < n; ++i) rs[i] = as[i]; cells = rs; } } finally { busy = 0; } collide = false; continue; // Retry with expanded table } h ^= h << 13; // Rehash h ^= h >>> 17; h ^= h << 5; } else if (busy == 0 && cells == as && casBusy()) { boolean init = false; try { // Initialize table if (cells == as) { Cell[] rs = new Cell[2]; rs[h & 1] = new Cell(x); cells = rs; init = true; } } finally { busy = 0; } if (init) break; } else if (casBase(v = base, fn(v, x))) break; // Fall back on using base } hc.code = h; // Record index for next time } /** * Sets base and all cells to the given value. */ final void internalReset(long initialValue) { Cell[] as = cells; base = initialValue; if (as != null) { int n = as.length; for (int i = 0; i < n; ++i) { Cell a = as[i]; if (a != null) a.value = initialValue; } } } // Unsafe mechanics private static final sun.misc.Unsafe UNSAFE; private static final long baseOffset; private static final long busyOffset; static { try { UNSAFE = getUnsafe(); Class<?> sk = Striped64.class; baseOffset = UNSAFE.objectFieldOffset (sk.getDeclaredField("base")); busyOffset = UNSAFE.objectFieldOffset (sk.getDeclaredField("busy")); } catch (Exception e) { throw new Error(e); } } /** * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. * Replace with a simple call to Unsafe.getUnsafe when integrating * into a jdk. * * @return a sun.misc.Unsafe */ private static sun.misc.Unsafe getUnsafe() { try { return sun.misc.Unsafe.getUnsafe(); } catch (SecurityException se) { try { return java.security.AccessController.doPrivileged (new java.security .PrivilegedExceptionAction<sun.misc.Unsafe>() { public sun.misc.Unsafe run() throws Exception { java.lang.reflect.Field f = sun.misc .Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); return (sun.misc.Unsafe) f.get(null); }}); } catch (java.security.PrivilegedActionException e) { throw new RuntimeException("Could not initialize intrinsics", e.getCause()); } } } }
4,660
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/config/HystrixConfigurationStream.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.netflix.config.DynamicIntProperty; import com.netflix.config.DynamicPropertyFactory; 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 rx.Observable; import rx.functions.Action0; import rx.functions.Func1; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * This class samples current Hystrix configuration and exposes that as a stream */ public class HystrixConfigurationStream { private final int intervalInMilliseconds; private final Observable<HystrixConfiguration> allConfigurationStream; private final AtomicBoolean isSourceCurrentlySubscribed = new AtomicBoolean(false); private static final DynamicIntProperty dataEmissionIntervalInMs = DynamicPropertyFactory.getInstance().getIntProperty("hystrix.stream.config.intervalInMilliseconds", 5000); private static final Func1<Long, HystrixConfiguration> getAllConfig = new Func1<Long, HystrixConfiguration>() { @Override public HystrixConfiguration call(Long timestamp) { return HystrixConfiguration.from( getAllCommandConfig.call(timestamp), getAllThreadPoolConfig.call(timestamp), getAllCollapserConfig.call(timestamp) ); } }; /** * @deprecated Not for public use. Please use {@link #getInstance()}. This facilitates better stream-sharing * @param intervalInMilliseconds milliseconds between data emissions */ @Deprecated //deprecated in 1.5.4. public HystrixConfigurationStream(final int intervalInMilliseconds) { this.intervalInMilliseconds = intervalInMilliseconds; this.allConfigurationStream = Observable.interval(intervalInMilliseconds, TimeUnit.MILLISECONDS) .map(getAllConfig) .doOnSubscribe(new Action0() { @Override public void call() { isSourceCurrentlySubscribed.set(true); } }) .doOnUnsubscribe(new Action0() { @Override public void call() { isSourceCurrentlySubscribed.set(false); } }) .share() .onBackpressureDrop(); } //The data emission interval is looked up on startup only private static final HystrixConfigurationStream INSTANCE = new HystrixConfigurationStream(dataEmissionIntervalInMs.get()); public static HystrixConfigurationStream getInstance() { return INSTANCE; } static HystrixConfigurationStream getNonSingletonInstanceOnlyUsedInUnitTests(int delayInMs) { return new HystrixConfigurationStream(delayInMs); } /** * Return a ref-counted stream that will only do work when at least one subscriber is present */ public Observable<HystrixConfiguration> observe() { return allConfigurationStream; } public Observable<Map<HystrixCommandKey, HystrixCommandConfiguration>> observeCommandConfiguration() { return allConfigurationStream.map(getOnlyCommandConfig); } public Observable<Map<HystrixThreadPoolKey, HystrixThreadPoolConfiguration>> observeThreadPoolConfiguration() { return allConfigurationStream.map(getOnlyThreadPoolConfig); } public Observable<Map<HystrixCollapserKey, HystrixCollapserConfiguration>> observeCollapserConfiguration() { return allConfigurationStream.map(getOnlyCollapserConfig); } public int getIntervalInMilliseconds() { return this.intervalInMilliseconds; } public boolean isSourceCurrentlySubscribed() { return isSourceCurrentlySubscribed.get(); } private static HystrixCommandConfiguration sampleCommandConfiguration(HystrixCommandKey commandKey, HystrixThreadPoolKey threadPoolKey, HystrixCommandGroupKey groupKey, HystrixCommandProperties commandProperties) { return HystrixCommandConfiguration.sample(commandKey, threadPoolKey, groupKey, commandProperties); } private static HystrixThreadPoolConfiguration sampleThreadPoolConfiguration(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties threadPoolProperties) { return HystrixThreadPoolConfiguration.sample(threadPoolKey, threadPoolProperties); } private static HystrixCollapserConfiguration sampleCollapserConfiguration(HystrixCollapserKey collapserKey, HystrixCollapserProperties collapserProperties) { return HystrixCollapserConfiguration.sample(collapserKey, collapserProperties); } private static final Func1<Long, Map<HystrixCommandKey, HystrixCommandConfiguration>> getAllCommandConfig = new Func1<Long, Map<HystrixCommandKey, HystrixCommandConfiguration>>() { @Override public Map<HystrixCommandKey, HystrixCommandConfiguration> call(Long timestamp) { Map<HystrixCommandKey, HystrixCommandConfiguration> commandConfigPerKey = new HashMap<HystrixCommandKey, HystrixCommandConfiguration>(); for (HystrixCommandMetrics commandMetrics: HystrixCommandMetrics.getInstances()) { HystrixCommandKey commandKey = commandMetrics.getCommandKey(); HystrixThreadPoolKey threadPoolKey = commandMetrics.getThreadPoolKey(); HystrixCommandGroupKey groupKey = commandMetrics.getCommandGroup(); commandConfigPerKey.put(commandKey, sampleCommandConfiguration(commandKey, threadPoolKey, groupKey, commandMetrics.getProperties())); } return commandConfigPerKey; } }; private static final Func1<Long, Map<HystrixThreadPoolKey, HystrixThreadPoolConfiguration>> getAllThreadPoolConfig = new Func1<Long, Map<HystrixThreadPoolKey, HystrixThreadPoolConfiguration>>() { @Override public Map<HystrixThreadPoolKey, HystrixThreadPoolConfiguration> call(Long timestamp) { Map<HystrixThreadPoolKey, HystrixThreadPoolConfiguration> threadPoolConfigPerKey = new HashMap<HystrixThreadPoolKey, HystrixThreadPoolConfiguration>(); for (HystrixThreadPoolMetrics threadPoolMetrics: HystrixThreadPoolMetrics.getInstances()) { HystrixThreadPoolKey threadPoolKey = threadPoolMetrics.getThreadPoolKey(); threadPoolConfigPerKey.put(threadPoolKey, sampleThreadPoolConfiguration(threadPoolKey, threadPoolMetrics.getProperties())); } return threadPoolConfigPerKey; } }; private static final Func1<Long, Map<HystrixCollapserKey, HystrixCollapserConfiguration>> getAllCollapserConfig = new Func1<Long, Map<HystrixCollapserKey, HystrixCollapserConfiguration>>() { @Override public Map<HystrixCollapserKey, HystrixCollapserConfiguration> call(Long timestamp) { Map<HystrixCollapserKey, HystrixCollapserConfiguration> collapserConfigPerKey = new HashMap<HystrixCollapserKey, HystrixCollapserConfiguration>(); for (HystrixCollapserMetrics collapserMetrics: HystrixCollapserMetrics.getInstances()) { HystrixCollapserKey collapserKey = collapserMetrics.getCollapserKey(); collapserConfigPerKey.put(collapserKey, sampleCollapserConfiguration(collapserKey, collapserMetrics.getProperties())); } return collapserConfigPerKey; } }; private static final Func1<HystrixConfiguration, Map<HystrixCommandKey, HystrixCommandConfiguration>> getOnlyCommandConfig = new Func1<HystrixConfiguration, Map<HystrixCommandKey, HystrixCommandConfiguration>>() { @Override public Map<HystrixCommandKey, HystrixCommandConfiguration> call(HystrixConfiguration hystrixConfiguration) { return hystrixConfiguration.getCommandConfig(); } }; private static final Func1<HystrixConfiguration, Map<HystrixThreadPoolKey, HystrixThreadPoolConfiguration>> getOnlyThreadPoolConfig = new Func1<HystrixConfiguration, Map<HystrixThreadPoolKey, HystrixThreadPoolConfiguration>>() { @Override public Map<HystrixThreadPoolKey, HystrixThreadPoolConfiguration> call(HystrixConfiguration hystrixConfiguration) { return hystrixConfiguration.getThreadPoolConfig(); } }; private static final Func1<HystrixConfiguration, Map<HystrixCollapserKey, HystrixCollapserConfiguration>> getOnlyCollapserConfig = new Func1<HystrixConfiguration, Map<HystrixCollapserKey, HystrixCollapserConfiguration>>() { @Override public Map<HystrixCollapserKey, HystrixCollapserConfiguration> call(HystrixConfiguration hystrixConfiguration) { return hystrixConfiguration.getCollapserConfig(); } }; }
4,661
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/config/HystrixThreadPoolConfiguration.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.config; import com.netflix.hystrix.HystrixThreadPoolKey; import com.netflix.hystrix.HystrixThreadPoolProperties; public class HystrixThreadPoolConfiguration { private final HystrixThreadPoolKey threadPoolKey; private final int coreSize; private final int maximumSize; private final int actualMaximumSize; private final int maxQueueSize; private final int queueRejectionThreshold; private final int keepAliveTimeInMinutes; private final boolean allowMaximumSizeToDivergeFromCoreSize; private final int rollingCounterNumberOfBuckets; private final int rollingCounterBucketSizeInMilliseconds; private HystrixThreadPoolConfiguration(HystrixThreadPoolKey threadPoolKey, int coreSize, int maximumSize, int actualMaximumSize, int maxQueueSize, int queueRejectionThreshold, int keepAliveTimeInMinutes, boolean allowMaximumSizeToDivergeFromCoreSize, int rollingCounterNumberOfBuckets, int rollingCounterBucketSizeInMilliseconds) { this.threadPoolKey = threadPoolKey; this.allowMaximumSizeToDivergeFromCoreSize = allowMaximumSizeToDivergeFromCoreSize; this.coreSize = coreSize; this.maximumSize = maximumSize; this.actualMaximumSize = actualMaximumSize; this.maxQueueSize = maxQueueSize; this.queueRejectionThreshold = queueRejectionThreshold; this.keepAliveTimeInMinutes = keepAliveTimeInMinutes; this.rollingCounterNumberOfBuckets = rollingCounterNumberOfBuckets; this.rollingCounterBucketSizeInMilliseconds = rollingCounterBucketSizeInMilliseconds; } private HystrixThreadPoolConfiguration(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties threadPoolProperties) { this(threadPoolKey, threadPoolProperties.coreSize().get(), threadPoolProperties.maximumSize().get(), threadPoolProperties.actualMaximumSize(), threadPoolProperties.maxQueueSize().get(), threadPoolProperties.queueSizeRejectionThreshold().get(), threadPoolProperties.keepAliveTimeMinutes().get(), threadPoolProperties.getAllowMaximumSizeToDivergeFromCoreSize().get(), threadPoolProperties.metricsRollingStatisticalWindowBuckets().get(), threadPoolProperties.metricsRollingStatisticalWindowInMilliseconds().get()); } public static HystrixThreadPoolConfiguration sample(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties threadPoolProperties) { return new HystrixThreadPoolConfiguration(threadPoolKey, threadPoolProperties); } public HystrixThreadPoolKey getThreadPoolKey() { return threadPoolKey; } public int getCoreSize() { return coreSize; } /** * Simple getter that returns what the `maximumSize` property is configured as * @return */ public int getMaximumSize() { return maximumSize; } /** * Given all of the thread pool configuration, what is the actual maximumSize applied to the thread pool. * * Cases: * 1) allowMaximumSizeToDivergeFromCoreSize == false: maximumSize is set to coreSize * 2) allowMaximumSizeToDivergeFromCoreSize == true, maximumSize >= coreSize: thread pool has different core/max sizes, so return the configured max * 3) allowMaximumSizeToDivergeFromCoreSize == true, maximumSize < coreSize: threadpool incorrectly configured, use coreSize for max size * @return actually configured maximum size of threadpool */ public int getActualMaximumSize() { return this.actualMaximumSize; } public int getMaxQueueSize() { return maxQueueSize; } public int getQueueRejectionThreshold() { return queueRejectionThreshold; } public int getKeepAliveTimeInMinutes() { return keepAliveTimeInMinutes; } public boolean getAllowMaximumSizeToDivergeFromCoreSize() { return allowMaximumSizeToDivergeFromCoreSize; } public int getRollingCounterNumberOfBuckets() { return rollingCounterNumberOfBuckets; } public int getRollingCounterBucketSizeInMilliseconds() { return rollingCounterBucketSizeInMilliseconds; } }
4,662
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/config/HystrixCommandConfiguration.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.config; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.HystrixThreadPoolKey; public class HystrixCommandConfiguration { //The idea is for this object to be serialized off-box. For future-proofing, I'm adding a version so that changing config over time can be handled gracefully private static final String VERSION = "1"; private final HystrixCommandKey commandKey; private final HystrixThreadPoolKey threadPoolKey; private final HystrixCommandGroupKey groupKey; private final HystrixCommandExecutionConfig executionConfig; private final HystrixCommandCircuitBreakerConfig circuitBreakerConfig; private final HystrixCommandMetricsConfig metricsConfig; public HystrixCommandConfiguration(HystrixCommandKey commandKey, HystrixThreadPoolKey threadPoolKey, HystrixCommandGroupKey groupKey, HystrixCommandExecutionConfig executionConfig, HystrixCommandCircuitBreakerConfig circuitBreakerConfig, HystrixCommandMetricsConfig metricsConfig) { this.commandKey = commandKey; this.threadPoolKey = threadPoolKey; this.groupKey = groupKey; this.executionConfig = executionConfig; this.circuitBreakerConfig = circuitBreakerConfig; this.metricsConfig = metricsConfig; } public static HystrixCommandConfiguration sample(HystrixCommandKey commandKey, HystrixThreadPoolKey threadPoolKey, HystrixCommandGroupKey groupKey, HystrixCommandProperties commandProperties) { HystrixCommandExecutionConfig executionConfig = new HystrixCommandExecutionConfig( commandProperties.executionIsolationSemaphoreMaxConcurrentRequests().get(), commandProperties.executionIsolationStrategy().get(), commandProperties.executionIsolationThreadInterruptOnTimeout().get(), commandProperties.executionIsolationThreadPoolKeyOverride().get(), commandProperties.executionTimeoutEnabled().get(), commandProperties.executionTimeoutInMilliseconds().get(), commandProperties.fallbackEnabled().get(), commandProperties.fallbackIsolationSemaphoreMaxConcurrentRequests().get(), commandProperties.requestCacheEnabled().get(), commandProperties.requestLogEnabled().get() ); HystrixCommandCircuitBreakerConfig circuitBreakerConfig = new HystrixCommandCircuitBreakerConfig( commandProperties.circuitBreakerEnabled().get(), commandProperties.circuitBreakerErrorThresholdPercentage().get(), commandProperties.circuitBreakerForceClosed().get(), commandProperties.circuitBreakerForceOpen().get(), commandProperties.circuitBreakerRequestVolumeThreshold().get(), commandProperties.circuitBreakerSleepWindowInMilliseconds().get() ); HystrixCommandMetricsConfig metricsConfig = new HystrixCommandMetricsConfig( commandProperties.metricsHealthSnapshotIntervalInMilliseconds().get(), commandProperties.metricsRollingPercentileEnabled().get(), commandProperties.metricsRollingPercentileWindowBuckets().get(), commandProperties.metricsRollingPercentileWindowInMilliseconds().get(), commandProperties.metricsRollingStatisticalWindowBuckets().get(), commandProperties.metricsRollingStatisticalWindowInMilliseconds().get() ); return new HystrixCommandConfiguration( commandKey, threadPoolKey, groupKey, executionConfig, circuitBreakerConfig, metricsConfig); } public HystrixThreadPoolKey getThreadPoolKey() { return threadPoolKey; } public HystrixCommandGroupKey getGroupKey() { return groupKey; } public HystrixCommandExecutionConfig getExecutionConfig() { return executionConfig; } public HystrixCommandCircuitBreakerConfig getCircuitBreakerConfig() { return circuitBreakerConfig; } public HystrixCommandMetricsConfig getMetricsConfig() { return metricsConfig; } public static class HystrixCommandCircuitBreakerConfig { private final boolean enabled; private final int errorThresholdPercentage; private final boolean forceClosed; private final boolean forceOpen; private final int requestVolumeThreshold; private final int sleepWindowInMilliseconds; public HystrixCommandCircuitBreakerConfig(boolean enabled, int errorThresholdPercentage, boolean forceClosed, boolean forceOpen, int requestVolumeThreshold, int sleepWindowInMilliseconds) { this.enabled = enabled; this.errorThresholdPercentage = errorThresholdPercentage; this.forceClosed = forceClosed; this.forceOpen = forceOpen; this.requestVolumeThreshold = requestVolumeThreshold; this.sleepWindowInMilliseconds = sleepWindowInMilliseconds; } public boolean isEnabled() { return enabled; } public int getErrorThresholdPercentage() { return errorThresholdPercentage; } public boolean isForceClosed() { return forceClosed; } public boolean isForceOpen() { return forceOpen; } public int getRequestVolumeThreshold() { return requestVolumeThreshold; } public int getSleepWindowInMilliseconds() { return sleepWindowInMilliseconds; } } public static class HystrixCommandExecutionConfig { private final int semaphoreMaxConcurrentRequests; private final HystrixCommandProperties.ExecutionIsolationStrategy isolationStrategy; private final boolean threadInterruptOnTimeout; private final String threadPoolKeyOverride; private final boolean timeoutEnabled; private final int timeoutInMilliseconds; private final boolean fallbackEnabled; private final int fallbackMaxConcurrentRequest; private final boolean requestCacheEnabled; private final boolean requestLogEnabled; public HystrixCommandExecutionConfig(int semaphoreMaxConcurrentRequests, HystrixCommandProperties.ExecutionIsolationStrategy isolationStrategy, boolean threadInterruptOnTimeout, String threadPoolKeyOverride, boolean timeoutEnabled, int timeoutInMilliseconds, boolean fallbackEnabled, int fallbackMaxConcurrentRequests, boolean requestCacheEnabled, boolean requestLogEnabled) { this.semaphoreMaxConcurrentRequests = semaphoreMaxConcurrentRequests; this.isolationStrategy = isolationStrategy; this.threadInterruptOnTimeout = threadInterruptOnTimeout; this.threadPoolKeyOverride = threadPoolKeyOverride; this.timeoutEnabled = timeoutEnabled; this.timeoutInMilliseconds = timeoutInMilliseconds; this.fallbackEnabled = fallbackEnabled; this.fallbackMaxConcurrentRequest = fallbackMaxConcurrentRequests; this.requestCacheEnabled = requestCacheEnabled; this.requestLogEnabled = requestLogEnabled; } public int getSemaphoreMaxConcurrentRequests() { return semaphoreMaxConcurrentRequests; } public HystrixCommandProperties.ExecutionIsolationStrategy getIsolationStrategy() { return isolationStrategy; } public boolean isThreadInterruptOnTimeout() { return threadInterruptOnTimeout; } public String getThreadPoolKeyOverride() { return threadPoolKeyOverride; } public boolean isTimeoutEnabled() { return timeoutEnabled; } public int getTimeoutInMilliseconds() { return timeoutInMilliseconds; } public boolean isFallbackEnabled() { return fallbackEnabled; } public int getFallbackMaxConcurrentRequest() { return fallbackMaxConcurrentRequest; } public boolean isRequestCacheEnabled() { return requestCacheEnabled; } public boolean isRequestLogEnabled() { return requestLogEnabled; } } public static class HystrixCommandMetricsConfig { private final int healthIntervalInMilliseconds; private final boolean rollingPercentileEnabled; private final int rollingPercentileNumberOfBuckets; private final int rollingPercentileBucketSizeInMilliseconds; private final int rollingCounterNumberOfBuckets; private final int rollingCounterBucketSizeInMilliseconds; public HystrixCommandMetricsConfig(int healthIntervalInMilliseconds, boolean rollingPercentileEnabled, int rollingPercentileNumberOfBuckets, int rollingPercentileBucketSizeInMilliseconds, int rollingCounterNumberOfBuckets, int rollingCounterBucketSizeInMilliseconds) { this.healthIntervalInMilliseconds = healthIntervalInMilliseconds; this.rollingPercentileEnabled = rollingPercentileEnabled; this.rollingPercentileNumberOfBuckets = rollingPercentileNumberOfBuckets; this.rollingPercentileBucketSizeInMilliseconds = rollingPercentileBucketSizeInMilliseconds; this.rollingCounterNumberOfBuckets = rollingCounterNumberOfBuckets; this.rollingCounterBucketSizeInMilliseconds = rollingCounterBucketSizeInMilliseconds; } public int getHealthIntervalInMilliseconds() { return healthIntervalInMilliseconds; } public boolean isRollingPercentileEnabled() { return rollingPercentileEnabled; } public int getRollingPercentileNumberOfBuckets() { return rollingPercentileNumberOfBuckets; } public int getRollingPercentileBucketSizeInMilliseconds() { return rollingPercentileBucketSizeInMilliseconds; } public int getRollingCounterNumberOfBuckets() { return rollingCounterNumberOfBuckets; } public int getRollingCounterBucketSizeInMilliseconds() { return rollingCounterBucketSizeInMilliseconds; } } }
4,663
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/config/HystrixConfiguration.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.config; import com.netflix.hystrix.HystrixCollapserKey; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixThreadPoolKey; import java.util.Map; public class HystrixConfiguration { private final Map<HystrixCommandKey, HystrixCommandConfiguration> commandConfig; private final Map<HystrixThreadPoolKey, HystrixThreadPoolConfiguration> threadPoolConfig; private final Map<HystrixCollapserKey, HystrixCollapserConfiguration> collapserConfig; public HystrixConfiguration(Map<HystrixCommandKey, HystrixCommandConfiguration> commandConfig, Map<HystrixThreadPoolKey, HystrixThreadPoolConfiguration> threadPoolConfig, Map<HystrixCollapserKey, HystrixCollapserConfiguration> collapserConfig) { this.commandConfig = commandConfig; this.threadPoolConfig = threadPoolConfig; this.collapserConfig = collapserConfig; } public static HystrixConfiguration from(Map<HystrixCommandKey, HystrixCommandConfiguration> commandConfig, Map<HystrixThreadPoolKey, HystrixThreadPoolConfiguration> threadPoolConfig, Map<HystrixCollapserKey, HystrixCollapserConfiguration> collapserConfig) { return new HystrixConfiguration(commandConfig, threadPoolConfig, collapserConfig); } public Map<HystrixCommandKey, HystrixCommandConfiguration> getCommandConfig() { return commandConfig; } public Map<HystrixThreadPoolKey, HystrixThreadPoolConfiguration> getThreadPoolConfig() { return threadPoolConfig; } public Map<HystrixCollapserKey, HystrixCollapserConfiguration> getCollapserConfig() { return collapserConfig; } }
4,664
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/config/HystrixCollapserConfiguration.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.config; import com.netflix.hystrix.HystrixCollapserKey; import com.netflix.hystrix.HystrixCollapserProperties; public class HystrixCollapserConfiguration { private final HystrixCollapserKey collapserKey; private final int maxRequestsInBatch; private final int timerDelayInMilliseconds; private final boolean requestCacheEnabled; private final CollapserMetricsConfig collapserMetricsConfig; public HystrixCollapserConfiguration(HystrixCollapserKey collapserKey, int maxRequestsInBatch, int timerDelayInMilliseconds, boolean requestCacheEnabled, CollapserMetricsConfig collapserMetricsConfig) { this.collapserKey = collapserKey; this.maxRequestsInBatch = maxRequestsInBatch; this.timerDelayInMilliseconds = timerDelayInMilliseconds; this.requestCacheEnabled = requestCacheEnabled; this.collapserMetricsConfig = collapserMetricsConfig; } public static HystrixCollapserConfiguration sample(HystrixCollapserKey collapserKey, HystrixCollapserProperties collapserProperties) { CollapserMetricsConfig collapserMetricsConfig = new CollapserMetricsConfig( collapserProperties.metricsRollingPercentileWindowBuckets().get(), collapserProperties.metricsRollingPercentileWindowInMilliseconds().get(), collapserProperties.metricsRollingPercentileEnabled().get(), collapserProperties.metricsRollingStatisticalWindowBuckets().get(), collapserProperties.metricsRollingStatisticalWindowInMilliseconds().get() ); return new HystrixCollapserConfiguration( collapserKey, collapserProperties.maxRequestsInBatch().get(), collapserProperties.timerDelayInMilliseconds().get(), collapserProperties.requestCacheEnabled().get(), collapserMetricsConfig ); } public HystrixCollapserKey getCollapserKey() { return collapserKey; } public int getMaxRequestsInBatch() { return maxRequestsInBatch; } public int getTimerDelayInMilliseconds() { return timerDelayInMilliseconds; } public boolean isRequestCacheEnabled() { return requestCacheEnabled; } public CollapserMetricsConfig getCollapserMetricsConfig() { return collapserMetricsConfig; } public static class CollapserMetricsConfig { private final int rollingPercentileNumberOfBuckets; private final int rollingPercentileBucketSizeInMilliseconds; private final boolean rollingPercentileEnabled; private final int rollingCounterNumberOfBuckets; private final int rollingCounterBucketSizeInMilliseconds; public CollapserMetricsConfig(int rollingPercentileNumberOfBuckets, int rollingPercentileBucketSizeInMilliseconds, boolean rollingPercentileEnabled, int rollingCounterNumberOfBuckets, int rollingCounterBucketSizeInMilliseconds) { this.rollingPercentileNumberOfBuckets = rollingCounterNumberOfBuckets; this.rollingPercentileBucketSizeInMilliseconds = rollingPercentileBucketSizeInMilliseconds; this.rollingPercentileEnabled = rollingPercentileEnabled; this.rollingCounterNumberOfBuckets = rollingCounterNumberOfBuckets; this.rollingCounterBucketSizeInMilliseconds = rollingCounterBucketSizeInMilliseconds; } public int getRollingPercentileNumberOfBuckets() { return rollingPercentileNumberOfBuckets; } public int getRollingPercentileBucketSizeInMilliseconds() { return rollingPercentileBucketSizeInMilliseconds; } public boolean isRollingPercentileEnabled() { return rollingPercentileEnabled; } public int getRollingCounterNumberOfBuckets() { return rollingCounterNumberOfBuckets; } public int getRollingCounterBucketSizeInMilliseconds() { return rollingCounterBucketSizeInMilliseconds; } } }
4,665
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/collapser/RequestCollapserFactory.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 java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.hystrix.HystrixCollapserKey; import com.netflix.hystrix.HystrixCollapserProperties; import com.netflix.hystrix.strategy.HystrixPlugins; import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableHolder; import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableLifecycle; import com.netflix.hystrix.strategy.properties.HystrixPropertiesFactory; import com.netflix.hystrix.util.HystrixTimer; /** * Factory for retrieving the correct instance of a RequestCollapser. * * @param <BatchReturnType> * @param <ResponseType> * @param <RequestArgumentType> */ public class RequestCollapserFactory<BatchReturnType, ResponseType, RequestArgumentType> { private static final Logger logger = LoggerFactory.getLogger(RequestCollapserFactory.class); private final CollapserTimer timer; private final HystrixCollapserKey collapserKey; private final HystrixCollapserProperties properties; private final HystrixConcurrencyStrategy concurrencyStrategy; private final Scope scope; public static interface Scope { String name(); } // internally expected scopes, dealing with the not-so-fun inheritance issues of enum when shared between classes private static enum Scopes implements Scope { REQUEST, GLOBAL } public RequestCollapserFactory(HystrixCollapserKey collapserKey, Scope scope, CollapserTimer timer, HystrixCollapserProperties.Setter propertiesBuilder) { this(collapserKey, scope, timer, HystrixPropertiesFactory.getCollapserProperties(collapserKey, propertiesBuilder)); } public RequestCollapserFactory(HystrixCollapserKey collapserKey, Scope scope, CollapserTimer timer, HystrixCollapserProperties properties) { /* strategy: ConcurrencyStrategy */ this.concurrencyStrategy = HystrixPlugins.getInstance().getConcurrencyStrategy(); this.timer = timer; this.scope = scope; this.collapserKey = collapserKey; this.properties = properties; } public HystrixCollapserKey getCollapserKey() { return collapserKey; } public Scope getScope() { return scope; } public HystrixCollapserProperties getProperties() { return properties; } public RequestCollapser<BatchReturnType, ResponseType, RequestArgumentType> getRequestCollapser(HystrixCollapserBridge<BatchReturnType, ResponseType, RequestArgumentType> commandCollapser) { if (Scopes.REQUEST == Scopes.valueOf(getScope().name())) { return getCollapserForUserRequest(commandCollapser); } else if (Scopes.GLOBAL == Scopes.valueOf(getScope().name())) { return getCollapserForGlobalScope(commandCollapser); } else { logger.warn("Invalid Scope: {} Defaulting to REQUEST scope.", getScope()); return getCollapserForUserRequest(commandCollapser); } } /** * Static global cache of RequestCollapsers for Scope.GLOBAL */ // String is CollapserKey.name() (we can't use CollapserKey directly as we can't guarantee it implements hashcode/equals correctly) private static ConcurrentHashMap<String, RequestCollapser<?, ?, ?>> globalScopedCollapsers = new ConcurrentHashMap<String, RequestCollapser<?, ?, ?>>(); @SuppressWarnings("unchecked") private RequestCollapser<BatchReturnType, ResponseType, RequestArgumentType> getCollapserForGlobalScope(HystrixCollapserBridge<BatchReturnType, ResponseType, RequestArgumentType> commandCollapser) { RequestCollapser<?, ?, ?> collapser = globalScopedCollapsers.get(collapserKey.name()); if (collapser != null) { return (RequestCollapser<BatchReturnType, ResponseType, RequestArgumentType>) collapser; } // create new collapser using 'this' first instance as the one that will get cached for future executions ('this' is stateless so we can do that) RequestCollapser<BatchReturnType, ResponseType, RequestArgumentType> newCollapser = new RequestCollapser<BatchReturnType, ResponseType, RequestArgumentType>(commandCollapser, properties, timer, concurrencyStrategy); RequestCollapser<?, ?, ?> existing = globalScopedCollapsers.putIfAbsent(collapserKey.name(), newCollapser); if (existing == null) { // we won return newCollapser; } else { // we lost ... another thread beat us // shutdown the one we created but didn't get stored newCollapser.shutdown(); // return the existing one return (RequestCollapser<BatchReturnType, ResponseType, RequestArgumentType>) existing; } } /** * Static global cache of RequestVariables with RequestCollapsers for Scope.REQUEST */ // String is HystrixCollapserKey.name() (we can't use HystrixCollapserKey directly as we can't guarantee it implements hashcode/equals correctly) private static ConcurrentHashMap<String, HystrixRequestVariableHolder<RequestCollapser<?, ?, ?>>> requestScopedCollapsers = new ConcurrentHashMap<String, HystrixRequestVariableHolder<RequestCollapser<?, ?, ?>>>(); /* we are casting because the Map needs to be <?, ?> but we know it is <ReturnType, RequestArgumentType> for this thread */ @SuppressWarnings("unchecked") private RequestCollapser<BatchReturnType, ResponseType, RequestArgumentType> getCollapserForUserRequest(HystrixCollapserBridge<BatchReturnType, ResponseType, RequestArgumentType> commandCollapser) { return (RequestCollapser<BatchReturnType, ResponseType, RequestArgumentType>) getRequestVariableForCommand(commandCollapser).get(concurrencyStrategy); } /** * Lookup (or create and store) the RequestVariable for a given HystrixCollapserKey. * * @param commandCollapser collapser to retrieve {@link HystrixRequestVariableHolder} for * @return HystrixRequestVariableHolder */ @SuppressWarnings("unchecked") private HystrixRequestVariableHolder<RequestCollapser<?, ?, ?>> getRequestVariableForCommand(final HystrixCollapserBridge<BatchReturnType, ResponseType, RequestArgumentType> commandCollapser) { HystrixRequestVariableHolder<RequestCollapser<?, ?, ?>> requestVariable = requestScopedCollapsers.get(commandCollapser.getCollapserKey().name()); if (requestVariable == null) { // create new collapser using 'this' first instance as the one that will get cached for future executions ('this' is stateless so we can do that) @SuppressWarnings({ "rawtypes" }) HystrixRequestVariableHolder newCollapser = new RequestCollapserRequestVariable(commandCollapser, properties, timer, concurrencyStrategy); HystrixRequestVariableHolder<RequestCollapser<?, ?, ?>> existing = requestScopedCollapsers.putIfAbsent(commandCollapser.getCollapserKey().name(), newCollapser); if (existing == null) { // this thread won, so return the one we just created requestVariable = newCollapser; } else { // another thread beat us (this should only happen when we have concurrency on the FIRST request for the life of the app for this HystrixCollapser class) requestVariable = existing; /* * This *should* be okay to discard the created object without cleanup as the RequestVariable implementation * should properly do lazy-initialization and only call initialValue() the first time get() is called. * * If it does not correctly follow this contract then there is a chance of a memory leak here. */ } } return requestVariable; } /** * Clears all state. If new requests come in instances will be recreated and metrics started from scratch. */ public static void reset() { globalScopedCollapsers.clear(); requestScopedCollapsers.clear(); HystrixTimer.reset(); } /** * Used for testing */ public static void resetRequest() { requestScopedCollapsers.clear(); } /** * Used for testing */ public static HystrixRequestVariableHolder<RequestCollapser<?, ?, ?>> getRequestVariable(String key) { return requestScopedCollapsers.get(key); } /** * Request scoped RequestCollapser that lives inside a RequestVariable. * <p> * This depends on the RequestVariable getting reset before each user request in NFFilter to ensure the RequestCollapser is new for each user request. */ private final class RequestCollapserRequestVariable extends HystrixRequestVariableHolder<RequestCollapser<BatchReturnType, ResponseType, RequestArgumentType>> { /** * NOTE: There is only 1 instance of this for the life of the app per HystrixCollapser instance. The state changes on each request via the initialValue()/get() methods. * <p> * Thus, do NOT put any instance variables in this class that are not static for all threads. */ private RequestCollapserRequestVariable(final HystrixCollapserBridge<BatchReturnType, ResponseType, RequestArgumentType> commandCollapser, final HystrixCollapserProperties properties, final CollapserTimer timer, final HystrixConcurrencyStrategy concurrencyStrategy) { super(new HystrixRequestVariableLifecycle<RequestCollapser<BatchReturnType, ResponseType, RequestArgumentType>>() { @Override public RequestCollapser<BatchReturnType, ResponseType, RequestArgumentType> initialValue() { // this gets calls once per request per HystrixCollapser instance return new RequestCollapser<BatchReturnType, ResponseType, RequestArgumentType>(commandCollapser, properties, timer, concurrencyStrategy); } @Override public void shutdown(RequestCollapser<BatchReturnType, ResponseType, RequestArgumentType> currentCollapser) { // shut down the RequestCollapser (the internal timer tasks) if (currentCollapser != null) { currentCollapser.shutdown(); } } }); } } }
4,666
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/collapser/HystrixCollapserBridge.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 java.util.Collection; import rx.Observable; import com.netflix.hystrix.HystrixCollapser.CollapsedRequest; import com.netflix.hystrix.HystrixCollapserKey; /** * Bridge between HystrixCollapser and RequestCollapser to expose 'protected' and 'private' functionality across packages. * * @param <BatchReturnType> * @param <ResponseType> * @param <RequestArgumentType> */ public interface HystrixCollapserBridge<BatchReturnType, ResponseType, RequestArgumentType> { Collection<Collection<CollapsedRequest<ResponseType, RequestArgumentType>>> shardRequests(Collection<CollapsedRequest<ResponseType, RequestArgumentType>> requests); Observable<BatchReturnType> createObservableCommand(Collection<CollapsedRequest<ResponseType, RequestArgumentType>> requests); Observable<Void> mapResponseToRequests(Observable<BatchReturnType> batchResponse, Collection<CollapsedRequest<ResponseType, RequestArgumentType>> requests); HystrixCollapserKey getCollapserKey(); }
4,667
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/collapser/RequestCollapser.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 java.lang.ref.Reference; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import com.netflix.hystrix.HystrixCollapserProperties; import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; import com.netflix.hystrix.strategy.concurrency.HystrixContextCallable; import com.netflix.hystrix.util.HystrixTimer.TimerListener; /** * Requests are submitted to this and batches executed based on size or time. Scoped to either a request or the global application. * <p> * Instances of this are retrieved from the RequestCollapserFactory. * * Must be thread-safe since it exists within a RequestVariable which is request-scoped and can be accessed from multiple threads. * * @ThreadSafe */ public class RequestCollapser<BatchReturnType, ResponseType, RequestArgumentType> { static final Logger logger = LoggerFactory.getLogger(RequestCollapser.class); static final Object NULL_SENTINEL = new Object(); private final HystrixCollapserBridge<BatchReturnType, ResponseType, RequestArgumentType> commandCollapser; // batch can be null once shutdown private final AtomicReference<RequestBatch<BatchReturnType, ResponseType, RequestArgumentType>> batch = new AtomicReference<RequestBatch<BatchReturnType, ResponseType, RequestArgumentType>>(); private final AtomicReference<Reference<TimerListener>> timerListenerReference = new AtomicReference<Reference<TimerListener>>(); private final AtomicBoolean timerListenerRegistered = new AtomicBoolean(); private final CollapserTimer timer; private final HystrixCollapserProperties properties; private final HystrixConcurrencyStrategy concurrencyStrategy; /** * @param commandCollapser collapser which will create the batched requests and demultiplex the results * @param properties collapser properties that define how collapsing occurs * @param timer {@link CollapserTimer} which performs the collapsing * @param concurrencyStrategy strategy for managing the {@link Callable}s generated by {@link RequestCollapser} */ RequestCollapser(HystrixCollapserBridge<BatchReturnType, ResponseType, RequestArgumentType> commandCollapser, HystrixCollapserProperties properties, CollapserTimer timer, HystrixConcurrencyStrategy concurrencyStrategy) { this.commandCollapser = commandCollapser; // the command with implementation of abstract methods we need this.concurrencyStrategy = concurrencyStrategy; this.properties = properties; this.timer = timer; batch.set(new RequestBatch<BatchReturnType, ResponseType, RequestArgumentType>(properties, commandCollapser, properties.maxRequestsInBatch().get())); } /** * Submit a request to a batch. If the batch maxSize is hit trigger the batch immediately. * * @param arg argument to a {@link RequestCollapser} * @return Observable<ResponseType> * @throws IllegalStateException * if submitting after shutdown */ public Observable<ResponseType> submitRequest(final RequestArgumentType arg) { /* * We only want the timer ticking if there are actually things to do so we register it the first time something is added. */ if (!timerListenerRegistered.get() && timerListenerRegistered.compareAndSet(false, true)) { /* schedule the collapsing task to be executed every x milliseconds (x defined inside CollapsedTask) */ timerListenerReference.set(timer.addListener(new CollapsedTask())); } // loop until succeed (compare-and-set spin-loop) while (true) { final RequestBatch<BatchReturnType, ResponseType, RequestArgumentType> b = batch.get(); if (b == null) { return Observable.error(new IllegalStateException("Submitting requests after collapser is shutdown")); } final Observable<ResponseType> response; if (arg != null) { response = b.offer(arg); } else { response = b.offer( (RequestArgumentType) NULL_SENTINEL); } // it will always get an Observable unless we hit the max batch size if (response != null) { return response; } else { // this batch can't accept requests so create a new one and set it if another thread doesn't beat us createNewBatchAndExecutePreviousIfNeeded(b); } } } private void createNewBatchAndExecutePreviousIfNeeded(RequestBatch<BatchReturnType, ResponseType, RequestArgumentType> previousBatch) { if (previousBatch == null) { throw new IllegalStateException("Trying to start null batch which means it was shutdown already."); } if (batch.compareAndSet(previousBatch, new RequestBatch<BatchReturnType, ResponseType, RequestArgumentType>(properties, commandCollapser, properties.maxRequestsInBatch().get()))) { // this thread won so trigger the previous batch previousBatch.executeBatchIfNotAlreadyStarted(); } } /** * Called from RequestVariable.shutdown() to unschedule the task. */ public void shutdown() { RequestBatch<BatchReturnType, ResponseType, RequestArgumentType> currentBatch = batch.getAndSet(null); if (currentBatch != null) { currentBatch.shutdown(); } if (timerListenerReference.get() != null) { // if the timer was started we'll clear it so it stops ticking timerListenerReference.get().clear(); } } /** * Executed on each Timer interval execute the current batch if it has requests in it. */ private class CollapsedTask implements TimerListener { final Callable<Void> callableWithContextOfParent; CollapsedTask() { // this gets executed from the context of a HystrixCommand parent thread (such as a Tomcat thread) // so we create the callable now where we can capture the thread context callableWithContextOfParent = new HystrixContextCallable<Void>(concurrencyStrategy, new Callable<Void>() { // the wrapCallable call allows a strategy to capture thread-context if desired @Override public Void call() throws Exception { try { // we fetch current so that when multiple threads race // we can do compareAndSet with the expected/new to ensure only one happens RequestBatch<BatchReturnType, ResponseType, RequestArgumentType> currentBatch = batch.get(); // 1) it can be null if it got shutdown // 2) we don't execute this batch if it has no requests and let it wait until next tick to be executed if (currentBatch != null && currentBatch.getSize() > 0) { // do execution within context of wrapped Callable createNewBatchAndExecutePreviousIfNeeded(currentBatch); } } catch (Throwable t) { logger.error("Error occurred trying to execute the batch.", t); t.printStackTrace(); // ignore error so we don't kill the Timer mainLoop and prevent further items from being scheduled } return null; } }); } @Override public void tick() { try { callableWithContextOfParent.call(); } catch (Exception e) { logger.error("Error occurred trying to execute callable inside CollapsedTask from Timer.", e); e.printStackTrace(); } } @Override public int getIntervalTimeInMilliseconds() { return properties.timerDelayInMilliseconds().get(); } } }
4,668
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/collapser/RequestBatch.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 java.util.Collection; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.functions.Action0; import rx.functions.Action1; import com.netflix.hystrix.HystrixCollapser.CollapsedRequest; import com.netflix.hystrix.HystrixCollapserProperties; /** * A batch of requests collapsed together by a RequestCollapser instance. When full or time has expired it will execute and stop accepting further submissions. * * @param <BatchReturnType> * @param <ResponseType> * @param <RequestArgumentType> */ public class RequestBatch<BatchReturnType, ResponseType, RequestArgumentType> { private static final Logger logger = LoggerFactory.getLogger(RequestBatch.class); private final HystrixCollapserBridge<BatchReturnType, ResponseType, RequestArgumentType> commandCollapser; private final int maxBatchSize; private final AtomicBoolean batchStarted = new AtomicBoolean(); private final ConcurrentMap<RequestArgumentType, CollapsedRequest<ResponseType, RequestArgumentType>> argumentMap = new ConcurrentHashMap<RequestArgumentType, CollapsedRequest<ResponseType, RequestArgumentType>>(); private final HystrixCollapserProperties properties; private ReentrantReadWriteLock batchLock = new ReentrantReadWriteLock(); public RequestBatch(HystrixCollapserProperties properties, HystrixCollapserBridge<BatchReturnType, ResponseType, RequestArgumentType> commandCollapser, int maxBatchSize) { this.properties = properties; this.commandCollapser = commandCollapser; this.maxBatchSize = maxBatchSize; } /** * @return Observable if offer accepted, null if batch is full, already started or completed */ public Observable<ResponseType> offer(RequestArgumentType arg) { /* short-cut - if the batch is started we reject the offer */ if (batchStarted.get()) { return null; } /* * The 'read' just means non-exclusive even though we are writing. */ if (batchLock.readLock().tryLock()) { try { /* double-check now that we have the lock - if the batch is started we reject the offer */ if (batchStarted.get()) { return null; } if (argumentMap.size() >= maxBatchSize) { return null; } else { CollapsedRequestSubject<ResponseType, RequestArgumentType> collapsedRequest = new CollapsedRequestSubject<ResponseType, RequestArgumentType>(arg, this); final CollapsedRequestSubject<ResponseType, RequestArgumentType> existing = (CollapsedRequestSubject<ResponseType, RequestArgumentType>) argumentMap.putIfAbsent(arg, collapsedRequest); /** * If the argument already exists in the batch, then there are 2 options: * A) If request caching is ON (the default): only keep 1 argument in the batch and let all responses * be hooked up to that argument * B) If request caching is OFF: return an error to all duplicate argument requests * * This maintains the invariant that each batch has no duplicate arguments. This prevents the impossible * logic (in a user-provided mapResponseToRequests for HystrixCollapser and the internals of HystrixObservableCollapser) * of trying to figure out which argument of a set of duplicates should get attached to a response. * * See https://github.com/Netflix/Hystrix/pull/1176 for further discussion. */ if (existing != null) { boolean requestCachingEnabled = properties.requestCacheEnabled().get(); if (requestCachingEnabled) { return existing.toObservable(); } else { return Observable.error(new IllegalArgumentException("Duplicate argument in collapser batch : [" + arg + "] This is not supported. Please turn request-caching on for HystrixCollapser:" + commandCollapser.getCollapserKey().name() + " or prevent duplicates from making it into the batch!")); } } else { return collapsedRequest.toObservable(); } } } finally { batchLock.readLock().unlock(); } } else { return null; } } /** * Best-effort attempt to remove an argument from a batch. This may get invoked when a cancellation occurs somewhere downstream. * This method finds the argument in the batch, and removes it. * * @param arg argument to remove from batch */ /* package-private */ void remove(RequestArgumentType arg) { if (batchStarted.get()) { //nothing we can do return; } if (batchLock.readLock().tryLock()) { try { /* double-check now that we have the lock - if the batch is started, deleting is useless */ if (batchStarted.get()) { return; } argumentMap.remove(arg); } finally { batchLock.readLock().unlock(); } } } /** * Collapsed requests are triggered for batch execution and the array of arguments is passed in. * <p> * IMPORTANT IMPLEMENTATION DETAILS => The expected contract (responsibilities) of this method implementation is: * <p> * <ul> * <li>Do NOT block => Do the work on a separate worker thread. Do not perform inline otherwise it will block other requests.</li> * <li>Set ALL CollapsedRequest response values => Set the response values T on each CollapsedRequest<T, R>, even if the response is NULL otherwise the user thread waiting on the response will * think a response was never received and will either block indefinitely or will timeout while waiting.</li> * </ul> * */ public void executeBatchIfNotAlreadyStarted() { /* * - check that we only execute once since there's multiple paths to do so (timer, waiting thread or max batch size hit) * - close the gate so 'offer' can no longer be invoked and we turn those threads away so they create a new batch */ if (batchStarted.compareAndSet(false, true)) { /* wait for 'offer'/'remove' threads to finish before executing the batch so 'requests' is complete */ batchLock.writeLock().lock(); try { // shard batches Collection<Collection<CollapsedRequest<ResponseType, RequestArgumentType>>> shards = commandCollapser.shardRequests(argumentMap.values()); // for each shard execute its requests for (final Collection<CollapsedRequest<ResponseType, RequestArgumentType>> shardRequests : shards) { try { // create a new command to handle this batch of requests Observable<BatchReturnType> o = commandCollapser.createObservableCommand(shardRequests); commandCollapser.mapResponseToRequests(o, shardRequests).doOnError(new Action1<Throwable>() { /** * This handles failed completions */ @Override public void call(Throwable e) { // handle Throwable in case anything is thrown so we don't block Observers waiting for onError/onCompleted Exception ee; if (e instanceof Exception) { ee = (Exception) e; } else { ee = new RuntimeException("Throwable caught while executing batch and mapping responses.", e); } logger.debug("Exception mapping responses to requests.", e); // if a failure occurs we want to pass that exception to all of the Futures that we've returned for (CollapsedRequest<ResponseType, RequestArgumentType> request : argumentMap.values()) { try { ((CollapsedRequestSubject<ResponseType, RequestArgumentType>) request).setExceptionIfResponseNotReceived(ee); } catch (IllegalStateException e2) { // if we have partial responses set in mapResponseToRequests // then we may get IllegalStateException as we loop over them // so we'll log but continue to the rest logger.error("Partial success of 'mapResponseToRequests' resulted in IllegalStateException while setting Exception. Continuing ... ", e2); } } } }).doOnCompleted(new Action0() { /** * This handles successful completions */ @Override public void call() { // check that all requests had setResponse or setException invoked in case 'mapResponseToRequests' was implemented poorly Exception e = null; for (CollapsedRequest<ResponseType, RequestArgumentType> request : shardRequests) { try { e = ((CollapsedRequestSubject<ResponseType, RequestArgumentType>) request).setExceptionIfResponseNotReceived(e,"No response set by " + commandCollapser.getCollapserKey().name() + " 'mapResponseToRequests' implementation."); } catch (IllegalStateException e2) { logger.debug("Partial success of 'mapResponseToRequests' resulted in IllegalStateException while setting 'No response set' Exception. Continuing ... ", e2); } } } }).subscribe(); } catch (Exception e) { logger.error("Exception while creating and queueing command with batch.", e); // if a failure occurs we want to pass that exception to all of the Futures that we've returned for (CollapsedRequest<ResponseType, RequestArgumentType> request : shardRequests) { try { request.setException(e); } catch (IllegalStateException e2) { logger.debug("Failed trying to setException on CollapsedRequest", e2); } } } } } catch (Exception e) { logger.error("Exception while sharding requests.", e); // same error handling as we do around the shards, but this is a wider net in case the shardRequest method fails for (CollapsedRequest<ResponseType, RequestArgumentType> request : argumentMap.values()) { try { request.setException(e); } catch (IllegalStateException e2) { logger.debug("Failed trying to setException on CollapsedRequest", e2); } } } finally { batchLock.writeLock().unlock(); } } } public void shutdown() { // take the 'batchStarted' state so offers and execution will not be triggered elsewhere if (batchStarted.compareAndSet(false, true)) { // get the write lock so offers are synced with this (we don't really need to unlock as this is a one-shot deal to shutdown) batchLock.writeLock().lock(); try { // if we win the 'start' and once we have the lock we can now shut it down otherwise another thread will finish executing this batch if (argumentMap.size() > 0) { logger.warn("Requests still exist in queue but will not be executed due to RequestCollapser shutdown: " + argumentMap.size(), new IllegalStateException()); /* * In the event that there is a concurrency bug or thread scheduling prevents the timer from ticking we need to handle this so the Future.get() calls do not block. * * I haven't been able to reproduce this use case on-demand but when stressing a machine saw this occur briefly right after the JVM paused (logs stopped scrolling). * * This safety-net just prevents the CollapsedRequestFutureImpl.get() from waiting on the CountDownLatch until its max timeout. */ for (CollapsedRequest<ResponseType, RequestArgumentType> request : argumentMap.values()) { try { ((CollapsedRequestSubject<ResponseType, RequestArgumentType>) request).setExceptionIfResponseNotReceived(new IllegalStateException("Requests not executed before shutdown.")); } catch (Exception e) { logger.debug("Failed to setException on CollapsedRequestFutureImpl instances.", e); } /** * https://github.com/Netflix/Hystrix/issues/78 Include more info when collapsed requests remain in queue */ logger.warn("Request still in queue but not be executed due to RequestCollapser shutdown. Argument => " + request.getArgument() + " Request Object => " + request, new IllegalStateException()); } } } finally { batchLock.writeLock().unlock(); } } } public int getSize() { return argumentMap.size(); } }
4,669
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/collapser/RealCollapserTimer.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 java.lang.ref.Reference; import com.netflix.hystrix.util.HystrixTimer; import com.netflix.hystrix.util.HystrixTimer.TimerListener; /** * Actual CollapserTimer implementation for triggering batch execution that uses HystrixTimer. */ public class RealCollapserTimer implements CollapserTimer { /* single global timer that all collapsers will schedule their tasks on */ private final static HystrixTimer timer = HystrixTimer.getInstance(); @Override public Reference<TimerListener> addListener(TimerListener collapseTask) { return timer.addTimerListener(collapseTask); } }
4,670
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/collapser/CollapsedRequestSubject.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 com.netflix.hystrix.HystrixCollapser.CollapsedRequest; import rx.Observable; import rx.functions.Action0; import rx.subjects.ReplaySubject; import java.util.concurrent.atomic.AtomicBoolean; /** * The Observable that represents a collapsed request sent back to a user. It gets used by Collapser implementations * when receiving a batch response and emitting values/errors to collapsers. * * There are 4 methods that Collapser implementations may use: * * 1) {@link #setResponse(T)}: return a single-valued response. equivalent to OnNext(T), OnCompleted() * 2) {@link #emitResponse(T)}: emit a single value. equivalent to OnNext(T) * 3) {@link #setException(Exception)}: return an exception. equivalent to OnError(Exception) * 4) {@link #setComplete()}: mark that no more values will be emitted. Should be used in conjunction with {@link #emitResponse(T)}. equivalent to OnCompleted() * * <p> * This is an internal implementation of CollapsedRequest<T, R> functionality. Instead of directly extending {@link rx.Observable}, * it provides a {@link #toObservable()} method * <p> * * @param <T> * * @param <R> */ /* package */class CollapsedRequestSubject<T, R> implements CollapsedRequest<T, R> { private final R argument; private AtomicBoolean valueSet = new AtomicBoolean(false); private final ReplaySubject<T> subject = ReplaySubject.create(); private final Observable<T> subjectWithAccounting; private volatile int outstandingSubscriptions = 0; public CollapsedRequestSubject(final R arg, final RequestBatch<?, T, R> containingBatch) { if (arg == RequestCollapser.NULL_SENTINEL) { this.argument = null; } else { this.argument = arg; } this.subjectWithAccounting = subject .doOnSubscribe(new Action0() { @Override public void call() { outstandingSubscriptions++; } }) .doOnUnsubscribe(new Action0() { @Override public void call() { outstandingSubscriptions--; if (outstandingSubscriptions == 0) { containingBatch.remove(arg); } } }); } public CollapsedRequestSubject(final R arg) { this.subjectWithAccounting = subject; this.argument = arg; } /** * The request argument. * * @return request argument */ @Override public R getArgument() { return argument; } /** * When set any client thread blocking on get() will immediately be unblocked and receive the single-valued response. * * @throws IllegalStateException * if called more than once or after setException. * @param response response to give to initial command */ @Override public void setResponse(T response) { if (!isTerminated()) { subject.onNext(response); valueSet.set(true); subject.onCompleted(); } else { throw new IllegalStateException("Response has already terminated so response can not be set : " + response); } } /** * Emit a response that should be OnNexted to an Observer * @param response response to emit to initial command */ @Override public void emitResponse(T response) { if (!isTerminated()) { subject.onNext(response); valueSet.set(true); } else { throw new IllegalStateException("Response has already terminated so response can not be set : " + response); } } @Override public void setComplete() { if (!isTerminated()) { subject.onCompleted(); } } /** * Set an exception if a response is not yet received otherwise skip it * * @param e synthetic error to set on initial command when no actual response is available */ public void setExceptionIfResponseNotReceived(Exception e) { if (!valueSet.get() && !isTerminated()) { subject.onError(e); } } /** * Set an ISE if a response is not yet received otherwise skip it * * @param e A pre-generated exception. If this is null an ISE will be created and returned * @param exceptionMessage The message for the ISE */ public Exception setExceptionIfResponseNotReceived(Exception e, String exceptionMessage) { Exception exception = e; if (!valueSet.get() && !isTerminated()) { if (e == null) { exception = new IllegalStateException(exceptionMessage); } setExceptionIfResponseNotReceived(exception); } // return any exception that was generated return exception; } /** * When set any client thread blocking on get() will immediately be unblocked and receive the exception. * * @throws IllegalStateException * if called more than once or after setResponse. * @param e received exception that gets set on the initial command */ @Override public void setException(Exception e) { if (!isTerminated()) { subject.onError(e); } else { throw new IllegalStateException("Response has already terminated so exception can not be set", e); } } private boolean isTerminated() { return (subject.hasCompleted() || subject.hasThrowable()); } public Observable<T> toObservable() { return subjectWithAccounting; } }
4,671
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/collapser/CollapserTimer.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 java.lang.ref.Reference; import com.netflix.hystrix.util.HystrixTimer.TimerListener; /** * Timer used for trigger batch execution. */ public interface CollapserTimer { public Reference<TimerListener> addListener(TimerListener collapseTask); }
4,672
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/CachedValuesHistogram.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.metric; import org.HdrHistogram.Histogram; public class CachedValuesHistogram { private final static int NUMBER_SIGNIFICANT_DIGITS = 3; private final int mean; private final int p0; private final int p5; private final int p10; private final int p15; private final int p20; private final int p25; private final int p30; private final int p35; private final int p40; private final int p45; private final int p50; private final int p55; private final int p60; private final int p65; private final int p70; private final int p75; private final int p80; private final int p85; private final int p90; private final int p95; private final int p99; private final int p99_5; private final int p99_9; private final int p99_95; private final int p99_99; private final int p100; private final long totalCount; public static CachedValuesHistogram backedBy(Histogram underlying) { return new CachedValuesHistogram(underlying); } private CachedValuesHistogram(Histogram underlying) { /** * Single thread calculates a variety of commonly-accessed quantities. * This way, all threads can access the cached values without synchronization * Synchronization is only required for values that are not cached */ mean = (int) underlying.getMean(); p0 = (int) underlying.getValueAtPercentile(0); p5 = (int) underlying.getValueAtPercentile(5); p10 = (int) underlying.getValueAtPercentile(10); p15 = (int) underlying.getValueAtPercentile(15); p20 = (int) underlying.getValueAtPercentile(20); p25 = (int) underlying.getValueAtPercentile(25); p30 = (int) underlying.getValueAtPercentile(30); p35 = (int) underlying.getValueAtPercentile(35); p40 = (int) underlying.getValueAtPercentile(40); p45 = (int) underlying.getValueAtPercentile(45); p50 = (int) underlying.getValueAtPercentile(50); p55 = (int) underlying.getValueAtPercentile(55); p60 = (int) underlying.getValueAtPercentile(60); p65 = (int) underlying.getValueAtPercentile(65); p70 = (int) underlying.getValueAtPercentile(70); p75 = (int) underlying.getValueAtPercentile(75); p80 = (int) underlying.getValueAtPercentile(80); p85 = (int) underlying.getValueAtPercentile(85); p90 = (int) underlying.getValueAtPercentile(90); p95 = (int) underlying.getValueAtPercentile(95); p99 = (int) underlying.getValueAtPercentile(99); p99_5 = (int) underlying.getValueAtPercentile(99.5); p99_9 = (int) underlying.getValueAtPercentile(99.9); p99_95 = (int) underlying.getValueAtPercentile(99.95); p99_99 = (int) underlying.getValueAtPercentile(99.99); p100 = (int) underlying.getValueAtPercentile(100); totalCount = underlying.getTotalCount(); } /** * Return the cached value only * @return cached distribution mean */ public int getMean() { return mean; } /** * Return the cached value if available. * Otherwise, we need to synchronize access to the underlying {@link Histogram} * @param percentile percentile of distribution * @return value at percentile (from cache if possible) */ public int getValueAtPercentile(double percentile) { int permyriad = (int) (percentile * 100); switch (permyriad) { case 0: return p0; case 500: return p5; case 1000: return p10; case 1500: return p15; case 2000: return p20; case 2500: return p25; case 3000: return p30; case 3500: return p35; case 4000: return p40; case 4500: return p45; case 5000: return p50; case 5500: return p55; case 6000: return p60; case 6500: return p65; case 7000: return p70; case 7500: return p75; case 8000: return p80; case 8500: return p85; case 9000: return p90; case 9500: return p95; case 9900: return p99; case 9950: return p99_5; case 9990: return p99_9; case 9995: return p99_95; case 9999: return p99_99; case 10000: return p100; default: throw new IllegalArgumentException("Percentile (" + percentile + ") is not currently cached"); } } public long getTotalCount() { return totalCount; } public static Histogram getNewHistogram() { return new Histogram(NUMBER_SIGNIFICANT_DIGITS); } }
4,673
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/HystrixCommandExecutionStarted.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.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.HystrixThreadPoolKey; /** * Data class that get fed to event stream when a command starts executing. */ public class HystrixCommandExecutionStarted extends HystrixCommandEvent { private final HystrixCommandProperties.ExecutionIsolationStrategy isolationStrategy; private final int currentConcurrency; public HystrixCommandExecutionStarted(HystrixCommandKey commandKey, HystrixThreadPoolKey threadPoolKey, HystrixCommandProperties.ExecutionIsolationStrategy isolationStrategy, int currentConcurrency) { super(commandKey, threadPoolKey); this.isolationStrategy = isolationStrategy; this.currentConcurrency = currentConcurrency; } @Override public boolean isExecutionStart() { return true; } @Override public boolean isExecutedInThread() { return isolationStrategy == HystrixCommandProperties.ExecutionIsolationStrategy.THREAD; } @Override public boolean isResponseThreadPoolRejected() { return false; } @Override public boolean isCommandCompletion() { return false; } @Override public boolean didCommandExecute() { return false; } public int getCurrentConcurrency() { return currentConcurrency; } }
4,674
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/HystrixCommandEvent.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.HystrixCommandKey; import com.netflix.hystrix.HystrixThreadPoolKey; import rx.functions.Func1; /** * Data class that comprises the event stream for Hystrix command executions. * As of 1.5.0-RC1, this is only {@link HystrixCommandCompletion}s. */ public abstract class HystrixCommandEvent implements HystrixEvent { private final HystrixCommandKey commandKey; private final HystrixThreadPoolKey threadPoolKey; protected HystrixCommandEvent(HystrixCommandKey commandKey, HystrixThreadPoolKey threadPoolKey) { this.commandKey = commandKey; this.threadPoolKey = threadPoolKey; } public HystrixCommandKey getCommandKey() { return commandKey; } public HystrixThreadPoolKey getThreadPoolKey() { return threadPoolKey; } public abstract boolean isExecutionStart(); public abstract boolean isExecutedInThread(); public abstract boolean isResponseThreadPoolRejected(); public abstract boolean isCommandCompletion(); public abstract boolean didCommandExecute(); public static final Func1<HystrixCommandEvent, Boolean> filterCompletionsOnly = new Func1<HystrixCommandEvent, Boolean>() { @Override public Boolean call(HystrixCommandEvent commandEvent) { return commandEvent.isCommandCompletion(); } }; public static final Func1<HystrixCommandEvent, Boolean> filterActualExecutions = new Func1<HystrixCommandEvent, Boolean>() { @Override public Boolean call(HystrixCommandEvent commandEvent) { return commandEvent.didCommandExecute(); } }; }
4,675
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/HystrixThreadPoolCompletionStream.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.HystrixThreadPoolKey; import rx.Observable; import rx.subjects.PublishSubject; import rx.subjects.SerializedSubject; import rx.subjects.Subject; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Per-ThreadPool stream of {@link HystrixCommandCompletion}s. This gets written to by {@link HystrixThreadEventStream}s. * Events are emitted synchronously in the same thread that performs the command execution. */ public class HystrixThreadPoolCompletionStream implements HystrixEventStream<HystrixCommandCompletion> { private final HystrixThreadPoolKey threadPoolKey; private final Subject<HystrixCommandCompletion, HystrixCommandCompletion> writeOnlySubject; private final Observable<HystrixCommandCompletion> readOnlyStream; private static final ConcurrentMap<String, HystrixThreadPoolCompletionStream> streams = new ConcurrentHashMap<String, HystrixThreadPoolCompletionStream>(); public static HystrixThreadPoolCompletionStream getInstance(HystrixThreadPoolKey threadPoolKey) { HystrixThreadPoolCompletionStream initialStream = streams.get(threadPoolKey.name()); if (initialStream != null) { return initialStream; } else { synchronized (HystrixThreadPoolCompletionStream.class) { HystrixThreadPoolCompletionStream existingStream = streams.get(threadPoolKey.name()); if (existingStream == null) { HystrixThreadPoolCompletionStream newStream = new HystrixThreadPoolCompletionStream(threadPoolKey); streams.putIfAbsent(threadPoolKey.name(), newStream); return newStream; } else { return existingStream; } } } } HystrixThreadPoolCompletionStream(final HystrixThreadPoolKey threadPoolKey) { this.threadPoolKey = threadPoolKey; this.writeOnlySubject = new SerializedSubject<HystrixCommandCompletion, HystrixCommandCompletion>(PublishSubject.<HystrixCommandCompletion>create()); this.readOnlyStream = writeOnlySubject.share(); } public static void reset() { streams.clear(); } public void write(HystrixCommandCompletion event) { writeOnlySubject.onNext(event); } @Override public Observable<HystrixCommandCompletion> observe() { return readOnlyStream; } @Override public String toString() { return "HystrixThreadPoolCompletionStream(" + threadPoolKey.name() + ")"; } }
4,676
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/HystrixEvent.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; /** * Marker interface for events which may appear in an event stream */ public interface HystrixEvent { }
4,677
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/HystrixCollapserEvent.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.HystrixCollapserKey; import com.netflix.hystrix.HystrixEventType; /** * Data class that comprises the event stream for Hystrix collapser executions. * This class represents the 3 things that can happen (found in {@link com.netflix.hystrix.HystrixEventType.Collapser} enum: * <p><ul> * <li>ADDED_TO_BATCH</li> * <li>BATCH_EXECUTED</li> * <li>RESPONSE_FROM_CACHE</li> * </ul> * */ public class HystrixCollapserEvent implements HystrixEvent { private final HystrixCollapserKey collapserKey; private final HystrixEventType.Collapser eventType; private final int count; protected HystrixCollapserEvent(HystrixCollapserKey collapserKey, HystrixEventType.Collapser eventType, int count) { this.collapserKey = collapserKey; this.eventType = eventType; this.count = count; } public static HystrixCollapserEvent from(HystrixCollapserKey collapserKey, HystrixEventType.Collapser eventType, int count) { return new HystrixCollapserEvent(collapserKey, eventType, count); } public HystrixCollapserKey getCollapserKey() { return collapserKey; } public HystrixEventType.Collapser getEventType() { return eventType; } public int getCount() { return count; } @Override public String toString() { return "HystrixCollapserEvent[" + collapserKey.name() + "] : " + eventType.name() + " : " + count; } }
4,678
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/HystrixEventStream.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 rx.Observable; /** * Base interface for a stream of {@link com.netflix.hystrix.HystrixEventType}s. Allows consumption by individual * {@link com.netflix.hystrix.HystrixEventType} or by time-based bucketing of events */ public interface HystrixEventStream<E extends HystrixEvent> { Observable<E> observe(); }
4,679
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/HystrixRequestEventsStream.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; import com.netflix.hystrix.HystrixInvokableInfo; import rx.Observable; import rx.subjects.PublishSubject; import rx.subjects.Subject; import java.util.Collection; /** * Stream of requests, each of which contains a series of command executions */ public class HystrixRequestEventsStream { private final Subject<HystrixRequestEvents, HystrixRequestEvents> writeOnlyRequestEventsSubject; private final Observable<HystrixRequestEvents> readOnlyRequestEvents; /* package */ HystrixRequestEventsStream() { writeOnlyRequestEventsSubject = PublishSubject.create(); readOnlyRequestEvents = writeOnlyRequestEventsSubject.onBackpressureBuffer(1024); } private static final HystrixRequestEventsStream INSTANCE = new HystrixRequestEventsStream(); public static HystrixRequestEventsStream getInstance() { return INSTANCE; } public void shutdown() { writeOnlyRequestEventsSubject.onCompleted(); } public void write(Collection<HystrixInvokableInfo<?>> executions) { HystrixRequestEvents requestEvents = new HystrixRequestEvents(executions); writeOnlyRequestEventsSubject.onNext(requestEvents); } public Observable<HystrixRequestEvents> observe() { return readOnlyRequestEvents; } }
4,680
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/HystrixCommandStartStream.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.HystrixCommandKey; import rx.Observable; import rx.subjects.PublishSubject; import rx.subjects.SerializedSubject; import rx.subjects.Subject; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Per-Command stream of {@link HystrixCommandExecutionStarted}s. This gets written to by {@link HystrixThreadEventStream}s. * Events are emitted synchronously in the same thread that performs the command execution. */ public class HystrixCommandStartStream implements HystrixEventStream<HystrixCommandExecutionStarted> { private final HystrixCommandKey commandKey; private final Subject<HystrixCommandExecutionStarted, HystrixCommandExecutionStarted> writeOnlySubject; private final Observable<HystrixCommandExecutionStarted> readOnlyStream; private static final ConcurrentMap<String, HystrixCommandStartStream> streams = new ConcurrentHashMap<String, HystrixCommandStartStream>(); public static HystrixCommandStartStream getInstance(HystrixCommandKey commandKey) { HystrixCommandStartStream initialStream = streams.get(commandKey.name()); if (initialStream != null) { return initialStream; } else { synchronized (HystrixCommandStartStream.class) { HystrixCommandStartStream existingStream = streams.get(commandKey.name()); if (existingStream == null) { HystrixCommandStartStream newStream = new HystrixCommandStartStream(commandKey); streams.putIfAbsent(commandKey.name(), newStream); return newStream; } else { return existingStream; } } } } HystrixCommandStartStream(final HystrixCommandKey commandKey) { this.commandKey = commandKey; this.writeOnlySubject = new SerializedSubject<HystrixCommandExecutionStarted, HystrixCommandExecutionStarted>(PublishSubject.<HystrixCommandExecutionStarted>create()); this.readOnlyStream = writeOnlySubject.share(); } public static void reset() { streams.clear(); } public void write(HystrixCommandExecutionStarted event) { writeOnlySubject.onNext(event); } @Override public Observable<HystrixCommandExecutionStarted> observe() { return readOnlyStream; } @Override public String toString() { return "HystrixCommandStartStream(" + commandKey.name() + ")"; } }
4,681
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/HystrixCommandCompletion.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 com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; import java.util.ArrayList; import java.util.List; /** * Data class which gets fed into event stream when a command completes (with any of the outcomes in {@link HystrixEventType}). */ public class HystrixCommandCompletion extends HystrixCommandEvent { protected final ExecutionResult executionResult; protected final HystrixRequestContext requestContext; private final static HystrixEventType[] ALL_EVENT_TYPES = HystrixEventType.values(); HystrixCommandCompletion(ExecutionResult executionResult, HystrixCommandKey commandKey, HystrixThreadPoolKey threadPoolKey, HystrixRequestContext requestContext) { super(commandKey, threadPoolKey); this.executionResult = executionResult; this.requestContext = requestContext; } public static HystrixCommandCompletion from(ExecutionResult executionResult, HystrixCommandKey commandKey, HystrixThreadPoolKey threadPoolKey) { return from(executionResult, commandKey, threadPoolKey, HystrixRequestContext.getContextForCurrentThread()); } public static HystrixCommandCompletion from(ExecutionResult executionResult, HystrixCommandKey commandKey, HystrixThreadPoolKey threadPoolKey, HystrixRequestContext requestContext) { return new HystrixCommandCompletion(executionResult, commandKey, threadPoolKey, requestContext); } @Override public boolean isResponseThreadPoolRejected() { return executionResult.isResponseThreadPoolRejected(); } @Override public boolean isExecutionStart() { return false; } @Override public boolean isExecutedInThread() { return executionResult.isExecutedInThread(); } @Override public boolean isCommandCompletion() { return true; } public HystrixRequestContext getRequestContext() { return this.requestContext; } public ExecutionResult.EventCounts getEventCounts() { return executionResult.getEventCounts(); } public long getExecutionLatency() { return executionResult.getExecutionLatency(); } public long getTotalLatency() { return executionResult.getUserThreadLatency(); } @Override public boolean didCommandExecute() { return executionResult.executionOccurred(); } @Override public String toString() { StringBuffer sb = new StringBuffer(); List<HystrixEventType> foundEventTypes = new ArrayList<HystrixEventType>(); sb.append(getCommandKey().name()).append("["); for (HystrixEventType eventType: ALL_EVENT_TYPES) { if (executionResult.getEventCounts().contains(eventType)) { foundEventTypes.add(eventType); } } int i = 0; for (HystrixEventType eventType: foundEventTypes) { sb.append(eventType.name()); int eventCount = executionResult.getEventCounts().getCount(eventType); if (eventCount > 1) { sb.append("x").append(eventCount); } if (i < foundEventTypes.size() - 1) { sb.append(", "); } i++; } sb.append("][").append(getExecutionLatency()).append(" ms]"); return sb.toString(); } }
4,682
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/HystrixThreadPoolStartStream.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; import com.netflix.hystrix.HystrixThreadPoolKey; import rx.Observable; import rx.subjects.PublishSubject; import rx.subjects.SerializedSubject; import rx.subjects.Subject; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Per-ThreadPool stream of {@link HystrixCommandExecutionStarted}s. This gets written to by {@link HystrixThreadEventStream}s. * Events are emitted synchronously in the same thread that performs the command execution. */ public class HystrixThreadPoolStartStream implements HystrixEventStream<HystrixCommandExecutionStarted> { private final HystrixThreadPoolKey threadPoolKey; private final Subject<HystrixCommandExecutionStarted, HystrixCommandExecutionStarted> writeOnlySubject; private final Observable<HystrixCommandExecutionStarted> readOnlyStream; private static final ConcurrentMap<String, HystrixThreadPoolStartStream> streams = new ConcurrentHashMap<String, HystrixThreadPoolStartStream>(); public static HystrixThreadPoolStartStream getInstance(HystrixThreadPoolKey threadPoolKey) { HystrixThreadPoolStartStream initialStream = streams.get(threadPoolKey.name()); if (initialStream != null) { return initialStream; } else { synchronized (HystrixThreadPoolStartStream.class) { HystrixThreadPoolStartStream existingStream = streams.get(threadPoolKey.name()); if (existingStream == null) { HystrixThreadPoolStartStream newStream = new HystrixThreadPoolStartStream(threadPoolKey); streams.putIfAbsent(threadPoolKey.name(), newStream); return newStream; } else { return existingStream; } } } } HystrixThreadPoolStartStream(final HystrixThreadPoolKey threadPoolKey) { this.threadPoolKey = threadPoolKey; this.writeOnlySubject = new SerializedSubject<HystrixCommandExecutionStarted, HystrixCommandExecutionStarted>(PublishSubject.<HystrixCommandExecutionStarted>create()); this.readOnlyStream = writeOnlySubject.share(); } public static void reset() { streams.clear(); } public void write(HystrixCommandExecutionStarted event) { writeOnlySubject.onNext(event); } @Override public Observable<HystrixCommandExecutionStarted> observe() { return readOnlyStream; } @Override public String toString() { return "HystrixThreadPoolStartStream(" + threadPoolKey.name() + ")"; } }
4,683
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/HystrixCollapserEventStream.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.HystrixCollapserKey; import rx.Observable; import rx.subjects.PublishSubject; import rx.subjects.SerializedSubject; import rx.subjects.Subject; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Per-Collapser stream of {@link HystrixCollapserEvent}s. This gets written to by {@link HystrixThreadEventStream}s. * Events are emitted synchronously in the same thread that performs the batch-command execution. */ public class HystrixCollapserEventStream implements HystrixEventStream<HystrixCollapserEvent> { private final HystrixCollapserKey collapserKey; private final Subject<HystrixCollapserEvent, HystrixCollapserEvent> writeOnlyStream; private final Observable<HystrixCollapserEvent> readOnlyStream; private static final ConcurrentMap<String, HystrixCollapserEventStream> streams = new ConcurrentHashMap<String, HystrixCollapserEventStream>(); public static HystrixCollapserEventStream getInstance(HystrixCollapserKey collapserKey) { HystrixCollapserEventStream initialStream = streams.get(collapserKey.name()); if (initialStream != null) { return initialStream; } else { synchronized (HystrixCollapserEventStream.class) { HystrixCollapserEventStream existingStream = streams.get(collapserKey.name()); if (existingStream == null) { HystrixCollapserEventStream newStream = new HystrixCollapserEventStream(collapserKey); streams.putIfAbsent(collapserKey.name(), newStream); return newStream; } else { return existingStream; } } } } HystrixCollapserEventStream(final HystrixCollapserKey collapserKey) { this.collapserKey = collapserKey; this.writeOnlyStream = new SerializedSubject<HystrixCollapserEvent, HystrixCollapserEvent>(PublishSubject.<HystrixCollapserEvent>create()); this.readOnlyStream = writeOnlyStream.share(); } public static void reset() { streams.clear(); } public void write(HystrixCollapserEvent event) { writeOnlyStream.onNext(event); } public Observable<HystrixCollapserEvent> observe() { return readOnlyStream; } @Override public String toString() { return "HystrixCollapserEventStream(" + collapserKey.name() + ")"; } }
4,684
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/HystrixThreadEventStream.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.HystrixCollapserKey; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.HystrixEventType; import com.netflix.hystrix.HystrixThreadPool; import com.netflix.hystrix.HystrixThreadPoolKey; import rx.functions.Action1; import rx.observers.Subscribers; import rx.subjects.PublishSubject; import rx.subjects.Subject; /** * Per-thread event stream. No synchronization required when writing to it since it's single-threaded. * * Some threads will be dedicated to a single HystrixCommandKey (a member of a thread-isolated {@link HystrixThreadPool}. * However, many situations arise where a single thread may serve many different commands. Examples include: * * Application caller threads (semaphore-isolated commands, or thread-pool-rejections) * * Timer threads (timeouts or collapsers) * <p> * I don't think that a thread-level view is an interesting one to consume (I could be wrong), so at the moment there * is no public way to consume it. I can always add it later, if desired. * <p> * Instead, this stream writes to the following streams, which have more meaning to metrics consumers: * <ul> * <li>{@link HystrixCommandCompletionStream}</li> * <li>{@link HystrixCommandStartStream}</li> * <li>{@link HystrixThreadPoolCompletionStream}</li> * <li>{@link HystrixThreadPoolStartStream}</li> * <li>{@link HystrixCollapserEventStream}</li> * </ul> * * Also note that any observers of this stream do so on the thread that writes the metric. This is the command caller * thread in the SEMAPHORE-isolated case, and the Hystrix thread in the THREAD-isolated case. I determined this to * be more efficient CPU-wise than immediately hopping off-thread and doing all the metric calculations in the * RxComputationThreadPool. */ public class HystrixThreadEventStream { private final long threadId; private final String threadName; private final Subject<HystrixCommandExecutionStarted, HystrixCommandExecutionStarted> writeOnlyCommandStartSubject; private final Subject<HystrixCommandCompletion, HystrixCommandCompletion> writeOnlyCommandCompletionSubject; private final Subject<HystrixCollapserEvent, HystrixCollapserEvent> writeOnlyCollapserSubject; private static final ThreadLocal<HystrixThreadEventStream> threadLocalStreams = new ThreadLocal<HystrixThreadEventStream>() { @Override protected HystrixThreadEventStream initialValue() { return new HystrixThreadEventStream(Thread.currentThread()); } }; private static final Action1<HystrixCommandExecutionStarted> writeCommandStartsToShardedStreams = new Action1<HystrixCommandExecutionStarted>() { @Override public void call(HystrixCommandExecutionStarted event) { HystrixCommandStartStream commandStartStream = HystrixCommandStartStream.getInstance(event.getCommandKey()); commandStartStream.write(event); if (event.isExecutedInThread()) { HystrixThreadPoolStartStream threadPoolStartStream = HystrixThreadPoolStartStream.getInstance(event.getThreadPoolKey()); threadPoolStartStream.write(event); } } }; private static final Action1<HystrixCommandCompletion> writeCommandCompletionsToShardedStreams = new Action1<HystrixCommandCompletion>() { @Override public void call(HystrixCommandCompletion commandCompletion) { HystrixCommandCompletionStream commandStream = HystrixCommandCompletionStream.getInstance(commandCompletion.getCommandKey()); commandStream.write(commandCompletion); if (commandCompletion.isExecutedInThread() || commandCompletion.isResponseThreadPoolRejected()) { HystrixThreadPoolCompletionStream threadPoolStream = HystrixThreadPoolCompletionStream.getInstance(commandCompletion.getThreadPoolKey()); threadPoolStream.write(commandCompletion); } } }; private static final Action1<HystrixCollapserEvent> writeCollapserExecutionsToShardedStreams = new Action1<HystrixCollapserEvent>() { @Override public void call(HystrixCollapserEvent collapserEvent) { HystrixCollapserEventStream collapserStream = HystrixCollapserEventStream.getInstance(collapserEvent.getCollapserKey()); collapserStream.write(collapserEvent); } }; /* package */ HystrixThreadEventStream(Thread thread) { this.threadId = thread.getId(); this.threadName = thread.getName(); writeOnlyCommandStartSubject = PublishSubject.create(); writeOnlyCommandCompletionSubject = PublishSubject.create(); writeOnlyCollapserSubject = PublishSubject.create(); writeOnlyCommandStartSubject .onBackpressureBuffer() .doOnNext(writeCommandStartsToShardedStreams) .unsafeSubscribe(Subscribers.empty()); writeOnlyCommandCompletionSubject .onBackpressureBuffer() .doOnNext(writeCommandCompletionsToShardedStreams) .unsafeSubscribe(Subscribers.empty()); writeOnlyCollapserSubject .onBackpressureBuffer() .doOnNext(writeCollapserExecutionsToShardedStreams) .unsafeSubscribe(Subscribers.empty()); } public static HystrixThreadEventStream getInstance() { return threadLocalStreams.get(); } public void shutdown() { writeOnlyCommandStartSubject.onCompleted(); writeOnlyCommandCompletionSubject.onCompleted(); writeOnlyCollapserSubject.onCompleted(); } public void commandExecutionStarted(HystrixCommandKey commandKey, HystrixThreadPoolKey threadPoolKey, HystrixCommandProperties.ExecutionIsolationStrategy isolationStrategy, int currentConcurrency) { HystrixCommandExecutionStarted event = new HystrixCommandExecutionStarted(commandKey, threadPoolKey, isolationStrategy, currentConcurrency); writeOnlyCommandStartSubject.onNext(event); } public void executionDone(ExecutionResult executionResult, HystrixCommandKey commandKey, HystrixThreadPoolKey threadPoolKey) { HystrixCommandCompletion event = HystrixCommandCompletion.from(executionResult, commandKey, threadPoolKey); writeOnlyCommandCompletionSubject.onNext(event); } public void collapserResponseFromCache(HystrixCollapserKey collapserKey) { HystrixCollapserEvent collapserEvent = HystrixCollapserEvent.from(collapserKey, HystrixEventType.Collapser.RESPONSE_FROM_CACHE, 1); writeOnlyCollapserSubject.onNext(collapserEvent); } public void collapserBatchExecuted(HystrixCollapserKey collapserKey, int batchSize) { HystrixCollapserEvent batchExecution = HystrixCollapserEvent.from(collapserKey, HystrixEventType.Collapser.BATCH_EXECUTED, 1); HystrixCollapserEvent batchAdditions = HystrixCollapserEvent.from(collapserKey, HystrixEventType.Collapser.ADDED_TO_BATCH, batchSize); writeOnlyCollapserSubject.onNext(batchExecution); writeOnlyCollapserSubject.onNext(batchAdditions); } @Override public String toString() { return "HystrixThreadEventStream (" + threadId + " - " + threadName + ")"; } }
4,685
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/HystrixCommandCompletionStream.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.HystrixCommandKey; import rx.Observable; import rx.subjects.PublishSubject; import rx.subjects.SerializedSubject; import rx.subjects.Subject; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Per-Command stream of {@link HystrixCommandCompletion}s. This gets written to by {@link HystrixThreadEventStream}s. * Events are emitted synchronously in the same thread that performs the command execution. */ public class HystrixCommandCompletionStream implements HystrixEventStream<HystrixCommandCompletion> { private final HystrixCommandKey commandKey; private final Subject<HystrixCommandCompletion, HystrixCommandCompletion> writeOnlySubject; private final Observable<HystrixCommandCompletion> readOnlyStream; private static final ConcurrentMap<String, HystrixCommandCompletionStream> streams = new ConcurrentHashMap<String, HystrixCommandCompletionStream>(); public static HystrixCommandCompletionStream getInstance(HystrixCommandKey commandKey) { HystrixCommandCompletionStream initialStream = streams.get(commandKey.name()); if (initialStream != null) { return initialStream; } else { synchronized (HystrixCommandCompletionStream.class) { HystrixCommandCompletionStream existingStream = streams.get(commandKey.name()); if (existingStream == null) { HystrixCommandCompletionStream newStream = new HystrixCommandCompletionStream(commandKey); streams.putIfAbsent(commandKey.name(), newStream); return newStream; } else { return existingStream; } } } } HystrixCommandCompletionStream(final HystrixCommandKey commandKey) { this.commandKey = commandKey; this.writeOnlySubject = new SerializedSubject<HystrixCommandCompletion, HystrixCommandCompletion>(PublishSubject.<HystrixCommandCompletion>create()); this.readOnlyStream = writeOnlySubject.share(); } public static void reset() { streams.clear(); } public void write(HystrixCommandCompletion event) { writeOnlySubject.onNext(event); } @Override public Observable<HystrixCommandCompletion> observe() { return readOnlyStream; } @Override public String toString() { return "HystrixCommandCompletionStream(" + commandKey.name() + ")"; } }
4,686
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/HystrixRequestEvents.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.metric; import com.netflix.hystrix.ExecutionResult; import com.netflix.hystrix.HystrixCollapserKey; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixInvokableInfo; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; public class HystrixRequestEvents { private final Collection<HystrixInvokableInfo<?>> executions; public HystrixRequestEvents(Collection<HystrixInvokableInfo<?>> executions) { this.executions = executions; } public Collection<HystrixInvokableInfo<?>> getExecutions() { return executions; } public Map<ExecutionSignature, List<Integer>> getExecutionsMappedToLatencies() { Map<CommandAndCacheKey, Integer> cachingDetector = new HashMap<CommandAndCacheKey, Integer>(); List<HystrixInvokableInfo<?>> nonCachedExecutions = new ArrayList<HystrixInvokableInfo<?>>(executions.size()); for (HystrixInvokableInfo<?> execution: executions) { if (execution.getPublicCacheKey() != null) { //eligible for caching - might be the initial, or might be from cache CommandAndCacheKey key = new CommandAndCacheKey(execution.getCommandKey().name(), execution.getPublicCacheKey()); Integer count = cachingDetector.get(key); if (count != null) { //key already seen cachingDetector.put(key, count + 1); } else { //key not seen yet cachingDetector.put(key, 0); } } if (!execution.isResponseFromCache()) { nonCachedExecutions.add(execution); } } Map<ExecutionSignature, List<Integer>> commandDeduper = new HashMap<ExecutionSignature, List<Integer>>(); for (HystrixInvokableInfo<?> execution: nonCachedExecutions) { int cachedCount = 0; String cacheKey = execution.getPublicCacheKey(); if (cacheKey != null) { CommandAndCacheKey key = new CommandAndCacheKey(execution.getCommandKey().name(), cacheKey); cachedCount = cachingDetector.get(key); } ExecutionSignature signature; if (cachedCount > 0) { //this has a RESPONSE_FROM_CACHE and needs to get split off signature = ExecutionSignature.from(execution, cacheKey, cachedCount); } else { //nothing cached from this, can collapse further signature = ExecutionSignature.from(execution); } List<Integer> currentLatencyList = commandDeduper.get(signature); if (currentLatencyList != null) { currentLatencyList.add(execution.getExecutionTimeInMilliseconds()); } else { List<Integer> newLatencyList = new ArrayList<Integer>(); newLatencyList.add(execution.getExecutionTimeInMilliseconds()); commandDeduper.put(signature, newLatencyList); } } return commandDeduper; } private static class CommandAndCacheKey { private final String commandName; private final String cacheKey; public CommandAndCacheKey(String commandName, String cacheKey) { this.commandName = commandName; this.cacheKey = cacheKey; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CommandAndCacheKey that = (CommandAndCacheKey) o; if (!commandName.equals(that.commandName)) return false; return cacheKey.equals(that.cacheKey); } @Override public int hashCode() { int result = commandName.hashCode(); result = 31 * result + cacheKey.hashCode(); return result; } @Override public String toString() { return "CommandAndCacheKey{" + "commandName='" + commandName + '\'' + ", cacheKey='" + cacheKey + '\'' + '}'; } } public static class ExecutionSignature { private final String commandName; private final ExecutionResult.EventCounts eventCounts; private final String cacheKey; private final int cachedCount; private final HystrixCollapserKey collapserKey; private final int collapserBatchSize; private ExecutionSignature(HystrixCommandKey commandKey, ExecutionResult.EventCounts eventCounts, String cacheKey, int cachedCount, HystrixCollapserKey collapserKey, int collapserBatchSize) { this.commandName = commandKey.name(); this.eventCounts = eventCounts; this.cacheKey = cacheKey; this.cachedCount = cachedCount; this.collapserKey = collapserKey; this.collapserBatchSize = collapserBatchSize; } public static ExecutionSignature from(HystrixInvokableInfo<?> execution) { return new ExecutionSignature(execution.getCommandKey(), execution.getEventCounts(), null, 0, execution.getOriginatingCollapserKey(), execution.getNumberCollapsed()); } public static ExecutionSignature from(HystrixInvokableInfo<?> execution, String cacheKey, int cachedCount) { return new ExecutionSignature(execution.getCommandKey(), execution.getEventCounts(), cacheKey, cachedCount, execution.getOriginatingCollapserKey(), execution.getNumberCollapsed()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ExecutionSignature that = (ExecutionSignature) o; if (!commandName.equals(that.commandName)) return false; if (!eventCounts.equals(that.eventCounts)) return false; return !(cacheKey != null ? !cacheKey.equals(that.cacheKey) : that.cacheKey != null); } @Override public int hashCode() { int result = commandName.hashCode(); result = 31 * result + eventCounts.hashCode(); result = 31 * result + (cacheKey != null ? cacheKey.hashCode() : 0); return result; } public String getCommandName() { return commandName; } public ExecutionResult.EventCounts getEventCounts() { return eventCounts; } public int getCachedCount() { return cachedCount; } public HystrixCollapserKey getCollapserKey() { return collapserKey; } public int getCollapserBatchSize() { return collapserBatchSize; } } }
4,687
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/sample/HystrixCommandUtilization.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.metric.sample; import com.netflix.hystrix.HystrixCommandMetrics; public class HystrixCommandUtilization { private final int concurrentCommandCount; public HystrixCommandUtilization(int concurrentCommandCount) { this.concurrentCommandCount = concurrentCommandCount; } public static HystrixCommandUtilization sample(HystrixCommandMetrics commandMetrics) { return new HystrixCommandUtilization(commandMetrics.getCurrentConcurrentExecutionCount()); } public int getConcurrentCommandCount() { return concurrentCommandCount; } }
4,688
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/sample/HystrixThreadPoolUtilization.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.metric.sample; import com.netflix.hystrix.HystrixThreadPoolMetrics; public class HystrixThreadPoolUtilization { private final int currentActiveCount; private final int currentCorePoolSize; private final int currentPoolSize; private final int currentQueueSize; public HystrixThreadPoolUtilization(int currentActiveCount, int currentCorePoolSize, int currentPoolSize, int currentQueueSize) { this.currentActiveCount = currentActiveCount; this.currentCorePoolSize = currentCorePoolSize; this.currentPoolSize = currentPoolSize; this.currentQueueSize = currentQueueSize; } public static HystrixThreadPoolUtilization sample(HystrixThreadPoolMetrics threadPoolMetrics) { return new HystrixThreadPoolUtilization( threadPoolMetrics.getCurrentActiveCount().intValue(), threadPoolMetrics.getCurrentCorePoolSize().intValue(), threadPoolMetrics.getCurrentPoolSize().intValue(), threadPoolMetrics.getCurrentQueueSize().intValue() ); } public int getCurrentActiveCount() { return currentActiveCount; } public int getCurrentCorePoolSize() { return currentCorePoolSize; } public int getCurrentPoolSize() { return currentPoolSize; } public int getCurrentQueueSize() { return currentQueueSize; } }
4,689
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/sample/HystrixUtilizationStream.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.netflix.config.DynamicIntProperty; import com.netflix.config.DynamicPropertyFactory; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandMetrics; import com.netflix.hystrix.HystrixThreadPoolKey; import com.netflix.hystrix.HystrixThreadPoolMetrics; import rx.Observable; import rx.functions.Action0; import rx.functions.Func1; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * This class samples current Hystrix utilization of resources and exposes that as a stream */ public class HystrixUtilizationStream { private final int intervalInMilliseconds; private final Observable<HystrixUtilization> allUtilizationStream; private final AtomicBoolean isSourceCurrentlySubscribed = new AtomicBoolean(false); private static final DynamicIntProperty dataEmissionIntervalInMs = DynamicPropertyFactory.getInstance().getIntProperty("hystrix.stream.utilization.intervalInMilliseconds", 500); private static final Func1<Long, HystrixUtilization> getAllUtilization = new Func1<Long, HystrixUtilization>() { @Override public HystrixUtilization call(Long timestamp) { return HystrixUtilization.from( getAllCommandUtilization.call(timestamp), getAllThreadPoolUtilization.call(timestamp) ); } }; /** * @deprecated Not for public use. Please use {@link #getInstance()}. This facilitates better stream-sharing * @param intervalInMilliseconds milliseconds between data emissions */ @Deprecated //deprecated in 1.5.4. public HystrixUtilizationStream(final int intervalInMilliseconds) { this.intervalInMilliseconds = intervalInMilliseconds; this.allUtilizationStream = Observable.interval(intervalInMilliseconds, TimeUnit.MILLISECONDS) .map(getAllUtilization) .doOnSubscribe(new Action0() { @Override public void call() { isSourceCurrentlySubscribed.set(true); } }) .doOnUnsubscribe(new Action0() { @Override public void call() { isSourceCurrentlySubscribed.set(false); } }) .share() .onBackpressureDrop(); } //The data emission interval is looked up on startup only private static final HystrixUtilizationStream INSTANCE = new HystrixUtilizationStream(dataEmissionIntervalInMs.get()); public static HystrixUtilizationStream getInstance() { return INSTANCE; } static HystrixUtilizationStream getNonSingletonInstanceOnlyUsedInUnitTests(int delayInMs) { return new HystrixUtilizationStream(delayInMs); } /** * Return a ref-counted stream that will only do work when at least one subscriber is present */ public Observable<HystrixUtilization> observe() { return allUtilizationStream; } public Observable<Map<HystrixCommandKey, HystrixCommandUtilization>> observeCommandUtilization() { return allUtilizationStream.map(getOnlyCommandUtilization); } public Observable<Map<HystrixThreadPoolKey, HystrixThreadPoolUtilization>> observeThreadPoolUtilization() { return allUtilizationStream.map(getOnlyThreadPoolUtilization); } public int getIntervalInMilliseconds() { return this.intervalInMilliseconds; } public boolean isSourceCurrentlySubscribed() { return isSourceCurrentlySubscribed.get(); } private static HystrixCommandUtilization sampleCommandUtilization(HystrixCommandMetrics commandMetrics) { return HystrixCommandUtilization.sample(commandMetrics); } private static HystrixThreadPoolUtilization sampleThreadPoolUtilization(HystrixThreadPoolMetrics threadPoolMetrics) { return HystrixThreadPoolUtilization.sample(threadPoolMetrics); } private static final Func1<Long, Map<HystrixCommandKey, HystrixCommandUtilization>> getAllCommandUtilization = new Func1<Long, Map<HystrixCommandKey, HystrixCommandUtilization>>() { @Override public Map<HystrixCommandKey, HystrixCommandUtilization> call(Long timestamp) { Map<HystrixCommandKey, HystrixCommandUtilization> commandUtilizationPerKey = new HashMap<HystrixCommandKey, HystrixCommandUtilization>(); for (HystrixCommandMetrics commandMetrics: HystrixCommandMetrics.getInstances()) { HystrixCommandKey commandKey = commandMetrics.getCommandKey(); commandUtilizationPerKey.put(commandKey, sampleCommandUtilization(commandMetrics)); } return commandUtilizationPerKey; } }; private static final Func1<Long, Map<HystrixThreadPoolKey, HystrixThreadPoolUtilization>> getAllThreadPoolUtilization = new Func1<Long, Map<HystrixThreadPoolKey, HystrixThreadPoolUtilization>>() { @Override public Map<HystrixThreadPoolKey, HystrixThreadPoolUtilization> call(Long timestamp) { Map<HystrixThreadPoolKey, HystrixThreadPoolUtilization> threadPoolUtilizationPerKey = new HashMap<HystrixThreadPoolKey, HystrixThreadPoolUtilization>(); for (HystrixThreadPoolMetrics threadPoolMetrics: HystrixThreadPoolMetrics.getInstances()) { HystrixThreadPoolKey threadPoolKey = threadPoolMetrics.getThreadPoolKey(); threadPoolUtilizationPerKey.put(threadPoolKey, sampleThreadPoolUtilization(threadPoolMetrics)); } return threadPoolUtilizationPerKey; } }; private static final Func1<HystrixUtilization, Map<HystrixCommandKey, HystrixCommandUtilization>> getOnlyCommandUtilization = new Func1<HystrixUtilization, Map<HystrixCommandKey, HystrixCommandUtilization>>() { @Override public Map<HystrixCommandKey, HystrixCommandUtilization> call(HystrixUtilization hystrixUtilization) { return hystrixUtilization.getCommandUtilizationMap(); } }; private static final Func1<HystrixUtilization, Map<HystrixThreadPoolKey, HystrixThreadPoolUtilization>> getOnlyThreadPoolUtilization = new Func1<HystrixUtilization, Map<HystrixThreadPoolKey, HystrixThreadPoolUtilization>>() { @Override public Map<HystrixThreadPoolKey, HystrixThreadPoolUtilization> call(HystrixUtilization hystrixUtilization) { return hystrixUtilization.getThreadPoolUtilizationMap(); } }; }
4,690
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/sample/HystrixUtilization.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.metric.sample; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixThreadPoolKey; import java.util.Map; public class HystrixUtilization { private final Map<HystrixCommandKey, HystrixCommandUtilization> commandUtilizationMap; private final Map<HystrixThreadPoolKey, HystrixThreadPoolUtilization> threadPoolUtilizationMap; public HystrixUtilization(Map<HystrixCommandKey, HystrixCommandUtilization> commandUtilizationMap, Map<HystrixThreadPoolKey, HystrixThreadPoolUtilization> threadPoolUtilizationMap) { this.commandUtilizationMap = commandUtilizationMap; this.threadPoolUtilizationMap = threadPoolUtilizationMap; } public static HystrixUtilization from(Map<HystrixCommandKey, HystrixCommandUtilization> commandUtilizationMap, Map<HystrixThreadPoolKey, HystrixThreadPoolUtilization> threadPoolUtilizationMap) { return new HystrixUtilization(commandUtilizationMap, threadPoolUtilizationMap); } public Map<HystrixCommandKey, HystrixCommandUtilization> getCommandUtilizationMap() { return commandUtilizationMap; } public Map<HystrixThreadPoolKey, HystrixThreadPoolUtilization> getThreadPoolUtilizationMap() { return threadPoolUtilizationMap; } }
4,691
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/consumer/RollingCommandEventCounterStream.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.consumer; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandMetrics; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.HystrixEventType; import com.netflix.hystrix.metric.HystrixCommandCompletion; import com.netflix.hystrix.metric.HystrixCommandCompletionStream; import rx.functions.Func2; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Maintains a stream of event counters for a given Command. * There is a rolling window abstraction on this stream. * The event counters object is calculated over a window of t1 milliseconds. This window has b buckets. * Therefore, a new set of counters is produced every t2 (=t1/b) milliseconds * t1 = {@link HystrixCommandProperties#metricsRollingStatisticalWindowInMilliseconds()} * b = {@link HystrixCommandProperties#metricsRollingStatisticalWindowBuckets()} * * These values are stable - there's no peeking into a bucket until it is emitted * * These values get produced and cached in this class. This value (the latest observed value) may be queried using {@link #getLatest(HystrixEventType)}. */ public class RollingCommandEventCounterStream extends BucketedRollingCounterStream<HystrixCommandCompletion, long[], long[]> { private static final ConcurrentMap<String, RollingCommandEventCounterStream> streams = new ConcurrentHashMap<String, RollingCommandEventCounterStream>(); private static final int NUM_EVENT_TYPES = HystrixEventType.values().length; public static RollingCommandEventCounterStream getInstance(HystrixCommandKey commandKey, HystrixCommandProperties properties) { final int counterMetricWindow = properties.metricsRollingStatisticalWindowInMilliseconds().get(); final int numCounterBuckets = properties.metricsRollingStatisticalWindowBuckets().get(); final int counterBucketSizeInMs = counterMetricWindow / numCounterBuckets; return getInstance(commandKey, numCounterBuckets, counterBucketSizeInMs); } public static RollingCommandEventCounterStream getInstance(HystrixCommandKey commandKey, int numBuckets, int bucketSizeInMs) { RollingCommandEventCounterStream initialStream = streams.get(commandKey.name()); if (initialStream != null) { return initialStream; } else { synchronized (RollingCommandEventCounterStream.class) { RollingCommandEventCounterStream existingStream = streams.get(commandKey.name()); if (existingStream == null) { RollingCommandEventCounterStream newStream = new RollingCommandEventCounterStream(commandKey, numBuckets, bucketSizeInMs, HystrixCommandMetrics.appendEventToBucket, HystrixCommandMetrics.bucketAggregator); streams.putIfAbsent(commandKey.name(), newStream); return newStream; } else { return existingStream; } } } } public static void reset() { streams.clear(); } private RollingCommandEventCounterStream(HystrixCommandKey commandKey, int numCounterBuckets, int counterBucketSizeInMs, Func2<long[], HystrixCommandCompletion, long[]> reduceCommandCompletion, Func2<long[], long[], long[]> reduceBucket) { super(HystrixCommandCompletionStream.getInstance(commandKey), numCounterBuckets, counterBucketSizeInMs, reduceCommandCompletion, reduceBucket); } @Override long[] getEmptyBucketSummary() { return new long[NUM_EVENT_TYPES]; } @Override long[] getEmptyOutputValue() { return new long[NUM_EVENT_TYPES]; } public long getLatest(HystrixEventType eventType) { return getLatest()[eventType.ordinal()]; } }
4,692
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/consumer/RollingDistributionStream.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.consumer; import com.netflix.hystrix.metric.CachedValuesHistogram; import com.netflix.hystrix.metric.HystrixEvent; import com.netflix.hystrix.metric.HystrixEventStream; import org.HdrHistogram.Histogram; import rx.Observable; import rx.Subscription; import rx.functions.Func0; import rx.functions.Func1; import rx.functions.Func2; import rx.subjects.BehaviorSubject; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; /** * Maintains a stream of distributions for a given Command. * There is a rolling window abstraction on this stream. * The latency distribution object is calculated over a window of t1 milliseconds. This window has b buckets. * Therefore, a new set of counters is produced every t2 (=t1/b) milliseconds * t1 = metricsRollingPercentileWindowInMilliseconds() * b = metricsRollingPercentileBucketSize() * * These values are stable - there's no peeking into a bucket until it is emitted * * These values get produced and cached in this class. */ public class RollingDistributionStream<Event extends HystrixEvent> { private AtomicReference<Subscription> rollingDistributionSubscription = new AtomicReference<Subscription>(null); private final BehaviorSubject<CachedValuesHistogram> rollingDistribution = BehaviorSubject.create(CachedValuesHistogram.backedBy(CachedValuesHistogram.getNewHistogram())); private final Observable<CachedValuesHistogram> rollingDistributionStream; private static final Func2<Histogram, Histogram, Histogram> distributionAggregator = new Func2<Histogram, Histogram, Histogram>() { @Override public Histogram call(Histogram initialDistribution, Histogram distributionToAdd) { initialDistribution.add(distributionToAdd); return initialDistribution; } }; private static final Func1<Observable<Histogram>, Observable<Histogram>> reduceWindowToSingleDistribution = new Func1<Observable<Histogram>, Observable<Histogram>>() { @Override public Observable<Histogram> call(Observable<Histogram> window) { return window.reduce(distributionAggregator); } }; private static final Func1<Histogram, CachedValuesHistogram> cacheHistogramValues = new Func1<Histogram, CachedValuesHistogram>() { @Override public CachedValuesHistogram call(Histogram histogram) { return CachedValuesHistogram.backedBy(histogram); } }; private static final Func1<Observable<CachedValuesHistogram>, Observable<List<CachedValuesHistogram>>> convertToList = new Func1<Observable<CachedValuesHistogram>, Observable<List<CachedValuesHistogram>>>() { @Override public Observable<List<CachedValuesHistogram>> call(Observable<CachedValuesHistogram> windowOf2) { return windowOf2.toList(); } }; protected RollingDistributionStream(final HystrixEventStream<Event> stream, final int numBuckets, final int bucketSizeInMs, final Func2<Histogram, Event, Histogram> addValuesToBucket) { final List<Histogram> emptyDistributionsToStart = new ArrayList<Histogram>(); for (int i = 0; i < numBuckets; i++) { emptyDistributionsToStart.add(CachedValuesHistogram.getNewHistogram()); } final Func1<Observable<Event>, Observable<Histogram>> reduceBucketToSingleDistribution = new Func1<Observable<Event>, Observable<Histogram>>() { @Override public Observable<Histogram> call(Observable<Event> bucket) { return bucket.reduce(CachedValuesHistogram.getNewHistogram(), addValuesToBucket); } }; rollingDistributionStream = stream .observe() .window(bucketSizeInMs, TimeUnit.MILLISECONDS) //stream of unaggregated buckets .flatMap(reduceBucketToSingleDistribution) //stream of aggregated Histograms .startWith(emptyDistributionsToStart) //stream of aggregated Histograms that starts with n empty .window(numBuckets, 1) //windowed stream: each OnNext is a stream of n Histograms .flatMap(reduceWindowToSingleDistribution) //reduced stream: each OnNext is a single Histogram .map(cacheHistogramValues) //convert to CachedValueHistogram (commonly-accessed values are cached) .share() .onBackpressureDrop(); } public Observable<CachedValuesHistogram> observe() { return rollingDistributionStream; } public int getLatestMean() { CachedValuesHistogram latest = getLatest(); if (latest != null) { return latest.getMean(); } else { return 0; } } public int getLatestPercentile(double percentile) { CachedValuesHistogram latest = getLatest(); if (latest != null) { return latest.getValueAtPercentile(percentile); } else { return 0; } } public void startCachingStreamValuesIfUnstarted() { if (rollingDistributionSubscription.get() == null) { //the stream is not yet started Subscription candidateSubscription = observe().subscribe(rollingDistribution); if (rollingDistributionSubscription.compareAndSet(null, candidateSubscription)) { //won the race to set the subscription } else { //lost the race to set the subscription, so we need to cancel this one candidateSubscription.unsubscribe(); } } } CachedValuesHistogram getLatest() { startCachingStreamValuesIfUnstarted(); if (rollingDistribution.hasValue()) { return rollingDistribution.getValue(); } else { return null; } } public void unsubscribe() { Subscription s = rollingDistributionSubscription.get(); if (s != null) { s.unsubscribe(); rollingDistributionSubscription.compareAndSet(s, null); } } }
4,693
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/consumer/RollingCollapserEventCounterStream.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.consumer; import com.netflix.hystrix.HystrixCollapserKey; import com.netflix.hystrix.HystrixCollapserMetrics; import com.netflix.hystrix.HystrixCollapserProperties; import com.netflix.hystrix.HystrixEventType; import com.netflix.hystrix.metric.HystrixCollapserEvent; import com.netflix.hystrix.metric.HystrixCollapserEventStream; import rx.functions.Func2; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Maintains a stream of event counters for a given Command. * There is a rolling window abstraction on this stream. * The event counters object is calculated over a window of t1 milliseconds. This window has b buckets. * Therefore, a new set of counters is produced every t2 (=t1/b) milliseconds * t1 = {@link com.netflix.hystrix.HystrixCollapserProperties#metricsRollingStatisticalWindowInMilliseconds()} * b = {@link com.netflix.hystrix.HystrixCollapserProperties#metricsRollingStatisticalWindowBuckets()} * * These values are stable - there's no peeking into a bucket until it is emitted * * These values get produced and cached in this class. This value (the latest observed value) may be queried using {@link #getLatest(HystrixEventType.Collapser)}. */ public class RollingCollapserEventCounterStream extends BucketedRollingCounterStream<HystrixCollapserEvent, long[], long[]> { private static final ConcurrentMap<String, RollingCollapserEventCounterStream> streams = new ConcurrentHashMap<String, RollingCollapserEventCounterStream>(); private static final int NUM_EVENT_TYPES = HystrixEventType.Collapser.values().length; public static RollingCollapserEventCounterStream getInstance(HystrixCollapserKey collapserKey, HystrixCollapserProperties properties) { final int counterMetricWindow = properties.metricsRollingStatisticalWindowInMilliseconds().get(); final int numCounterBuckets = properties.metricsRollingStatisticalWindowBuckets().get(); final int counterBucketSizeInMs = counterMetricWindow / numCounterBuckets; return getInstance(collapserKey, numCounterBuckets, counterBucketSizeInMs); } public static RollingCollapserEventCounterStream getInstance(HystrixCollapserKey collapserKey, int numBuckets, int bucketSizeInMs) { RollingCollapserEventCounterStream initialStream = streams.get(collapserKey.name()); if (initialStream != null) { return initialStream; } else { synchronized (RollingCollapserEventCounterStream.class) { RollingCollapserEventCounterStream existingStream = streams.get(collapserKey.name()); if (existingStream == null) { RollingCollapserEventCounterStream newStream = new RollingCollapserEventCounterStream(collapserKey, numBuckets, bucketSizeInMs, HystrixCollapserMetrics.appendEventToBucket, HystrixCollapserMetrics.bucketAggregator); streams.putIfAbsent(collapserKey.name(), newStream); return newStream; } else { return existingStream; } } } } public static void reset() { streams.clear(); } private RollingCollapserEventCounterStream(HystrixCollapserKey collapserKey, int numCounterBuckets, int counterBucketSizeInMs, Func2<long[], HystrixCollapserEvent, long[]> appendEventToBucket, Func2<long[], long[], long[]> reduceBucket) { super(HystrixCollapserEventStream.getInstance(collapserKey), numCounterBuckets, counterBucketSizeInMs, appendEventToBucket, reduceBucket); } @Override long[] getEmptyBucketSummary() { return new long[NUM_EVENT_TYPES]; } @Override long[] getEmptyOutputValue() { return new long[NUM_EVENT_TYPES]; } public long getLatest(HystrixEventType.Collapser eventType) { return getLatest()[eventType.ordinal()]; } }
4,694
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/consumer/BucketedCumulativeCounterStream.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.consumer; import com.netflix.hystrix.metric.HystrixEvent; import com.netflix.hystrix.metric.HystrixEventStream; import rx.Observable; import rx.functions.Action0; import rx.functions.Func2; import java.util.concurrent.atomic.AtomicBoolean; /** * Refinement of {@link BucketedCounterStream} which accumulates counters infinitely in the bucket-reduction step * * @param <Event> type of raw data that needs to get summarized into a bucket * @param <Bucket> type of data contained in each bucket * @param <Output> type of data emitted to stream subscribers (often is the same as A but does not have to be) */ public abstract class BucketedCumulativeCounterStream<Event extends HystrixEvent, Bucket, Output> extends BucketedCounterStream<Event, Bucket, Output> { private Observable<Output> sourceStream; private final AtomicBoolean isSourceCurrentlySubscribed = new AtomicBoolean(false); protected BucketedCumulativeCounterStream(HystrixEventStream<Event> stream, int numBuckets, int bucketSizeInMs, Func2<Bucket, Event, Bucket> reduceCommandCompletion, Func2<Output, Bucket, Output> reduceBucket) { super(stream, numBuckets, bucketSizeInMs, reduceCommandCompletion); this.sourceStream = bucketedStream .scan(getEmptyOutputValue(), reduceBucket) .skip(numBuckets) .doOnSubscribe(new Action0() { @Override public void call() { isSourceCurrentlySubscribed.set(true); } }) .doOnUnsubscribe(new Action0() { @Override public void call() { isSourceCurrentlySubscribed.set(false); } }) .share() //multiple subscribers should get same data .onBackpressureDrop(); //if there are slow consumers, data should not buffer } @Override public Observable<Output> observe() { return sourceStream; } }
4,695
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/consumer/BucketedRollingCounterStream.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.consumer; import com.netflix.hystrix.metric.HystrixEvent; import com.netflix.hystrix.metric.HystrixEventStream; import rx.Observable; import rx.functions.Action0; import rx.functions.Func1; import rx.functions.Func2; import java.util.concurrent.atomic.AtomicBoolean; /** * Refinement of {@link BucketedCounterStream} which reduces numBuckets at a time. * * @param <Event> type of raw data that needs to get summarized into a bucket * @param <Bucket> type of data contained in each bucket * @param <Output> type of data emitted to stream subscribers (often is the same as A but does not have to be) */ public abstract class BucketedRollingCounterStream<Event extends HystrixEvent, Bucket, Output> extends BucketedCounterStream<Event, Bucket, Output> { private Observable<Output> sourceStream; private final AtomicBoolean isSourceCurrentlySubscribed = new AtomicBoolean(false); protected BucketedRollingCounterStream(HystrixEventStream<Event> stream, final int numBuckets, int bucketSizeInMs, final Func2<Bucket, Event, Bucket> appendRawEventToBucket, final Func2<Output, Bucket, Output> reduceBucket) { super(stream, numBuckets, bucketSizeInMs, appendRawEventToBucket); Func1<Observable<Bucket>, Observable<Output>> reduceWindowToSummary = new Func1<Observable<Bucket>, Observable<Output>>() { @Override public Observable<Output> call(Observable<Bucket> window) { return window.scan(getEmptyOutputValue(), reduceBucket).skip(numBuckets); } }; this.sourceStream = bucketedStream //stream broken up into buckets .window(numBuckets, 1) //emit overlapping windows of buckets .flatMap(reduceWindowToSummary) //convert a window of bucket-summaries into a single summary .doOnSubscribe(new Action0() { @Override public void call() { isSourceCurrentlySubscribed.set(true); } }) .doOnUnsubscribe(new Action0() { @Override public void call() { isSourceCurrentlySubscribed.set(false); } }) .share() //multiple subscribers should get same data .onBackpressureDrop(); //if there are slow consumers, data should not buffer } @Override public Observable<Output> observe() { return sourceStream; } /* package-private */ boolean isSourceCurrentlySubscribed() { return isSourceCurrentlySubscribed.get(); } }
4,696
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/consumer/RollingCommandUserLatencyDistributionStream.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.consumer; import com.netflix.hystrix.HystrixCollapserProperties; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.metric.HystrixCommandCompletion; import com.netflix.hystrix.metric.HystrixCommandCompletionStream; import com.netflix.hystrix.metric.HystrixCommandEvent; import org.HdrHistogram.Histogram; import rx.functions.Func2; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Maintains a stream of latency distributions for a given Command. * There is a rolling window abstraction on this stream. * The latency distribution object is calculated over a window of t1 milliseconds. This window has b buckets. * Therefore, a new set of counters is produced every t2 (=t1/b) milliseconds * t1 = {@link HystrixCollapserProperties#metricsRollingPercentileWindowInMilliseconds()} * b = {@link HystrixCollapserProperties#metricsRollingPercentileBucketSize()} * * These values are stable - there's no peeking into a bucket until it is emitted * * The only latencies which get included in the distribution are for those commands which started execution. * This relies on {@link HystrixCommandEvent#didCommandExecute()} * * These values get produced and cached in this class. * The distributions can be queried on 2 dimensions: * * Execution time or total time * ** Execution time is the time spent executing the user-provided execution method. * ** Total time is the time spent from the perspecitve of the consumer, and includes all Hystrix bookkeeping. */ public class RollingCommandUserLatencyDistributionStream extends RollingDistributionStream<HystrixCommandCompletion> { private static final ConcurrentMap<String, RollingCommandUserLatencyDistributionStream> streams = new ConcurrentHashMap<String, RollingCommandUserLatencyDistributionStream>(); private static final Func2<Histogram, HystrixCommandCompletion, Histogram> addValuesToBucket = new Func2<Histogram, HystrixCommandCompletion, Histogram>() { @Override public Histogram call(Histogram initialDistribution, HystrixCommandCompletion event) { if (event.didCommandExecute() && event.getTotalLatency() > -1) { initialDistribution.recordValue(event.getTotalLatency()); } return initialDistribution; } }; public static RollingCommandUserLatencyDistributionStream getInstance(HystrixCommandKey commandKey, HystrixCommandProperties properties) { final int percentileMetricWindow = properties.metricsRollingPercentileWindowInMilliseconds().get(); final int numPercentileBuckets = properties.metricsRollingPercentileWindowBuckets().get(); final int percentileBucketSizeInMs = percentileMetricWindow / numPercentileBuckets; return getInstance(commandKey, numPercentileBuckets, percentileBucketSizeInMs); } public static RollingCommandUserLatencyDistributionStream getInstance(HystrixCommandKey commandKey, int numBuckets, int bucketSizeInMs) { RollingCommandUserLatencyDistributionStream initialStream = streams.get(commandKey.name()); if (initialStream != null) { return initialStream; } else { synchronized (RollingCommandUserLatencyDistributionStream.class) { RollingCommandUserLatencyDistributionStream existingStream = streams.get(commandKey.name()); if (existingStream == null) { RollingCommandUserLatencyDistributionStream newStream = new RollingCommandUserLatencyDistributionStream(commandKey, numBuckets, bucketSizeInMs); streams.putIfAbsent(commandKey.name(), newStream); return newStream; } else { return existingStream; } } } } public static void reset() { streams.clear(); } private RollingCommandUserLatencyDistributionStream(HystrixCommandKey commandKey, int numPercentileBuckets, int percentileBucketSizeInMs) { super(HystrixCommandCompletionStream.getInstance(commandKey), numPercentileBuckets, percentileBucketSizeInMs, addValuesToBucket); } }
4,697
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/consumer/RollingCommandMaxConcurrencyStream.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.consumer; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.metric.HystrixCommandStartStream; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Maintains a stream of the maximum concurrency seen by this command. * * This gets calculated using a rolling window of t1 milliseconds. This window has b buckets. * Therefore, a new rolling-max is produced every t2 (=t1/b) milliseconds * t1 = {@link HystrixCommandProperties#metricsRollingStatisticalWindowInMilliseconds()} * b = {@link HystrixCommandProperties#metricsRollingStatisticalWindowBuckets()} * * This value gets cached in this class. It may be queried using {@link #getLatestRollingMax()} * This value is stable - there's no peeking into a bucket until it is emitted * */ public class RollingCommandMaxConcurrencyStream extends RollingConcurrencyStream { private static final ConcurrentMap<String, RollingCommandMaxConcurrencyStream> streams = new ConcurrentHashMap<String, RollingCommandMaxConcurrencyStream>(); public static RollingCommandMaxConcurrencyStream getInstance(HystrixCommandKey commandKey, HystrixCommandProperties properties) { final int counterMetricWindow = properties.metricsRollingStatisticalWindowInMilliseconds().get(); final int numCounterBuckets = properties.metricsRollingStatisticalWindowBuckets().get(); final int counterBucketSizeInMs = counterMetricWindow / numCounterBuckets; return getInstance(commandKey, numCounterBuckets, counterBucketSizeInMs); } public static RollingCommandMaxConcurrencyStream getInstance(HystrixCommandKey commandKey, int numBuckets, int bucketSizeInMs) { RollingCommandMaxConcurrencyStream initialStream = streams.get(commandKey.name()); if (initialStream != null) { return initialStream; } else { synchronized (RollingCommandMaxConcurrencyStream.class) { RollingCommandMaxConcurrencyStream existingStream = streams.get(commandKey.name()); if (existingStream == null) { RollingCommandMaxConcurrencyStream newStream = new RollingCommandMaxConcurrencyStream(commandKey, numBuckets, bucketSizeInMs); streams.putIfAbsent(commandKey.name(), newStream); return newStream; } else { return existingStream; } } } } public static void reset() { streams.clear(); } private RollingCommandMaxConcurrencyStream(final HystrixCommandKey commandKey, final int numBuckets, final int bucketSizeInMs) { super(HystrixCommandStartStream.getInstance(commandKey), numBuckets, bucketSizeInMs); } }
4,698
0
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric
Create_ds/Hystrix/hystrix-core/src/main/java/com/netflix/hystrix/metric/consumer/HystrixDashboardStream.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.config.DynamicIntProperty; import com.netflix.config.DynamicPropertyFactory; import com.netflix.hystrix.HystrixCollapserMetrics; import com.netflix.hystrix.HystrixCommandMetrics; import com.netflix.hystrix.HystrixThreadPoolMetrics; import rx.Observable; import rx.functions.Action0; import rx.functions.Func1; import java.util.Collection; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; public class HystrixDashboardStream { final int delayInMs; final Observable<DashboardData> singleSource; final AtomicBoolean isSourceCurrentlySubscribed = new AtomicBoolean(false); private static final DynamicIntProperty dataEmissionIntervalInMs = DynamicPropertyFactory.getInstance().getIntProperty("hystrix.stream.dashboard.intervalInMilliseconds", 500); private HystrixDashboardStream(int delayInMs) { this.delayInMs = delayInMs; this.singleSource = Observable.interval(delayInMs, TimeUnit.MILLISECONDS) .map(new Func1<Long, DashboardData>() { @Override public DashboardData call(Long timestamp) { return new DashboardData( HystrixCommandMetrics.getInstances(), HystrixThreadPoolMetrics.getInstances(), HystrixCollapserMetrics.getInstances() ); } }) .doOnSubscribe(new Action0() { @Override public void call() { isSourceCurrentlySubscribed.set(true); } }) .doOnUnsubscribe(new Action0() { @Override public void call() { isSourceCurrentlySubscribed.set(false); } }) .share() .onBackpressureDrop(); } //The data emission interval is looked up on startup only private static final HystrixDashboardStream INSTANCE = new HystrixDashboardStream(dataEmissionIntervalInMs.get()); public static HystrixDashboardStream getInstance() { return INSTANCE; } static HystrixDashboardStream getNonSingletonInstanceOnlyUsedInUnitTests(int delayInMs) { return new HystrixDashboardStream(delayInMs); } /** * Return a ref-counted stream that will only do work when at least one subscriber is present */ public Observable<DashboardData> observe() { return singleSource; } public boolean isSourceCurrentlySubscribed() { return isSourceCurrentlySubscribed.get(); } public static class DashboardData { final Collection<HystrixCommandMetrics> commandMetrics; final Collection<HystrixThreadPoolMetrics> threadPoolMetrics; final Collection<HystrixCollapserMetrics> collapserMetrics; public DashboardData(Collection<HystrixCommandMetrics> commandMetrics, Collection<HystrixThreadPoolMetrics> threadPoolMetrics, Collection<HystrixCollapserMetrics> collapserMetrics) { this.commandMetrics = commandMetrics; this.threadPoolMetrics = threadPoolMetrics; this.collapserMetrics = collapserMetrics; } public Collection<HystrixCommandMetrics> getCommandMetrics() { return commandMetrics; } public Collection<HystrixThreadPoolMetrics> getThreadPoolMetrics() { return threadPoolMetrics; } public Collection<HystrixCollapserMetrics> getCollapserMetrics() { return collapserMetrics; } } }
4,699