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/ribbon/ribbon-loadbalancer/src/test/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/RandomLBTest.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.loadbalancer; import static org.junit.Assert.*; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import org.junit.BeforeClass; import org.junit.Test; public class RandomLBTest { static HashMap<String, Boolean> isAliveMap = new HashMap<String, Boolean>(); static BaseLoadBalancer lb; @BeforeClass public static void setup(){ isAliveMap.put("dummyservice0.netflix.com:8080", Boolean.TRUE); isAliveMap.put("dummyservice1.netflix.com:8080", Boolean.TRUE); isAliveMap.put("dummyservice2.netflix.com:8080", Boolean.TRUE); isAliveMap.put("dummyservice3.netflix.com:8080", Boolean.TRUE); IPing ping = new PingFake(); IRule rule = new RandomRule(); lb = new BaseLoadBalancer(ping,rule); lb.setPingInterval(20); lb.setMaxTotalPingTime(5); // the setting of servers is done by a call to DiscoveryService lb.setServers("dummyservice0.netflix.com:8080, dummyservice1.netflix.com:8080,dummyservice2.netflix.com:8080,dummyservice3.netflix.com:8080"); try { Thread.sleep(1000); } catch (InterruptedException e) { } } /** * Simulate a single user who should just round robin among the available servers */ @Test public void testRoundRobin(){ Set<String> servers = new HashSet<String>(); for (int i=0; i < 100; i++){ Server svc = lb.chooseServer("user1"); servers.add(svc.getId()); } assertEquals(isAliveMap.keySet(), servers); } static class PingFake implements IPing { public boolean isAlive(Server server) { Boolean res = isAliveMap.get(server.getId()); return ((res != null) && (res.booleanValue())); } } }
7,000
0
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/ServerStatusChangeListenerTest.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.loadbalancer; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.core.AllOf.allOf; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.junit.Before; import org.junit.Test; public class ServerStatusChangeListenerTest { /** * A load balancer that has all the functionality of the Base one except it does not * schedule any ping tasks that can concurrently update the state of the LB by either * causing forced pings to be dropped or changing the expected state of the test before * we assert our invariants. */ private class NoPingTaskLoadBalancer extends BaseLoadBalancer { @Override void setupPingTask() {} } private final Server server1 = new Server("server1"); private final Server server2 = new Server("server2"); private BaseLoadBalancer lb; private AtomicReference<List<Server>> serversReceivedByListener; @Before public void setupLoadbalancerAndListener() { lb = new NoPingTaskLoadBalancer(); lb.setServersList(asList(server1, server2)); serversReceivedByListener = new AtomicReference<List<Server>>(); lb.addServerStatusChangeListener(new ServerStatusChangeListener() { @Override public void serverStatusChanged(final Collection<Server> servers) { serversReceivedByListener.set(new ArrayList<Server>(servers)); } }); } @Test public void markServerDownByIdShouldBeReceivedByListener() { lb.markServerDown(server1.getId()); assertThat(serversReceivedByListener.get(), is(singletonList(server1))); lb.markServerDown(server2.getId()); assertThat(serversReceivedByListener.get(), is(singletonList(server2))); } @Test public void markServerDownByObjectShouldBeReceivedByListener() { lb.markServerDown(server1); assertThat(serversReceivedByListener.get(), is(singletonList(server1))); lb.markServerDown(server2); assertThat(serversReceivedByListener.get(), is(singletonList(server2))); } @Test public void changeServerStatusByPingShouldBeReceivedByListener() throws InterruptedException { final PingConstant ping = new PingConstant(); // Start with a ping where both servers are down. ping.setConstant(false); lb.setPing(ping); lb.forceQuickPing(); // We should see that the servers that changed status are both server1 and 2. assertThat(serversReceivedByListener.get(), allOf(hasItem(server1), hasItem(server2))); // Bring both servers back up. ping.setConstant(true); // Clear the list so we can see the change-list is non-empty after the listener is called. serversReceivedByListener.set(null); lb.forceQuickPing(); assertFalse(serversReceivedByListener.get().isEmpty()); assertThat(serversReceivedByListener.get(), allOf(hasItem(server1), hasItem(server2))); } }
7,001
0
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/ServerTest.java
package com.netflix.loadbalancer; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.junit.Test; public class ServerTest { @Test public void createSchemeHost() { Server server = new Server("http://netflix.com"); assertEquals("http", server.getScheme()); assertEquals("netflix.com", server.getHost()); assertEquals(80, server.getPort()); } @Test public void createSchemeHostPort() { Server server = new Server("http://netflix.com:8080"); assertEquals("http", server.getScheme()); assertEquals("netflix.com", server.getHost()); assertEquals(8080, server.getPort()); } @Test public void createSecureSchemeHost() { Server server = new Server("https://netflix.com"); assertEquals("https", server.getScheme()); assertEquals("netflix.com", server.getHost()); assertEquals(443, server.getPort()); } @Test public void createSecureSchemeHostPort() { Server server = new Server("https://netflix.com:443"); assertEquals("https", server.getScheme()); assertEquals("netflix.com", server.getHost()); assertEquals(443, server.getPort()); } @Test public void createSecureSchemeHostPortExplicit() { Server server = new Server("https", "netflix.com", 443); assertEquals("https", server.getScheme()); assertEquals("netflix.com", server.getHost()); assertEquals(443, server.getPort()); } @Test public void createHost() { Server server = new Server("netflix.com"); assertNull(server.getScheme()); assertEquals("netflix.com", server.getHost()); assertEquals(80, server.getPort()); } @Test public void createHostPort() { Server server = new Server("netflix.com:8080"); assertNull(server.getScheme()); assertEquals("netflix.com", server.getHost()); assertEquals(8080, server.getPort()); } }
7,002
0
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/LoadBalancerContextTest.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.loadbalancer; import static org.junit.Assert.assertEquals; import java.net.URI; import java.net.URLEncoder; import org.junit.Test; import com.netflix.client.config.IClientConfig; public class LoadBalancerContextTest { final static Object httpKey = "http"; final static Object httpsKey = "https"; static BaseLoadBalancer lb = new BaseLoadBalancer() { @Override public Server chooseServer(Object key) { return new Server("www.example.com:8080"); } }; static BaseLoadBalancer mixedSchemeLb = new BaseLoadBalancer() { @Override public Server chooseServer(Object key) { if (key == httpKey) { return new Server("http://www.example.com:8081"); } else if (key == httpsKey) { return new Server("https://www.example.com:8443"); } return new Server("www.example.com:8080"); } }; private MyLoadBalancerContext context; public LoadBalancerContextTest() { context = new MyLoadBalancerContext(lb); } @Test public void testComputeURIWithMixedSchemaLoadBalancer() throws Exception { context = new MyLoadBalancerContext(mixedSchemeLb); URI request = new URI("/test?abc=xyz"); // server with no scheme defined Server server = context.getServerFromLoadBalancer(request, null); URI newURI = context.reconstructURIWithServer(server, request); assertEquals("http://www.example.com:8080/test?abc=xyz", newURI.toString()); // server with no scheme defined server = context.getServerFromLoadBalancer(request, httpKey); newURI = context.reconstructURIWithServer(server, request); assertEquals("http://www.example.com:8081/test?abc=xyz", newURI.toString()); server = context.getServerFromLoadBalancer(request, httpsKey); newURI = context.reconstructURIWithServer(server, request); assertEquals("https://www.example.com:8443/test?abc=xyz", newURI.toString()); } @Test public void testComputeFinalUriWithLoadBalancer() throws Exception { URI request = new URI("/test?abc=xyz"); Server server = context.getServerFromLoadBalancer(request, null); URI newURI = context.reconstructURIWithServer(server, request); assertEquals("http://www.example.com:8080/test?abc=xyz", newURI.toString()); } @Test public void testEncodedPath() throws Exception { String uri = "http://localhost:8080/resources/abc%2Fxyz"; URI request = new URI(uri); Server server = context.getServerFromLoadBalancer(request, null); URI newURI = context.reconstructURIWithServer(server, request); assertEquals(uri, newURI.toString()); } @Test public void testPreservesUserInfo() throws Exception { // %3A == ":" -- ensure user info is not decoded String uri = "http://us%3Aer:pass@localhost:8080?foo=bar"; URI requestedURI = new URI(uri); Server server = context.getServerFromLoadBalancer(requestedURI, null); URI newURI = context.reconstructURIWithServer(server, requestedURI); assertEquals(uri, newURI.toString()); } @Test public void testQueryWithoutPath() throws Exception { String uri = "?foo=bar"; URI requestedURI = new URI(uri); Server server = context.getServerFromLoadBalancer(requestedURI, null); URI newURI = context.reconstructURIWithServer(server, requestedURI); assertEquals("http://www.example.com:8080?foo=bar", newURI.toString()); } @Test public void testEncodedPathAndHostChange() throws Exception { String uri = "/abc%2Fxyz"; URI request = new URI(uri); Server server = context.getServerFromLoadBalancer(request, null); URI newURI = context.reconstructURIWithServer(server, request); assertEquals("http://www.example.com:8080" + uri, newURI.toString()); } @Test public void testEncodedQuery() throws Exception { String uri = "http://localhost:8080/resources/abc?"; String queryString = "name=" + URLEncoder.encode("????&=*%!@#$%^&*()", "UTF-8"); URI request = new URI(uri + queryString); Server server = context.getServerFromLoadBalancer(request, null); URI newURI = context.reconstructURIWithServer(server, request); assertEquals(uri + queryString, newURI.toString()); } } class MyLoadBalancerContext extends LoadBalancerContext { public MyLoadBalancerContext(ILoadBalancer lb, IClientConfig clientConfig) { super(lb, clientConfig); } public MyLoadBalancerContext(ILoadBalancer lb) { super(lb); } }
7,003
0
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix/loadbalancer/reactive/ExecutionContextTest.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.loadbalancer.reactive; import com.netflix.client.RetryHandler; import com.netflix.client.config.DefaultClientConfigImpl; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; /** * @author Allen Wang */ public class ExecutionContextTest { @Test public void testSubContext() { ExecutionContext<String> context = new ExecutionContext<String>("hello", DefaultClientConfigImpl.getEmptyConfig(), DefaultClientConfigImpl.getClientConfigWithDefaultValues(), RetryHandler.DEFAULT); ExecutionContext<String> subContext1 = context.getChildContext("foo"); ExecutionContext<String> subContext2 = context.getChildContext("bar"); assertSame(context, context.getGlobalContext()); context.put("dummy", "globalValue"); context.put("dummy2", "globalValue"); subContext1.put("dummy", "context1Value"); subContext2.put("dummy", "context2Value"); assertEquals("context1Value", subContext1.get("dummy")); assertEquals("context2Value", subContext2.get("dummy")); assertEquals("globalValue", subContext1.getGlobalContext().get("dummy")); assertNull(subContext1.get("dummy2")); } }
7,004
0
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix/client/SimpleVipAddressResolverTest.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.client; import static org.junit.Assert.*; import org.junit.Test; import com.netflix.config.ConfigurationManager; public class SimpleVipAddressResolverTest { @Test public void test() { ConfigurationManager.getConfigInstance().setProperty("foo", "abc"); ConfigurationManager.getConfigInstance().setProperty("bar", "xyz"); SimpleVipAddressResolver resolver = new SimpleVipAddressResolver(); String resolved = resolver.resolve("www.${foo}.com,myserver,${bar}", null); assertEquals("www.abc.com,myserver,xyz", resolved); } @Test public void testNoMacro() { ConfigurationManager.getConfigInstance().setProperty("foo", "abc"); ConfigurationManager.getConfigInstance().setProperty("bar", "xyz"); SimpleVipAddressResolver resolver = new SimpleVipAddressResolver(); String resolved = resolver.resolve("www.foo.com,myserver,bar", null); assertEquals("www.foo.com,myserver,bar", resolved); } @Test public void testUndefinedProp() { ConfigurationManager.getConfigInstance().setProperty("bar", "xyz"); SimpleVipAddressResolver resolver = new SimpleVipAddressResolver(); String resolved = resolver.resolve("www.${var}.com,myserver,${bar}", null); assertEquals("www.${var}.com,myserver,xyz", resolved); } }
7,005
0
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix/client
Create_ds/ribbon/ribbon-loadbalancer/src/test/java/com/netflix/client/testutil/MockHttpServer.java
package com.netflix.client.testutil; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.InetSocketAddress; import java.net.URI; import java.net.URISyntaxException; import java.security.KeyStore; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLParameters; import javax.net.ssl.TrustManagerFactory; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.sun.jersey.core.util.Base64; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsParameters; import com.sun.net.httpserver.HttpsServer; /** * Rule for running an embedded HTTP server for basic testing. The * server uses ephemeral ports to ensure there are no conflicts when * running concurrent unit tests * * The server uses HttpServer classes available in the JVM to avoid * pulling in any extra dependencies. * * Available endpoints are, * * / Returns a 200 * /status?code=${code} Returns a request provide code * /noresponse No response from the server * * Optional query parameters * delay=${delay} Inject a delay into the request * * @author elandau * */ public class MockHttpServer implements TestRule { public static final String TEST_TS1 = "/u3+7QAAAAIAAAABAAAAAgALcmliYm9uX3Jvb3QAAAFA9E6KkQAFWC41MDkAAAIyMIICLjCCAZeg" + "AwIBAgIBATANBgkqhkiG9w0BAQUFADBTMRgwFgYDVQQDDA9SaWJib25UZXN0Um9vdDExCzAJBgNV" + "BAsMAklUMRAwDgYDVQQKDAdOZXRmbGl4MQswCQYDVQQIDAJDQTELMAkGA1UEBhMCVVMwIBcNMTMw" + "OTA2MTcyNTIyWhgPMjExMzA4MTMxNzI1MjJaMFMxGDAWBgNVBAMMD1JpYmJvblRlc3RSb290MTEL" + "MAkGA1UECwwCSVQxEDAOBgNVBAoMB05ldGZsaXgxCzAJBgNVBAgMAkNBMQswCQYDVQQGEwJVUzCB" + "nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAg8riOgT2Y39SQlZE+MWnOiKjREZzQ3ecvPf40oF8" + "9YPNGpBhJzIKdA0TR1vQ70p3Fl2+Y5txs1H2/iguOdFMBrSdv1H8qJG1UufaeYO++HBm3Mi2L02F" + "6fcTEEyXQMebKCWf04mxvLy5M6B5yMqZ9rHEZD+qsF4rXspx70bd0tUCAwEAAaMQMA4wDAYDVR0T" + "BAUwAwEB/zANBgkqhkiG9w0BAQUFAAOBgQBzTEn9AZniODYSRa+N7IvZu127rh+Sc6XWth68TBRj" + "hThDFARnGxxe2d3EFXB4xH7qcvLl3HQ3U6lIycyLabdm06D3/jzu68mkMToE5sHJmrYNHHTVl0aj" + "0gKFBQjLRJRlgJ3myUbbfrM+/a5g6S90TsVGTxXwFn5bDvdErsn8F8Hd41plMkW5ywsn6yFZMaFr" + "MxnX"; // Keystore type: JKS // Keystore provider: SUN // // Your keystore contains 1 entry // // Alias name: ribbon_root // Creation date: Sep 6, 2013 // Entry type: trustedCertEntry // // Owner: C=US, ST=CA, O=Netflix, OU=IT, CN=RibbonTestRoot2 // Issuer: C=US, ST=CA, O=Netflix, OU=IT, CN=RibbonTestRoot2 // Serial number: 1 // Valid from: Fri Sep 06 10:26:22 PDT 2013 until: Sun Aug 13 10:26:22 PDT 2113 // Certificate fingerprints: // MD5: 44:64:E3:25:4F:D2:2C:8D:4D:B0:53:19:59:BD:B3:20 // SHA1: 26:2F:41:6D:03:C7:D0:8E:4F:AF:0E:4F:29:E3:08:53:B7:3C:DB:EE // Signature algorithm name: SHA1withRSA // Version: 3 // // Extensions: // // #1: ObjectId: 2.5.29.19 Criticality=false // BasicConstraints:[ // CA:true // PathLen:2147483647 // ] public static final String TEST_TS2 = "/u3+7QAAAAIAAAABAAAAAgALcmliYm9uX3Jvb3QAAAFA9E92vgAFWC41MDkAAAIyMIICLjCCAZeg" + "AwIBAgIBATANBgkqhkiG9w0BAQUFADBTMRgwFgYDVQQDDA9SaWJib25UZXN0Um9vdDIxCzAJBgNV" + "BAsMAklUMRAwDgYDVQQKDAdOZXRmbGl4MQswCQYDVQQIDAJDQTELMAkGA1UEBhMCVVMwIBcNMTMw" + "OTA2MTcyNjIyWhgPMjExMzA4MTMxNzI2MjJaMFMxGDAWBgNVBAMMD1JpYmJvblRlc3RSb290MjEL" + "MAkGA1UECwwCSVQxEDAOBgNVBAoMB05ldGZsaXgxCzAJBgNVBAgMAkNBMQswCQYDVQQGEwJVUzCB" + "nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAnEwAfuHYKRJviVB3RyV3+/mp4qjWZZd/q+fE2Z0k" + "o2N2rrC8fAw53KXwGOE5fED6wXd3B2zyoSFHVsWOeL+TUoohn+eHSfwH7xK+0oWC8IvUoXWehOft" + "grYtv9Jt5qNY5SmspBmyxFiaiAWQJYuf12Ycu4Gqg+P7mieMHgu6Do0CAwEAAaMQMA4wDAYDVR0T" + "BAUwAwEB/zANBgkqhkiG9w0BAQUFAAOBgQBNA0ask9eTYYhYA3bbmQZInxkBV74Gq/xorLlVygjn" + "OgyGYp4/L274qwlPMqnQRmVbezkug2YlUK8xbrjwCUvHq2XW38e2RjK5q3EXVkGJxgCBuHug/eIf" + "wD+/IEIE8aVkTW2j1QrrdkXDhRO5OsjvIVdy5/V4U0hVDnSo865ud9VQ/hZmOQuZItHViSoGSe2j" + "bbZk"; // Keystore type: JKS // Keystore provider: SUN // // Your keystore contains 1 entry // // Alias name: ribbon_key // Creation date: Sep 6, 2013 // Entry type: PrivateKeyEntry // Certificate chain length: 1 // Certificate[1]: // Owner: C=US, ST=CA, O=Netflix, OU=IT, CN=RibbonTestEndEntity1 // Issuer: C=US, ST=CA, O=Netflix, OU=IT, CN=RibbonTestRoot1 // Serial number: 64 // Valid from: Fri Sep 06 10:25:22 PDT 2013 until: Sun Aug 13 10:25:22 PDT 2113 // Certificate fingerprints: // MD5: 79:C5:F3:B2:B8:4C:F2:3F:2E:C7:67:FC:E7:04:BF:90 // SHA1: B1:D0:4E:A6:D8:84:BF:8B:01:46:B6:EA:97:5B:A0:4E:13:8B:A9:DE // Signature algorithm name: SHA1withRSA // Version: 3 public static final String TEST_KS1 = "/u3+7QAAAAIAAAABAAAAAQAKcmliYm9uX2tleQAAAUD0Toq4AAACuzCCArcwDgYKKwYBBAEqAhEB" + "AQUABIICo9fLN8zeXLcyx50+6B6gdXiUslZKY0SgLwL8kKNlQFiccD3Oc1yWjMnVC2QOdLsFzcVk" + "ROhgMH/nHfFeXFlvY5IYMXqhbEC37LjE52RtX5KHv4FLYxxZCHduAwO8UTPa603XzrJ0VTMJ6Hso" + "9+Ql76cGxPtIPcYm8IfqIY22as3NlKO4eMbiur9GLvuC57eql8vROaxGy8y657gc6kZMUyQOC+HG" + "a5M3DTFpjl4V6HHbXHhMNEk9eXHnrZwYVOJmOgdgIrNNHOyD4kE+k21C7rUHhLAwK84wKL/tW4k9" + "xnhOJK/L1RmycRIFWwXVi3u/3vi49bzdZsRLn73MdQkTe5p8oNZzG9sxg76u67ua6+99TMZYE1ay" + "5JCYgbr85KbRsoX9Hd5XBcSNzROKJl0To2tAF8eTTMRlhEy7JZyTF2M9877juNaregVwE3Tp+a/J" + "ACeNMyrxOQItNDam7a5dgBohpM8oJdEFqqj/S9BU7H5sR0XYo8TyIe1BV9zR5ZC/23fj5l5zkrri" + "TCMgMbvt95JUGOT0gSzxBMmhV+ZLxpmVz3M5P2pXX0DXGTKfuHSiBWrh1GAQL4BOVpuKtyXlH1/9" + "55/xY25W0fpLzMiQJV7jf6W69LU0FAFWFH9uuwf/sFph0S1QQXcQSfpYmWPMi1gx/IgIbvT1xSuI" + "6vajgFqv6ctiVbFAJ6zmcnGd6e33+Ao9pmjs5JPZP3rtAYd6+PxtlwUbGLZuqIVK4o68LEISDfvm" + "nGlk4/1+S5CILKVqTC6Ja8ojwUjjsNSJbZwHue3pOkmJQUNtuK6kDOYXgiMRLURbrYLyen0azWw8" + "C5/nPs5J4pN+irD/hhD6cupCnUJmzMw30u8+LOCN6GaM5fdCTQ2uQKF7quYuD+gR3lLNOqq7KAAA" + "AAEABVguNTA5AAACJTCCAiEwggGKoAMCAQICAWQwDQYJKoZIhvcNAQEFBQAwUzEYMBYGA1UEAwwP" + "UmliYm9uVGVzdFJvb3QxMQswCQYDVQQLDAJJVDEQMA4GA1UECgwHTmV0ZmxpeDELMAkGA1UECAwC" + "Q0ExCzAJBgNVBAYTAlVTMCAXDTEzMDkwNjE3MjUyMloYDzIxMTMwODEzMTcyNTIyWjBYMR0wGwYD" + "VQQDDBRSaWJib25UZXN0RW5kRW50aXR5MTELMAkGA1UECwwCSVQxEDAOBgNVBAoMB05ldGZsaXgx" + "CzAJBgNVBAgMAkNBMQswCQYDVQQGEwJVUzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAydqk" + "AJuUcSF8dpUbNJWl+G1usgHtEFEbOMm54N/ZqGC7iSYs6EXfeoEyiHrMw/hdCKACERq2vuiuqan8" + "h6z65/DXIiHUyykGb/Z4NK1I0aCQLZG4Ek3sERilILWyy2NRpjUrvqDPr/mQgymXqpuYhSD81jHx" + "F84AOpTrnGsY7/sCAwEAATANBgkqhkiG9w0BAQUFAAOBgQAjvtRKNhb1R6XIuWaOxJ0XDLine464" + "Ie7LDfkE/KB43oE4MswjRh7nR9q6C73oa6TlIXmW6ysyKPp0vAyWHlq/zZhL3gNQ6faHuYHqas5s" + "nJQgvQpHAQh4VXRyZt1K8ZdsHg3Qbd4APTL0aRVQkxDt+Dxd6AsoRMKmO/c5CRwUFIV/CK7k5VSh" + "Sl5PRtH3PVj2vp84"; // Keystore type: JKS // Keystore provider: SUN // // Your keystore contains 1 entry // // Alias name: ribbon_key // Creation date: Sep 6, 2013 // Entry type: PrivateKeyEntry // Certificate chain length: 1 // Certificate[1]: // Owner: C=US, ST=CA, O=Netflix, OU=IT, CN=RibbonTestEndEntity2 // Issuer: C=US, ST=CA, O=Netflix, OU=IT, CN=RibbonTestRoot2 // Serial number: 64 // Valid from: Fri Sep 06 10:26:22 PDT 2013 until: Sun Aug 13 10:26:22 PDT 2113 // Certificate fingerprints: // MD5: C3:AF:6A:DB:18:ED:70:22:83:73:9A:A5:DB:58:6D:04 // SHA1: B7:D4:F0:87:A8:4E:49:0A:91:B1:7B:62:28:CA:A2:4A:0E:AE:40:CC // Signature algorithm name: SHA1withRSA // Version: 3 // // // public static final String TEST_KS2 = "/u3+7QAAAAIAAAABAAAAAQAKcmliYm9uX2tleQAAAUD0T3bNAAACuzCCArcwDgYKKwYBBAEqAhEB" + "AQUABIICoysDP4inwmxxKZkS8EYMW3DCJCD1AmpwFHxJIzo2v9fMysg+vjKxsrvVyKG23ZcHcznI" + "ftmrEpriCCUZp+NNAf0EJWVAIzGenwrsd0+rI5I96gBOh9slJUzgucn7164R3XKNKk+VWcwGJRh+" + "IuHxVrwFN025pfhlBJXNGJg4ZlzB7ZwcQPYblBzhLbhS3vJ1Vc46pEYWpnjxmHaDSetaQIcueAp8" + "HnTUkFMXJ6t51N0u9QMPhBH7p7N8tNjaa5noSdxhSl/2Znj6r04NwQU1qX2n4rSWEnYaW1qOVkgx" + "YrQzxI2kSHZfQDM2T918UikboQvAS1aX4h5P3gVCDKLr3EOO6UYO0ZgLHUr/DZrhVKd1KAhnzaJ8" + "BABxot2ES7Zu5EzY9goiaYDA2/bkURmt0zDdKpeORb7r59XBZUm/8D80naaNnE45W/gBA9bCiDu3" + "R99xie447c7ZX9Jio25yil3ncv+npBO1ozc5QIgQnbEfxbbwii3//shvPT6oxYPrcwWBXnaJNC5w" + "2HDpCTXJZNucyjnNVVxC7p1ANNnvvZhgC0+GpEqmf/BW+fb9Qu+AXe0/h4Vnoe/Zs92vPDehpaKy" + "oe+jBlUNiW2bpR88DSqxVcIu1DemlgzPa1Unzod0FdrOr/272bJnB2zAo4OBaBSv3KNf/rsMKjsU" + "X2Po77+S+PKoQkqd8KJFpmLEb0vxig9JsrTDJXLf4ebeSA1W7+mBotimMrp646PA3NciMSbS4csh" + "A7o/dBYhHlEosVgThm1JknIKhemf+FZsOzR3bJDT1oXJ/GhYpfzlCLyVFBeVP0KRnhih4xO0MEO7" + "Q21DBaTTqAvUo7Iv3/F3mGMOanLcLgoRoq3moQ7FhfCDRtRAPA1qT2+pxPG5wqlGeYc6McOvogAA" + "AAEABVguNTA5AAACJTCCAiEwggGKoAMCAQICAWQwDQYJKoZIhvcNAQEFBQAwUzEYMBYGA1UEAwwP" + "UmliYm9uVGVzdFJvb3QyMQswCQYDVQQLDAJJVDEQMA4GA1UECgwHTmV0ZmxpeDELMAkGA1UECAwC" + "Q0ExCzAJBgNVBAYTAlVTMCAXDTEzMDkwNjE3MjYyMloYDzIxMTMwODEzMTcyNjIyWjBYMR0wGwYD" + "VQQDDBRSaWJib25UZXN0RW5kRW50aXR5MjELMAkGA1UECwwCSVQxEDAOBgNVBAoMB05ldGZsaXgx" + "CzAJBgNVBAgMAkNBMQswCQYDVQQGEwJVUzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAtOvK" + "fBMC/oMo4xf4eYGN7hTNn+IywaSaVYndqECIfuznoIqRKSbeCKPSGs4CN1D+u3E2UoXcsDmTguHU" + "fokDA7sLUu8wD5ndAXfCkP3gXlFtUpNz/jPaXDsMFntTn2BdLKccxRxNwtwC0zzwIdtx9pw/Ru0g" + "NXIQnPi50aql5WcCAwEAATANBgkqhkiG9w0BAQUFAAOBgQCYWM2ZdBjG3jCvMw/RkebMLkEDRxVM" + "XU63Ygo+iCZUk8V8d0/S48j8Nk/hhVGHljsHqE/dByEF77X6uHaDGtt3Xwe+AYPofoJukh89jKnT" + "jEDtLF+y5AVfz6b2z3TnJcuigMr4ZtBFv18R00KLnVAznl/waXG8ix44IL5ss6nRZBJE4jr+ZMG9" + "9I4P1YhySxo3Qd3g"; public static final String PASSWORD = "changeit"; public static final String INTERNALERROR_PATH = "/internalerror"; public static final String NORESPONSE_PATH = "/noresponse"; public static final String STATUS_PATH = "/status"; public static final String OK_PATH = "/ok"; public static final String ROOT_PATH = "/"; private static final int DEFAULT_THREAD_COUNT = 10; private static final String DELAY_QUERY_PARAM = "delay"; private HttpServer server; private int localHttpServerPort = 0; private ExecutorService service; private int threadCount = DEFAULT_THREAD_COUNT; private LinkedHashMap<String, HttpHandler> handlers = new LinkedHashMap<String, HttpHandler>(); private boolean hasSsl = false; private File keystore; private File truststore; private String GENERIC_RESPONSE = "GenericTestHttpServer Response"; public MockHttpServer() { handlers.put(ROOT_PATH, new TestHttpHandler() { @Override protected void handle(RequestContext context) throws IOException { context.response(200, GENERIC_RESPONSE); }}); handlers.put(OK_PATH, new TestHttpHandler() { @Override protected void handle(RequestContext context) throws IOException { context.response(200, GENERIC_RESPONSE); }}); handlers.put(STATUS_PATH, new TestHttpHandler() { @Override protected void handle(RequestContext context) throws IOException { context.response(Integer.parseInt(context.query("code")), GENERIC_RESPONSE); }}); handlers.put(NORESPONSE_PATH, new TestHttpHandler() { @Override protected void handle(RequestContext context) throws IOException { }}); handlers.put(INTERNALERROR_PATH, new TestHttpHandler() { @Override protected void handle(RequestContext context) throws IOException { throw new RuntimeException("InternalError"); }}); } public MockHttpServer handler(String path, HttpHandler handler) { handlers.put(path, handler); return this; } public MockHttpServer port(int port) { this.localHttpServerPort = port; return this; } public MockHttpServer secure() { this.hasSsl = true; return this; } public MockHttpServer threadCount(int threads) { this.threadCount = threads; return this; } @Override public Statement apply(final Statement statement, final Description description) { return new Statement() { @Override public void evaluate() throws Throwable { before(description); try { statement.evaluate(); } finally { after(description); } } }; } private static interface RequestContext { void response(int code, String body) throws IOException; String query(String key); } private static abstract class TestHttpHandler implements HttpHandler { @Override public final void handle(final HttpExchange t) throws IOException { try { final Map<String, String> queryParameters = queryToMap(t); if (queryParameters.containsKey(DELAY_QUERY_PARAM)) { Long delay = Long.parseLong(queryParameters.get(DELAY_QUERY_PARAM)); if (delay != null) { try { TimeUnit.MILLISECONDS.sleep(delay); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } handle(new RequestContext() { @Override public void response(int code, String body) throws IOException { OutputStream os = t.getResponseBody(); t.sendResponseHeaders(code, body.length()); os.write(body.getBytes()); os.close(); } @Override public String query(String key) { return queryParameters.get(key); } }); } catch (Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); String body = sw.toString(); OutputStream os = t.getResponseBody(); t.sendResponseHeaders(500, body.length()); os.write(body.getBytes()); os.close(); } } protected abstract void handle(RequestContext context) throws IOException; private static Map<String, String> queryToMap(HttpExchange t) { String queryString = t.getRequestURI().getQuery(); Map<String, String> result = new HashMap<String, String>(); if (queryString != null) { for (String param : queryString.split("&")) { String pair[] = param.split("="); if (pair.length>1) { result.put(pair[0], pair[1]); } else{ result.put(pair[0], ""); } } } return result; } } public void before(final Description description) throws Exception { this.service = Executors.newFixedThreadPool( threadCount, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("TestHttpServer-%d").build()); InetSocketAddress inetSocketAddress = new InetSocketAddress("localhost", 0); if (hasSsl) { byte[] sampleTruststore1 = Base64.decode(TEST_TS1); byte[] sampleKeystore1 = Base64.decode(TEST_KS1); keystore = File.createTempFile("SecureAcceptAllGetTest", ".keystore"); truststore = File.createTempFile("SecureAcceptAllGetTest", ".truststore"); FileOutputStream keystoreFileOut = new FileOutputStream(keystore); try { keystoreFileOut.write(sampleKeystore1); } finally { keystoreFileOut.close(); } FileOutputStream truststoreFileOut = new FileOutputStream(truststore); try { truststoreFileOut.write(sampleTruststore1); } finally { truststoreFileOut.close(); } KeyStore ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream(keystore), PASSWORD.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, PASSWORD.toCharArray()); KeyStore ts = KeyStore.getInstance("JKS"); ts.load(new FileInputStream(truststore), PASSWORD.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ts); SSLContext sc = SSLContext.getInstance("TLS"); sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); HttpsServer secureServer = HttpsServer.create(inetSocketAddress, 0); secureServer.setHttpsConfigurator(new HttpsConfigurator(sc) { public void configure (HttpsParameters params) { SSLContext c = getSSLContext(); SSLParameters sslparams = c.getDefaultSSLParameters(); params.setSSLParameters(sslparams); } }); server = secureServer; } else { server = HttpServer.create(inetSocketAddress, 0); } server.setExecutor(service); for (Entry<String, HttpHandler> handler : handlers.entrySet()) { server.createContext(handler.getKey(), handler.getValue()); } server.start(); localHttpServerPort = server.getAddress().getPort(); System.out.println(description.getClassName() + " TestServer is started: " + getServerUrl()); } public void after(final Description description) { try{ server.stop(0); ((ExecutorService) server.getExecutor()).shutdownNow(); System.out.println(description.getClassName() + " TestServer is shutdown: " + getServerUrl()); } catch (Exception e) { e.printStackTrace(); } } /** * @return Get the root server URL */ public String getServerUrl() { if (hasSsl) { return "https://localhost:" + localHttpServerPort; } else { return "http://localhost:" + localHttpServerPort; } } /** * @return Get the root server URL * @throws URISyntaxException */ public URI getServerURI() throws URISyntaxException { return new URI(getServerUrl()); } /** * @param path * @return Get a path to this server */ public String getServerPath(String path) { return getServerUrl() + path; } /** * @param path * @return Get a path to this server */ public URI getServerPathURI(String path) throws URISyntaxException { return new URI(getServerUrl() + path); } /** * @return Return the ephemeral port used by this server */ public int getServerPort() { return localHttpServerPort; } public File getKeyStore() { return keystore; } public File getTrustStore() { return truststore; } }
7,006
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/PollingServerListUpdater.java
package com.netflix.loadbalancer; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * A default strategy for the dynamic server list updater to update. * (refactored and moved here from {@link com.netflix.loadbalancer.DynamicServerListLoadBalancer}) * * @author David Liu */ public class PollingServerListUpdater implements ServerListUpdater { private static final Logger logger = LoggerFactory.getLogger(PollingServerListUpdater.class); private static long LISTOFSERVERS_CACHE_UPDATE_DELAY = 1000; // msecs; private static int LISTOFSERVERS_CACHE_REPEAT_INTERVAL = 30 * 1000; // msecs; private static int POOL_SIZE = 2; private static class LazyHolder { static ScheduledExecutorService _serverListRefreshExecutor = null; static { _serverListRefreshExecutor = Executors.newScheduledThreadPool(POOL_SIZE, new ThreadFactoryBuilder() .setNameFormat("PollingServerListUpdater-%d") .setDaemon(true) .build()); } } private static ScheduledExecutorService getRefreshExecutor() { return LazyHolder._serverListRefreshExecutor; } private final AtomicBoolean isActive = new AtomicBoolean(false); private volatile long lastUpdated = System.currentTimeMillis(); private final long initialDelayMs; private final long refreshIntervalMs; private volatile ScheduledFuture<?> scheduledFuture; public PollingServerListUpdater() { this(LISTOFSERVERS_CACHE_UPDATE_DELAY, LISTOFSERVERS_CACHE_REPEAT_INTERVAL); } public PollingServerListUpdater(IClientConfig clientConfig) { this(LISTOFSERVERS_CACHE_UPDATE_DELAY, getRefreshIntervalMs(clientConfig)); } public PollingServerListUpdater(final long initialDelayMs, final long refreshIntervalMs) { this.initialDelayMs = initialDelayMs; this.refreshIntervalMs = refreshIntervalMs; } @Override public synchronized void start(final UpdateAction updateAction) { if (isActive.compareAndSet(false, true)) { final Runnable wrapperRunnable = () -> { if (!isActive.get()) { if (scheduledFuture != null) { scheduledFuture.cancel(true); } return; } try { updateAction.doUpdate(); lastUpdated = System.currentTimeMillis(); } catch (Exception e) { logger.warn("Failed one update cycle", e); } }; scheduledFuture = getRefreshExecutor().scheduleWithFixedDelay( wrapperRunnable, initialDelayMs, refreshIntervalMs, TimeUnit.MILLISECONDS ); } else { logger.info("Already active, no-op"); } } @Override public synchronized void stop() { if (isActive.compareAndSet(true, false)) { if (scheduledFuture != null) { scheduledFuture.cancel(true); } } else { logger.info("Not active, no-op"); } } @Override public String getLastUpdate() { return new Date(lastUpdated).toString(); } @Override public long getDurationSinceLastUpdateMs() { return System.currentTimeMillis() - lastUpdated; } @Override public int getNumberMissedCycles() { if (!isActive.get()) { return 0; } return (int) ((int) (System.currentTimeMillis() - lastUpdated) / refreshIntervalMs); } @Override public int getCoreThreads() { return POOL_SIZE; } private static long getRefreshIntervalMs(IClientConfig clientConfig) { return clientConfig.get(CommonClientConfigKey.ServerListRefreshInterval, LISTOFSERVERS_CACHE_REPEAT_INTERVAL); } }
7,007
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/DummyPing.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.loadbalancer; import com.netflix.client.config.IClientConfig; /** * Default simple implementation that marks the liveness of a Server * * @author stonse * */ public class DummyPing extends AbstractLoadBalancerPing { public DummyPing() { } public boolean isAlive(Server server) { return true; } }
7,008
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ServerListSubsetFilter.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.loadbalancer; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.netflix.client.IClientConfigAware; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import com.netflix.client.config.Property; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Random; import java.util.Set; /** * A server list filter that limits the number of the servers used by the load balancer to be the subset of all servers. * This is useful if the server farm is large (e.g., in the hundreds) and making use of every one of them * and keeping the connections in http client's connection pool is unnecessary. It also has the capability of eviction * of relatively unhealthy servers by comparing the total network failures and concurrent connections. * * @author awang * * @param <T> */ public class ServerListSubsetFilter<T extends Server> extends ZoneAffinityServerListFilter<T> implements IClientConfigAware, Comparator<T>{ private Random random = new Random(); private volatile Set<T> currentSubset = Sets.newHashSet(); private Property<Integer> sizeProp; private Property<Float> eliminationPercent; private Property<Integer> eliminationFailureCountThreshold; private Property<Integer> eliminationConnectionCountThreshold; private static final IClientConfigKey<Integer> SIZE = new CommonClientConfigKey<Integer>("ServerListSubsetFilter.size", 20) {}; private static final IClientConfigKey<Float> FORCE_ELIMINATE_PERCENT = new CommonClientConfigKey<Float>("ServerListSubsetFilter.forceEliminatePercent", 0.1f) {}; private static final IClientConfigKey<Integer> ELIMINATION_FAILURE_THRESHOLD = new CommonClientConfigKey<Integer>("ServerListSubsetFilter.eliminationFailureThresold", 0) {}; private static final IClientConfigKey<Integer> ELIMINATION_CONNECTION_THRESHOLD = new CommonClientConfigKey<Integer>("ServerListSubsetFilter.eliminationConnectionThresold", 0) {}; /** * @deprecated ServerListSubsetFilter should only be created with an IClientConfig. See {@link ServerListSubsetFilter#ServerListSubsetFilter(IClientConfig)} */ @Deprecated public ServerListSubsetFilter() { sizeProp = Property.of(SIZE.defaultValue()); eliminationPercent = Property.of(FORCE_ELIMINATE_PERCENT.defaultValue()); eliminationFailureCountThreshold = Property.of(ELIMINATION_FAILURE_THRESHOLD.defaultValue()); eliminationConnectionCountThreshold = Property.of(ELIMINATION_CONNECTION_THRESHOLD.defaultValue()); } public ServerListSubsetFilter(IClientConfig clientConfig) { super(clientConfig); initWithNiwsConfig(clientConfig); } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { sizeProp = clientConfig.getDynamicProperty(SIZE); eliminationPercent = clientConfig.getDynamicProperty(FORCE_ELIMINATE_PERCENT); eliminationFailureCountThreshold = clientConfig.getDynamicProperty(ELIMINATION_FAILURE_THRESHOLD); eliminationConnectionCountThreshold = clientConfig.getDynamicProperty(ELIMINATION_CONNECTION_THRESHOLD); } /** * Given all the servers, keep only a stable subset of servers to use. This method * keeps the current list of subset in use and keep returning the same list, with exceptions * to relatively unhealthy servers, which are defined as the following: * <p> * <ul> * <li>Servers with their concurrent connection count exceeding the client configuration for * {@code <clientName>.<nameSpace>.ServerListSubsetFilter.eliminationConnectionThresold} (default is 0) * <li>Servers with their failure count exceeding the client configuration for * {@code <clientName>.<nameSpace>.ServerListSubsetFilter.eliminationFailureThresold} (default is 0) * <li>If the servers evicted above is less than the forced eviction percentage as defined by client configuration * {@code <clientName>.<nameSpace>.ServerListSubsetFilter.forceEliminatePercent} (default is 10%, or 0.1), the * remaining servers will be sorted by their health status and servers will worst health status will be * forced evicted. * </ul> * <p> * After the elimination, new servers will be randomly chosen from all servers pool to keep the * number of the subset unchanged. * */ @Override public List<T> getFilteredListOfServers(List<T> servers) { List<T> zoneAffinityFiltered = super.getFilteredListOfServers(servers); Set<T> candidates = Sets.newHashSet(zoneAffinityFiltered); Set<T> newSubSet = Sets.newHashSet(currentSubset); LoadBalancerStats lbStats = getLoadBalancerStats(); for (T server: currentSubset) { // this server is either down or out of service if (!candidates.contains(server)) { newSubSet.remove(server); } else { ServerStats stats = lbStats.getSingleServerStat(server); // remove the servers that do not meet health criteria if (stats.getActiveRequestsCount() > eliminationConnectionCountThreshold.getOrDefault() || stats.getFailureCount() > eliminationFailureCountThreshold.getOrDefault()) { newSubSet.remove(server); // also remove from the general pool to avoid selecting them again candidates.remove(server); } } } int targetedListSize = sizeProp.getOrDefault(); int numEliminated = currentSubset.size() - newSubSet.size(); int minElimination = (int) (targetedListSize * eliminationPercent.getOrDefault()); int numToForceEliminate = 0; if (targetedListSize < newSubSet.size()) { // size is shrinking numToForceEliminate = newSubSet.size() - targetedListSize; } else if (minElimination > numEliminated) { numToForceEliminate = minElimination - numEliminated; } if (numToForceEliminate > newSubSet.size()) { numToForceEliminate = newSubSet.size(); } if (numToForceEliminate > 0) { List<T> sortedSubSet = Lists.newArrayList(newSubSet); Collections.sort(sortedSubSet, this); List<T> forceEliminated = sortedSubSet.subList(0, numToForceEliminate); newSubSet.removeAll(forceEliminated); candidates.removeAll(forceEliminated); } // after forced elimination or elimination of unhealthy instances, // the size of the set may be less than the targeted size, // then we just randomly add servers from the big pool if (newSubSet.size() < targetedListSize) { int numToChoose = targetedListSize - newSubSet.size(); candidates.removeAll(newSubSet); if (numToChoose > candidates.size()) { // Not enough healthy instances to choose, fallback to use the // total server pool candidates = Sets.newHashSet(zoneAffinityFiltered); candidates.removeAll(newSubSet); } List<T> chosen = randomChoose(Lists.newArrayList(candidates), numToChoose); for (T server: chosen) { newSubSet.add(server); } } currentSubset = newSubSet; return Lists.newArrayList(newSubSet); } /** * Randomly shuffle the beginning portion of server list (according to the number passed into the method) * and return them. * * @param servers * @param toChoose * @return */ private List<T> randomChoose(List<T> servers, int toChoose) { int size = servers.size(); if (toChoose >= size || toChoose < 0) { return servers; } for (int i = 0; i < toChoose; i++) { int index = random.nextInt(size); T tmp = servers.get(index); servers.set(index, servers.get(i)); servers.set(i, tmp); } return servers.subList(0, toChoose); } /** * Function to sort the list by server health condition, with * unhealthy servers before healthy servers. The servers are first sorted by * failures count, and then concurrent connection count. */ @Override public int compare(T server1, T server2) { LoadBalancerStats lbStats = getLoadBalancerStats(); ServerStats stats1 = lbStats.getSingleServerStat(server1); ServerStats stats2 = lbStats.getSingleServerStat(server2); int failuresDiff = (int) (stats2.getFailureCount() - stats1.getFailureCount()); if (failuresDiff != 0) { return failuresDiff; } else { return (stats2.getActiveRequestsCount() - stats1.getActiveRequestsCount()); } } }
7,009
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/NoOpLoadBalancer.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.loadbalancer; import java.util.Collections; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A noOp Loadbalancer * i.e. doesnt do anything "loadbalancer like" * * @author stonse * */ public class NoOpLoadBalancer extends AbstractLoadBalancer { static final Logger logger = LoggerFactory.getLogger(NoOpLoadBalancer.class); @Override public void addServers(List<Server> newServers) { logger.info("addServers to NoOpLoadBalancer ignored"); } @Override public Server chooseServer(Object key) { return null; } @Override public LoadBalancerStats getLoadBalancerStats() { return null; } @Override public List<Server> getServerList(ServerGroup serverGroup) { return Collections.emptyList(); } @Override public void markServerDown(Server server) { logger.info("markServerDown to NoOpLoadBalancer ignored"); } @Override public List<Server> getServerList(boolean availableOnly) { // TODO Auto-generated method stub return null; } @Override public List<Server> getReachableServers() { return null; } @Override public List<Server> getAllServers() { return null; } }
7,010
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/IPing.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.loadbalancer; /** * Interface that defines how we "ping" a server to check if its alive * @author stonse * */ public interface IPing { /** * Checks whether the given <code>Server</code> is "alive" i.e. should be * considered a candidate while loadbalancing * */ public boolean isAlive(Server server); }
7,011
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ZoneAffinityServerListFilter.java
package com.netflix.loadbalancer; /* * * 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. * */ import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.netflix.client.IClientConfigAware; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import com.netflix.client.config.Property; import com.netflix.servo.monitor.Counter; import com.netflix.servo.monitor.Monitors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; /** * This server list filter deals with filtering out servers based on the Zone affinity. * This filtering will be turned on if either {@link CommonClientConfigKey#EnableZoneAffinity} * or {@link CommonClientConfigKey#EnableZoneExclusivity} is set to true in {@link IClientConfig} object * passed into this class during initialization. When turned on, servers outside the same zone (as * indicated by {@link Server#getZone()}) will be filtered out. By default, zone affinity * and exclusivity are turned off and nothing is filtered out. * * @author stonse * */ public class ZoneAffinityServerListFilter<T extends Server> extends AbstractServerListFilter<T> implements IClientConfigAware { private static IClientConfigKey<String> ZONE = new CommonClientConfigKey<String>("@zone", "") {}; private static IClientConfigKey<Double> MAX_LOAD_PER_SERVER = new CommonClientConfigKey<Double>("zoneAffinity.maxLoadPerServer", 0.6d) {}; private static IClientConfigKey<Double> MAX_BLACKOUT_SERVER_PERCENTAGE = new CommonClientConfigKey<Double>("zoneAffinity.maxBlackOutServesrPercentage", 0.8d) {}; private static IClientConfigKey<Integer> MIN_AVAILABLE_SERVERS = new CommonClientConfigKey<Integer>("zoneAffinity.minAvailableServers", 2) {}; private boolean zoneAffinity; private boolean zoneExclusive; private Property<Double> activeReqeustsPerServerThreshold; private Property<Double> blackOutServerPercentageThreshold; private Property<Integer> availableServersThreshold; private Counter overrideCounter; private ZoneAffinityPredicate zoneAffinityPredicate; private static Logger logger = LoggerFactory.getLogger(ZoneAffinityServerListFilter.class); private String zone; /** * @deprecated Must pass in a config via {@link ZoneAffinityServerListFilter#ZoneAffinityServerListFilter(IClientConfig)} */ @Deprecated public ZoneAffinityServerListFilter() { } public ZoneAffinityServerListFilter(IClientConfig niwsClientConfig) { initWithNiwsConfig(niwsClientConfig); } @Override public void initWithNiwsConfig(IClientConfig niwsClientConfig) { zoneAffinity = niwsClientConfig.getOrDefault(CommonClientConfigKey.EnableZoneAffinity); zoneExclusive = niwsClientConfig.getOrDefault(CommonClientConfigKey.EnableZoneExclusivity); zone = niwsClientConfig.getGlobalProperty(ZONE).getOrDefault(); zoneAffinityPredicate = new ZoneAffinityPredicate(zone); activeReqeustsPerServerThreshold = niwsClientConfig.getDynamicProperty(MAX_LOAD_PER_SERVER); blackOutServerPercentageThreshold = niwsClientConfig.getDynamicProperty(MAX_BLACKOUT_SERVER_PERCENTAGE); availableServersThreshold = niwsClientConfig.getDynamicProperty(MIN_AVAILABLE_SERVERS); overrideCounter = Monitors.newCounter("ZoneAffinity_OverrideCounter"); Monitors.registerObject("NIWSServerListFilter_" + niwsClientConfig.getClientName()); } private boolean shouldEnableZoneAffinity(List<T> filtered) { if (!zoneAffinity && !zoneExclusive) { return false; } if (zoneExclusive) { return true; } LoadBalancerStats stats = getLoadBalancerStats(); if (stats == null) { return zoneAffinity; } else { logger.debug("Determining if zone affinity should be enabled with given server list: {}", filtered); ZoneSnapshot snapshot = stats.getZoneSnapshot(filtered); double loadPerServer = snapshot.getLoadPerServer(); int instanceCount = snapshot.getInstanceCount(); int circuitBreakerTrippedCount = snapshot.getCircuitTrippedCount(); if (((double) circuitBreakerTrippedCount) / instanceCount >= blackOutServerPercentageThreshold.getOrDefault() || loadPerServer >= activeReqeustsPerServerThreshold.getOrDefault() || (instanceCount - circuitBreakerTrippedCount) < availableServersThreshold.getOrDefault()) { logger.debug("zoneAffinity is overriden. blackOutServerPercentage: {}, activeReqeustsPerServer: {}, availableServers: {}", new Object[] {(double) circuitBreakerTrippedCount / instanceCount, loadPerServer, instanceCount - circuitBreakerTrippedCount}); return false; } else { return true; } } } @Override public List<T> getFilteredListOfServers(List<T> servers) { if (zone != null && (zoneAffinity || zoneExclusive) && servers !=null && servers.size() > 0){ List<T> filteredServers = Lists.newArrayList(Iterables.filter( servers, this.zoneAffinityPredicate.getServerOnlyPredicate())); if (shouldEnableZoneAffinity(filteredServers)) { return filteredServers; } else if (zoneAffinity) { overrideCounter.increment(); } } return servers; } @Override public String toString(){ StringBuilder sb = new StringBuilder("ZoneAffinityServerListFilter:"); sb.append(", zone: ").append(zone).append(", zoneAffinity:").append(zoneAffinity); sb.append(", zoneExclusivity:").append(zoneExclusive); return sb.toString(); } }
7,012
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/AvailabilityPredicate.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.loadbalancer; import com.google.common.base.Preconditions; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import com.netflix.client.config.Property; import javax.annotation.Nullable; /** * Predicate with the logic of filtering out circuit breaker tripped servers and servers * with too many concurrent connections from this client. * * @author awang * */ public class AvailabilityPredicate extends AbstractServerPredicate { private static final IClientConfigKey<Boolean> FILTER_CIRCUIT_TRIPPED = new CommonClientConfigKey<Boolean>( "niws.loadbalancer.availabilityFilteringRule.filterCircuitTripped", true) {}; private static final IClientConfigKey<Integer> DEFAULT_ACTIVE_CONNECTIONS_LIMIT = new CommonClientConfigKey<Integer>( "niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit", -1) {}; private static final IClientConfigKey<Integer> ACTIVE_CONNECTIONS_LIMIT = new CommonClientConfigKey<Integer>( "ActiveConnectionsLimit", -1) {}; private Property<Boolean> circuitBreakerFiltering = Property.of(FILTER_CIRCUIT_TRIPPED.defaultValue()); private Property<Integer> defaultActiveConnectionsLimit = Property.of(DEFAULT_ACTIVE_CONNECTIONS_LIMIT.defaultValue()); private Property<Integer> activeConnectionsLimit = Property.of(ACTIVE_CONNECTIONS_LIMIT.defaultValue()); public AvailabilityPredicate(IRule rule, IClientConfig clientConfig) { super(rule); initDynamicProperty(clientConfig); } public AvailabilityPredicate(LoadBalancerStats lbStats, IClientConfig clientConfig) { super(lbStats); initDynamicProperty(clientConfig); } AvailabilityPredicate(IRule rule) { super(rule); } private void initDynamicProperty(IClientConfig clientConfig) { if (clientConfig != null) { this.circuitBreakerFiltering = clientConfig.getGlobalProperty(FILTER_CIRCUIT_TRIPPED); this.defaultActiveConnectionsLimit = clientConfig.getGlobalProperty(DEFAULT_ACTIVE_CONNECTIONS_LIMIT); this.activeConnectionsLimit = clientConfig.getDynamicProperty(ACTIVE_CONNECTIONS_LIMIT); } } private int getActiveConnectionsLimit() { Integer limit = activeConnectionsLimit.getOrDefault(); if (limit == -1) { limit = defaultActiveConnectionsLimit.getOrDefault(); if (limit == -1) { limit = Integer.MAX_VALUE; } } return limit; } @Override public boolean apply(@Nullable PredicateKey input) { LoadBalancerStats stats = getLBStats(); if (stats == null) { return true; } return !shouldSkipServer(stats.getSingleServerStat(input.getServer())); } private boolean shouldSkipServer(ServerStats stats) { if ((circuitBreakerFiltering.getOrDefault() && stats.isCircuitBreakerTripped()) || stats.getActiveRequestsCount() >= getActiveConnectionsLimit()) { return true; } return false; } }
7,013
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/PredicateKey.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.loadbalancer; /** * The input object of predicates of class {@link AbstractServerPredicate}. * It includes Server and an Object as load balancer key used in {@link IRule#choose(Object)}, * which might be null. * * @author awang * */ public class PredicateKey { private Object loadBalancerKey; private Server server; public PredicateKey(Object loadBalancerKey, Server server) { this.loadBalancerKey = loadBalancerKey; this.server = server; } public PredicateKey(Server server) { this(null, server); } public final Object getLoadBalancerKey() { return loadBalancerKey; } public final Server getServer() { return server; } }
7,014
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/PredicateBasedRule.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.loadbalancer; import com.google.common.base.Optional; /** * A rule which delegates the server filtering logic to an instance of {@link AbstractServerPredicate}. * After filtering, a server is returned from filtered list in a round robin fashion. * * * @author awang * */ public abstract class PredicateBasedRule extends ClientConfigEnabledRoundRobinRule { /** * Method that provides an instance of {@link AbstractServerPredicate} to be used by this class. * */ public abstract AbstractServerPredicate getPredicate(); /** * Get a server by calling {@link AbstractServerPredicate#chooseRandomlyAfterFiltering(java.util.List, Object)}. * The performance for this method is O(n) where n is number of servers to be filtered. */ @Override public Server choose(Object key) { ILoadBalancer lb = getLoadBalancer(); Optional<Server> server = getPredicate().chooseRoundRobinAfterFiltering(lb.getAllServers(), key); if (server.isPresent()) { return server.get(); } else { return null; } } }
7,015
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/AbstractLoadBalancer.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.loadbalancer; import java.util.List; /** * AbstractLoadBalancer contains features required for most loadbalancing * implementations. * * An anatomy of a typical LoadBalancer consists of 1. A List of Servers (nodes) * that are potentially bucketed based on a specific criteria. 2. A Class that * defines and implements a LoadBalacing Strategy via <code>IRule</code> 3. A * Class that defines and implements a mechanism to determine the * suitability/availability of the nodes/servers in the List. * * * @author stonse * */ public abstract class AbstractLoadBalancer implements ILoadBalancer { public enum ServerGroup{ ALL, STATUS_UP, STATUS_NOT_UP } /** * delegate to {@link #chooseServer(Object)} with parameter null. */ public Server chooseServer() { return chooseServer(null); } /** * List of servers that this Loadbalancer knows about * * @param serverGroup Servers grouped by status, e.g., {@link ServerGroup#STATUS_UP} */ public abstract List<Server> getServerList(ServerGroup serverGroup); /** * Obtain LoadBalancer related Statistics */ public abstract LoadBalancerStats getLoadBalancerStats(); }
7,016
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/RetryRule.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.loadbalancer; import com.netflix.client.config.IClientConfig; /** * Given that * {@link IRule} can be cascaded, this {@link RetryRule} class allows adding a retry logic to an existing Rule. * * @author stonse * */ public class RetryRule extends AbstractLoadBalancerRule { IRule subRule = new RoundRobinRule(); long maxRetryMillis = 500; public RetryRule() { } public RetryRule(IRule subRule) { this.subRule = (subRule != null) ? subRule : new RoundRobinRule(); } public RetryRule(IRule subRule, long maxRetryMillis) { this.subRule = (subRule != null) ? subRule : new RoundRobinRule(); this.maxRetryMillis = (maxRetryMillis > 0) ? maxRetryMillis : 500; } public void setRule(IRule subRule) { this.subRule = (subRule != null) ? subRule : new RoundRobinRule(); } public IRule getRule() { return subRule; } public void setMaxRetryMillis(long maxRetryMillis) { if (maxRetryMillis > 0) { this.maxRetryMillis = maxRetryMillis; } else { this.maxRetryMillis = 500; } } public long getMaxRetryMillis() { return maxRetryMillis; } @Override public void setLoadBalancer(ILoadBalancer lb) { super.setLoadBalancer(lb); subRule.setLoadBalancer(lb); } /* * Loop if necessary. Note that the time CAN be exceeded depending on the * subRule, because we're not spawning additional threads and returning * early. */ public Server choose(ILoadBalancer lb, Object key) { long requestTime = System.currentTimeMillis(); long deadline = requestTime + maxRetryMillis; Server answer = null; answer = subRule.choose(key); if (((answer == null) || (!answer.isAlive())) && (System.currentTimeMillis() < deadline)) { InterruptTask task = new InterruptTask(deadline - System.currentTimeMillis()); while (!Thread.interrupted()) { answer = subRule.choose(key); if (((answer == null) || (!answer.isAlive())) && (System.currentTimeMillis() < deadline)) { /* pause and retry hoping it's transient */ Thread.yield(); } else { break; } } task.cancel(); } if ((answer == null) || (!answer.isAlive())) { return null; } else { return answer; } } @Override public Server choose(Object key) { return choose(getLoadBalancer(), key); } }
7,017
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/InterruptTask.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.loadbalancer; import java.util.Timer; import java.util.TimerTask; public class InterruptTask extends TimerTask { static Timer timer = new Timer("InterruptTimer", true); protected Thread target = null; public InterruptTask(long millis) { target = Thread.currentThread(); timer.schedule(this, millis); } /* Auto-scheduling constructor */ public InterruptTask(Thread target, long millis) { this.target = target; timer.schedule(this, millis); } public boolean cancel() { try { /* This shouldn't throw exceptions, but... */ return super.cancel(); } catch (Exception e) { return false; } } public void run() { if ((target != null) && (target.isAlive())) { target.interrupt(); } } }
7,018
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/WeightedResponseTimeRule.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.loadbalancer; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicBoolean; /** * Rule that use the average/percentile response times * to assign dynamic "weights" per Server which is then used in * the "Weighted Round Robin" fashion. * <p> * The basic idea for weighted round robin has been obtained from JCS * The implementation for choosing the endpoint from the list of endpoints * is as follows:Let's assume 4 endpoints:A(wt=10), B(wt=30), C(wt=40), * D(wt=20). * <p> * Using the Random API, generate a random number between 1 and10+30+40+20. * Let's assume that the above list is randomized. Based on the weights, we * have intervals as follows: * <p> * 1-----10 (A's weight) * <br> * 11----40 (A's weight + B's weight) * <br> * 41----80 (A's weight + B's weight + C's weight) * <br> * 81----100(A's weight + B's weight + C's weight + C's weight) * <p> * Here's the psuedo code for deciding where to send the request: * <p> * if (random_number between 1 &amp; 10) {send request to A;} * <br> * else if (random_number between 11 &amp; 40) {send request to B;} * <br> * else if (random_number between 41 &amp; 80) {send request to C;} * <br> * else if (random_number between 81 &amp; 100) {send request to D;} * <p> * When there is not enough statistics gathered for the servers, this rule * will fall back to use {@link RoundRobinRule}. * @author stonse */ public class WeightedResponseTimeRule extends RoundRobinRule { public static final IClientConfigKey<Integer> WEIGHT_TASK_TIMER_INTERVAL_CONFIG_KEY = new IClientConfigKey<Integer>() { @Override public String key() { return "ServerWeightTaskTimerInterval"; } @Override public String toString() { return key(); } @Override public Class<Integer> type() { return Integer.class; } }; public static final int DEFAULT_TIMER_INTERVAL = 30 * 1000; private int serverWeightTaskTimerInterval = DEFAULT_TIMER_INTERVAL; private static final Logger logger = LoggerFactory.getLogger(WeightedResponseTimeRule.class); // holds the accumulated weight from index 0 to current index // for example, element at index 2 holds the sum of weight of servers from 0 to 2 private volatile List<Double> accumulatedWeights = new ArrayList<Double>(); private final Random random = new Random(); protected Timer serverWeightTimer = null; protected AtomicBoolean serverWeightAssignmentInProgress = new AtomicBoolean(false); String name = "unknown"; public WeightedResponseTimeRule() { super(); } public WeightedResponseTimeRule(ILoadBalancer lb) { super(lb); } @Override public void setLoadBalancer(ILoadBalancer lb) { super.setLoadBalancer(lb); if (lb instanceof BaseLoadBalancer) { name = ((BaseLoadBalancer) lb).getName(); } initialize(lb); } void initialize(ILoadBalancer lb) { if (serverWeightTimer != null) { serverWeightTimer.cancel(); } serverWeightTimer = new Timer("NFLoadBalancer-serverWeightTimer-" + name, true); serverWeightTimer.schedule(new DynamicServerWeightTask(), 0, serverWeightTaskTimerInterval); // do a initial run ServerWeight sw = new ServerWeight(); sw.maintainWeights(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { logger .info("Stopping NFLoadBalancer-serverWeightTimer-" + name); serverWeightTimer.cancel(); } })); } public void shutdown() { if (serverWeightTimer != null) { logger.info("Stopping NFLoadBalancer-serverWeightTimer-" + name); serverWeightTimer.cancel(); } } List<Double> getAccumulatedWeights() { return Collections.unmodifiableList(accumulatedWeights); } @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE") @Override public Server choose(ILoadBalancer lb, Object key) { if (lb == null) { return null; } Server server = null; while (server == null) { // get hold of the current reference in case it is changed from the other thread List<Double> currentWeights = accumulatedWeights; if (Thread.interrupted()) { return null; } List<Server> allList = lb.getAllServers(); int serverCount = allList.size(); if (serverCount == 0) { return null; } int serverIndex = 0; // last one in the list is the sum of all weights double maxTotalWeight = currentWeights.size() == 0 ? 0 : currentWeights.get(currentWeights.size() - 1); // No server has been hit yet and total weight is not initialized // fallback to use round robin if (maxTotalWeight < 0.001d || serverCount != currentWeights.size()) { server = super.choose(getLoadBalancer(), key); if(server == null) { return server; } } else { // generate a random weight between 0 (inclusive) to maxTotalWeight (exclusive) double randomWeight = random.nextDouble() * maxTotalWeight; // pick the server index based on the randomIndex int n = 0; for (Double d : currentWeights) { if (d >= randomWeight) { serverIndex = n; break; } else { n++; } } server = allList.get(serverIndex); } if (server == null) { /* Transient. */ Thread.yield(); continue; } if (server.isAlive()) { return (server); } // Next. server = null; } return server; } class DynamicServerWeightTask extends TimerTask { public void run() { ServerWeight serverWeight = new ServerWeight(); try { serverWeight.maintainWeights(); } catch (Exception e) { logger.error("Error running DynamicServerWeightTask for {}", name, e); } } } class ServerWeight { public void maintainWeights() { ILoadBalancer lb = getLoadBalancer(); if (lb == null) { return; } if (!serverWeightAssignmentInProgress.compareAndSet(false, true)) { return; } try { logger.info("Weight adjusting job started"); AbstractLoadBalancer nlb = (AbstractLoadBalancer) lb; LoadBalancerStats stats = nlb.getLoadBalancerStats(); if (stats == null) { // no statistics, nothing to do return; } double totalResponseTime = 0; // find maximal 95% response time for (Server server : nlb.getAllServers()) { // this will automatically load the stats if not in cache ServerStats ss = stats.getSingleServerStat(server); totalResponseTime += ss.getResponseTimeAvg(); } // weight for each server is (sum of responseTime of all servers - responseTime) // so that the longer the response time, the less the weight and the less likely to be chosen Double weightSoFar = 0.0; // create new list and hot swap the reference List<Double> finalWeights = new ArrayList<Double>(); for (Server server : nlb.getAllServers()) { ServerStats ss = stats.getSingleServerStat(server); double weight = totalResponseTime - ss.getResponseTimeAvg(); weightSoFar += weight; finalWeights.add(weightSoFar); } setWeights(finalWeights); } catch (Exception e) { logger.error("Error calculating server weights", e); } finally { serverWeightAssignmentInProgress.set(false); } } } void setWeights(List<Double> weights) { this.accumulatedWeights = weights; } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { super.initWithNiwsConfig(clientConfig); serverWeightTaskTimerInterval = clientConfig.get(WEIGHT_TASK_TIMER_INTERVAL_CONFIG_KEY, DEFAULT_TIMER_INTERVAL); } }
7,019
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/CompositePredicate.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.loadbalancer; import java.util.Iterator; import java.util.List; import javax.annotation.Nullable; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Lists; /** * A predicate that is composed from one or more predicates in "AND" relationship. * It also has the functionality of "fallback" to one of more different predicates. * If the primary predicate yield too few filtered servers from the {@link #getEligibleServers(List, Object)} * API, it will try the fallback predicates one by one, until the number of filtered servers * exceeds certain number threshold or percentage threshold. * * @author awang * */ public class CompositePredicate extends AbstractServerPredicate { private AbstractServerPredicate delegate; private List<AbstractServerPredicate> fallbacks = Lists.newArrayList(); private int minimalFilteredServers = 1; private float minimalFilteredPercentage = 0; @Override public boolean apply(@Nullable PredicateKey input) { return delegate.apply(input); } public static class Builder { private CompositePredicate toBuild; Builder(AbstractServerPredicate primaryPredicate) { toBuild = new CompositePredicate(); toBuild.delegate = primaryPredicate; } Builder(AbstractServerPredicate ...primaryPredicates) { toBuild = new CompositePredicate(); Predicate<PredicateKey> chain = Predicates.<PredicateKey>and(primaryPredicates); toBuild.delegate = AbstractServerPredicate.ofKeyPredicate(chain); } public Builder addFallbackPredicate(AbstractServerPredicate fallback) { toBuild.fallbacks.add(fallback); return this; } public Builder setFallbackThresholdAsMinimalFilteredNumberOfServers(int number) { toBuild.minimalFilteredServers = number; return this; } public Builder setFallbackThresholdAsMinimalFilteredPercentage(float percent) { toBuild.minimalFilteredPercentage = percent; return this; } public CompositePredicate build() { return toBuild; } } public static Builder withPredicates(AbstractServerPredicate ...primaryPredicates) { return new Builder(primaryPredicates); } public static Builder withPredicate(AbstractServerPredicate primaryPredicate) { return new Builder(primaryPredicate); } /** * Get the filtered servers from primary predicate, and if the number of the filtered servers * are not enough, trying the fallback predicates */ @Override public List<Server> getEligibleServers(List<Server> servers, Object loadBalancerKey) { List<Server> result = super.getEligibleServers(servers, loadBalancerKey); Iterator<AbstractServerPredicate> i = fallbacks.iterator(); while (!(result.size() >= minimalFilteredServers && result.size() > (int) (servers.size() * minimalFilteredPercentage)) && i.hasNext()) { AbstractServerPredicate predicate = i.next(); result = predicate.getEligibleServers(servers, loadBalancerKey); } return result; } }
7,020
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ServerList.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.loadbalancer; import java.util.List; /** * Interface that defines the methods sed to obtain the List of Servers * @author stonse * * @param <T> */ public interface ServerList<T extends Server> { public List<T> getInitialListOfServers(); /** * Return updated list of servers. This is called say every 30 secs * (configurable) by the Loadbalancer's Ping cycle * */ public List<T> getUpdatedListOfServers(); }
7,021
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ILoadBalancer.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.loadbalancer; import java.util.List; /** * Interface that defines the operations for a software loadbalancer. A typical * loadbalancer minimally need a set of servers to loadbalance for, a method to * mark a particular server to be out of rotation and a call that will choose a * server from the existing list of server. * * @author stonse * */ public interface ILoadBalancer { /** * Initial list of servers. * This API also serves to add additional ones at a later time * The same logical server (host:port) could essentially be added multiple times * (helpful in cases where you want to give more "weightage" perhaps ..) * * @param newServers new servers to add */ public void addServers(List<Server> newServers); /** * Choose a server from load balancer. * * @param key An object that the load balancer may use to determine which server to return. null if * the load balancer does not use this parameter. * @return server chosen */ public Server chooseServer(Object key); /** * To be called by the clients of the load balancer to notify that a Server is down * else, the LB will think its still Alive until the next Ping cycle - potentially * (assuming that the LB Impl does a ping) * * @param server Server to mark as down */ public void markServerDown(Server server); /** * @deprecated 2016-01-20 This method is deprecated in favor of the * cleaner {@link #getReachableServers} (equivalent to availableOnly=true) * and {@link #getAllServers} API (equivalent to availableOnly=false). * * Get the current list of servers. * * @param availableOnly if true, only live and available servers should be returned */ @Deprecated public List<Server> getServerList(boolean availableOnly); /** * @return Only the servers that are up and reachable. */ public List<Server> getReachableServers(); /** * @return All known servers, both reachable and unreachable. */ public List<Server> getAllServers(); }
7,022
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/RandomRule.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.loadbalancer; import com.netflix.client.config.IClientConfig; import java.util.List; import java.util.concurrent.ThreadLocalRandom; /** * A loadbalacing strategy that randomly distributes traffic amongst existing * servers. * * @author stonse * */ public class RandomRule extends AbstractLoadBalancerRule { /** * Randomly choose from all living servers */ @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE") public Server choose(ILoadBalancer lb, Object key) { if (lb == null) { return null; } Server server = null; while (server == null) { if (Thread.interrupted()) { return null; } List<Server> upList = lb.getReachableServers(); List<Server> allList = lb.getAllServers(); int serverCount = allList.size(); if (serverCount == 0) { /* * No servers. End regardless of pass, because subsequent passes * only get more restrictive. */ return null; } int index = chooseRandomInt(serverCount); server = upList.get(index); if (server == null) { /* * The only time this should happen is if the server list were * somehow trimmed. This is a transient condition. Retry after * yielding. */ Thread.yield(); continue; } if (server.isAlive()) { return (server); } // Shouldn't actually happen.. but must be transient or a bug. server = null; Thread.yield(); } return server; } protected int chooseRandomInt(int serverCount) { return ThreadLocalRandom.current().nextInt(serverCount); } @Override public Server choose(Object key) { return choose(getLoadBalancer(), key); } }
7,023
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ResponseTimeWeightedRule.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.loadbalancer; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; /** * Rule that use the average/percentile response times * to assign dynamic "weights" per Server which is then used in * the "Weighted Round Robin" fashion. * <p> * The basic idea for weighted round robin has been obtained from JCS * The implementation for choosing the endpoint from the list of endpoints * is as follows:Let's assume 4 endpoints:A(wt=10), B(wt=30), C(wt=40), * D(wt=20). * <p> * Using the Random API, generate a random number between 1 and10+30+40+20. * Let's assume that the above list is randomized. Based on the weights, we * have intervals as follows: * <p> * 1-----10 (A's weight) * <br> * 11----40 (A's weight + B's weight) * <br> * 41----80 (A's weight + B's weight + C's weight) * <br> * 81----100(A's weight + B's weight + C's weight + C's weight) * <p> * Here's the psuedo code for deciding where to send the request: * <p> * if (random_number between 1 &amp; 10) {send request to A;} * <br> * else if (random_number between 11 &amp; 40) {send request to B;} * <br> * else if (random_number between 41 &amp; 80) {send request to C;} * <br> * else if (random_number between 81 &amp; 100) {send request to D;} * <p> * When there is not enough statistics gathered for the servers, this rule * will fall back to use {@link RoundRobinRule}. * @author stonse * * @deprecated Use {@link WeightedResponseTimeRule} * * @see WeightedResponseTimeRule * */ public class ResponseTimeWeightedRule extends RoundRobinRule { public static final IClientConfigKey<Integer> WEIGHT_TASK_TIMER_INTERVAL_CONFIG_KEY = WeightedResponseTimeRule.WEIGHT_TASK_TIMER_INTERVAL_CONFIG_KEY; public static final int DEFAULT_TIMER_INTERVAL = 30 * 1000; private int serverWeightTaskTimerInterval = DEFAULT_TIMER_INTERVAL; private static final Logger logger = LoggerFactory.getLogger(ResponseTimeWeightedRule.class); // holds the accumulated weight from index 0 to current index // for example, element at index 2 holds the sum of weight of servers from 0 to 2 private volatile List<Double> accumulatedWeights = new ArrayList<Double>(); private final Random random = new Random(); protected Timer serverWeightTimer = null; protected AtomicBoolean serverWeightAssignmentInProgress = new AtomicBoolean(false); String name = "unknown"; public ResponseTimeWeightedRule() { super(); } public ResponseTimeWeightedRule(ILoadBalancer lb) { super(lb); } @Override public void setLoadBalancer(ILoadBalancer lb) { super.setLoadBalancer(lb); if (lb instanceof BaseLoadBalancer) { name = ((BaseLoadBalancer) lb).getName(); } initialize(lb); } void initialize(ILoadBalancer lb) { if (serverWeightTimer != null) { serverWeightTimer.cancel(); } serverWeightTimer = new Timer("NFLoadBalancer-serverWeightTimer-" + name, true); serverWeightTimer.schedule(new DynamicServerWeightTask(), 0, serverWeightTaskTimerInterval); // do a initial run ServerWeight sw = new ServerWeight(); sw.maintainWeights(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { logger.info("Stopping NFLoadBalancer-serverWeightTimer-{}", name); serverWeightTimer.cancel(); } })); } public void shutdown() { if (serverWeightTimer != null) { logger.info("Stopping NFLoadBalancer-serverWeightTimer-{}", name); serverWeightTimer.cancel(); } } @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE") @Override public Server choose(ILoadBalancer lb, Object key) { if (lb == null) { return null; } Server server = null; while (server == null) { // get hold of the current reference in case it is changed from the other thread List<Double> currentWeights = accumulatedWeights; if (Thread.interrupted()) { return null; } List<Server> allList = lb.getAllServers(); int serverCount = allList.size(); if (serverCount == 0) { return null; } int serverIndex = 0; // last one in the list is the sum of all weights double maxTotalWeight = currentWeights.size() == 0 ? 0 : currentWeights.get(currentWeights.size() - 1); // No server has been hit yet and total weight is not initialized // fallback to use round robin if (maxTotalWeight < 0.001d) { server = super.choose(getLoadBalancer(), key); } else { // generate a random weight between 0 (inclusive) to maxTotalWeight (exclusive) double randomWeight = random.nextDouble() * maxTotalWeight; // pick the server index based on the randomIndex int n = 0; for (Double d : currentWeights) { if (d >= randomWeight) { serverIndex = n; break; } else { n++; } } server = allList.get(serverIndex); } if (server == null) { /* Transient. */ Thread.yield(); continue; } if (server.isAlive()) { return (server); } // Next. server = null; } return server; } class DynamicServerWeightTask extends TimerTask { public void run() { ServerWeight serverWeight = new ServerWeight(); try { serverWeight.maintainWeights(); } catch (Exception e) { logger.error("Error running DynamicServerWeightTask for {}", name, e); } } } class ServerWeight { public void maintainWeights() { ILoadBalancer lb = getLoadBalancer(); if (lb == null) { return; } if (!serverWeightAssignmentInProgress.compareAndSet(false, true)) { return; } try { logger.info("Weight adjusting job started"); AbstractLoadBalancer nlb = (AbstractLoadBalancer) lb; LoadBalancerStats stats = nlb.getLoadBalancerStats(); if (stats == null) { // no statistics, nothing to do return; } double totalResponseTime = 0; // find maximal 95% response time for (Server server : nlb.getAllServers()) { // this will automatically load the stats if not in cache ServerStats ss = stats.getSingleServerStat(server); totalResponseTime += ss.getResponseTimeAvg(); } // weight for each server is (sum of responseTime of all servers - responseTime) // so that the longer the response time, the less the weight and the less likely to be chosen Double weightSoFar = 0.0; // create new list and hot swap the reference List<Double> finalWeights = new ArrayList<Double>(); for (Server server : nlb.getAllServers()) { ServerStats ss = stats.getSingleServerStat(server); double weight = totalResponseTime - ss.getResponseTimeAvg(); weightSoFar += weight; finalWeights.add(weightSoFar); } setWeights(finalWeights); } catch (Exception e) { logger.error("Error calculating server weights", e); } finally { serverWeightAssignmentInProgress.set(false); } } } void setWeights(List<Double> weights) { this.accumulatedWeights = weights; } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { super.initWithNiwsConfig(clientConfig); serverWeightTaskTimerInterval = clientConfig.get(WEIGHT_TASK_TIMER_INTERVAL_CONFIG_KEY, DEFAULT_TIMER_INTERVAL); } }
7,024
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ClientConfigEnabledRoundRobinRule.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.loadbalancer; import com.netflix.client.config.IClientConfig; /** * This class essentially contains the RoundRobinRule class defined in the * loadbalancer package * * @author stonse * */ public class ClientConfigEnabledRoundRobinRule extends AbstractLoadBalancerRule { RoundRobinRule roundRobinRule = new RoundRobinRule(); @Override public void initWithNiwsConfig(IClientConfig clientConfig) { roundRobinRule = new RoundRobinRule(); } @Override public void setLoadBalancer(ILoadBalancer lb) { super.setLoadBalancer(lb); roundRobinRule.setLoadBalancer(lb); } @Override public Server choose(Object key) { if (roundRobinRule != null) { return roundRobinRule.choose(key); } else { throw new IllegalArgumentException( "This class has not been initialized with the RoundRobinRule class"); } } }
7,025
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/BaseLoadBalancer.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.loadbalancer; import static java.util.Collections.singleton; import com.google.common.collect.ImmutableList; import com.netflix.client.ClientFactory; import com.netflix.client.IClientConfigAware; import com.netflix.client.PrimeConnections; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.annotations.Monitor; import com.netflix.servo.monitor.Counter; import com.netflix.servo.monitor.Monitors; import com.netflix.util.concurrent.ShutdownEnabledTimer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * A basic implementation of the load balancer where an arbitrary list of * servers can be set as the server pool. A ping can be set to determine the * liveness of a server. Internally, this class maintains an "all" server list * and an "up" server list and use them depending on what the caller asks for. * * @author stonse * */ public class BaseLoadBalancer extends AbstractLoadBalancer implements PrimeConnections.PrimeConnectionListener, IClientConfigAware { private static Logger logger = LoggerFactory.getLogger(BaseLoadBalancer.class); private final static IRule DEFAULT_RULE = new RoundRobinRule(); private final static SerialPingStrategy DEFAULT_PING_STRATEGY = new SerialPingStrategy(); private static final String DEFAULT_NAME = "default"; private static final String PREFIX = "LoadBalancer_"; protected IRule rule = DEFAULT_RULE; protected IPingStrategy pingStrategy = DEFAULT_PING_STRATEGY; protected IPing ping = null; @Monitor(name = PREFIX + "AllServerList", type = DataSourceType.INFORMATIONAL) protected volatile List<Server> allServerList = Collections .synchronizedList(new ArrayList<Server>()); @Monitor(name = PREFIX + "UpServerList", type = DataSourceType.INFORMATIONAL) protected volatile List<Server> upServerList = Collections .synchronizedList(new ArrayList<Server>()); protected ReadWriteLock allServerLock = new ReentrantReadWriteLock(); protected ReadWriteLock upServerLock = new ReentrantReadWriteLock(); protected String name = DEFAULT_NAME; protected Timer lbTimer = null; protected int pingIntervalSeconds = 10; protected int maxTotalPingTimeSeconds = 5; protected Comparator<Server> serverComparator = new ServerComparator(); protected AtomicBoolean pingInProgress = new AtomicBoolean(false); protected LoadBalancerStats lbStats; private volatile Counter counter = Monitors.newCounter("LoadBalancer_ChooseServer"); private PrimeConnections primeConnections; private volatile boolean enablePrimingConnections = false; private IClientConfig config; private List<ServerListChangeListener> changeListeners = new CopyOnWriteArrayList<ServerListChangeListener>(); private List<ServerStatusChangeListener> serverStatusListeners = new CopyOnWriteArrayList<ServerStatusChangeListener>(); /** * Default constructor which sets name as "default", sets null ping, and * {@link RoundRobinRule} as the rule. * <p> * This constructor is mainly used by {@link ClientFactory}. Calling this * constructor must be followed by calling {@link #init()} or * {@link #initWithNiwsConfig(IClientConfig)} to complete initialization. * This constructor is provided for reflection. When constructing * programatically, it is recommended to use other constructors. */ public BaseLoadBalancer() { this.name = DEFAULT_NAME; this.ping = null; setRule(DEFAULT_RULE); setupPingTask(); lbStats = new LoadBalancerStats(DEFAULT_NAME); } public BaseLoadBalancer(String lbName, IRule rule, LoadBalancerStats lbStats) { this(lbName, rule, lbStats, null); } public BaseLoadBalancer(IPing ping, IRule rule) { this(DEFAULT_NAME, rule, new LoadBalancerStats(DEFAULT_NAME), ping); } public BaseLoadBalancer(IPing ping, IRule rule, IPingStrategy pingStrategy) { this(DEFAULT_NAME, rule, new LoadBalancerStats(DEFAULT_NAME), ping, pingStrategy); } public BaseLoadBalancer(String name, IRule rule, LoadBalancerStats stats, IPing ping) { this(name, rule, stats, ping, DEFAULT_PING_STRATEGY); } public BaseLoadBalancer(String name, IRule rule, LoadBalancerStats stats, IPing ping, IPingStrategy pingStrategy) { logger.debug("LoadBalancer [{}]: initialized", name); this.name = name; this.ping = ping; this.pingStrategy = pingStrategy; setRule(rule); setupPingTask(); lbStats = stats; init(); } public BaseLoadBalancer(IClientConfig config) { initWithNiwsConfig(config); } public BaseLoadBalancer(IClientConfig config, IRule rule, IPing ping) { initWithConfig(config, rule, ping, createLoadBalancerStatsFromConfig(config, ClientFactory::instantiateInstanceWithClientConfig)); } void initWithConfig(IClientConfig clientConfig, IRule rule, IPing ping) { initWithConfig(clientConfig, rule, ping, createLoadBalancerStatsFromConfig(config, ClientFactory::instantiateInstanceWithClientConfig)); } void initWithConfig(IClientConfig clientConfig, IRule rule, IPing ping, LoadBalancerStats stats) { this.config = clientConfig; this.name = clientConfig.getClientName(); int pingIntervalTime = clientConfig.get(CommonClientConfigKey.NFLoadBalancerPingInterval, 30); int maxTotalPingTime = clientConfig.get(CommonClientConfigKey.NFLoadBalancerMaxTotalPingTime, 2); setPingInterval(pingIntervalTime); setMaxTotalPingTime(maxTotalPingTime); // cross associate with each other // i.e. Rule,Ping meet your container LB // LB, these are your Ping and Rule guys ... setRule(rule); setPing(ping); setLoadBalancerStats(stats); rule.setLoadBalancer(this); if (ping instanceof AbstractLoadBalancerPing) { ((AbstractLoadBalancerPing) ping).setLoadBalancer(this); } logger.info("Client: {} instantiated a LoadBalancer: {}", name, this); boolean enablePrimeConnections = clientConfig.getOrDefault(CommonClientConfigKey.EnablePrimeConnections); if (enablePrimeConnections) { this.setEnablePrimingConnections(true); PrimeConnections primeConnections = new PrimeConnections( this.getName(), clientConfig); this.setPrimeConnections(primeConnections); } init(); } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { try { initWithNiwsConfig(clientConfig, ClientFactory::instantiateInstanceWithClientConfig); } catch (Exception e) { throw new RuntimeException("Error initializing load balancer", e); } } @Override public void initWithNiwsConfig(IClientConfig clientConfig, Factory factory) { String ruleClassName = clientConfig.getOrDefault(CommonClientConfigKey.NFLoadBalancerRuleClassName); String pingClassName = clientConfig.getOrDefault(CommonClientConfigKey.NFLoadBalancerPingClassName); try { IRule rule = (IRule)factory.create(ruleClassName, clientConfig); IPing ping = (IPing)factory.create(pingClassName, clientConfig); LoadBalancerStats stats = createLoadBalancerStatsFromConfig(clientConfig, factory); initWithConfig(clientConfig, rule, ping, stats); } catch (Exception e) { throw new RuntimeException("Error initializing load balancer", e); } } private LoadBalancerStats createLoadBalancerStatsFromConfig(IClientConfig clientConfig, Factory factory) { String loadBalancerStatsClassName = clientConfig.getOrDefault(CommonClientConfigKey.NFLoadBalancerStatsClassName); try { return (LoadBalancerStats) factory.create(loadBalancerStatsClassName, clientConfig); } catch (Exception e) { throw new RuntimeException( "Error initializing configured LoadBalancerStats class - " + loadBalancerStatsClassName, e); } } public void addServerListChangeListener(ServerListChangeListener listener) { changeListeners.add(listener); } public void removeServerListChangeListener(ServerListChangeListener listener) { changeListeners.remove(listener); } public void addServerStatusChangeListener(ServerStatusChangeListener listener) { serverStatusListeners.add(listener); } public void removeServerStatusChangeListener(ServerStatusChangeListener listener) { serverStatusListeners.remove(listener); } public IClientConfig getClientConfig() { return config; } private boolean canSkipPing() { if (ping == null || ping.getClass().getName().equals(DummyPing.class.getName())) { // default ping, no need to set up timer return true; } else { return false; } } void setupPingTask() { if (canSkipPing()) { return; } if (lbTimer != null) { lbTimer.cancel(); } lbTimer = new ShutdownEnabledTimer("NFLoadBalancer-PingTimer-" + name, true); lbTimer.schedule(new PingTask(), 0, pingIntervalSeconds * 1000); forceQuickPing(); } /** * Set the name for the load balancer. This should not be called since name * should be immutable after initialization. Calling this method does not * guarantee that all other data structures that depend on this name will be * changed accordingly. */ void setName(String name) { // and register this.name = name; if (lbStats == null) { lbStats = new LoadBalancerStats(name); } else { lbStats.setName(name); } } public String getName() { return name; } @Override public LoadBalancerStats getLoadBalancerStats() { return lbStats; } public void setLoadBalancerStats(LoadBalancerStats lbStats) { this.lbStats = lbStats; } public Lock lockAllServerList(boolean write) { Lock aproposLock = write ? allServerLock.writeLock() : allServerLock .readLock(); aproposLock.lock(); return aproposLock; } public Lock lockUpServerList(boolean write) { Lock aproposLock = write ? upServerLock.writeLock() : upServerLock .readLock(); aproposLock.lock(); return aproposLock; } public void setPingInterval(int pingIntervalSeconds) { if (pingIntervalSeconds < 1) { return; } this.pingIntervalSeconds = pingIntervalSeconds; if (logger.isDebugEnabled()) { logger.debug("LoadBalancer [{}]: pingIntervalSeconds set to {}", name, this.pingIntervalSeconds); } setupPingTask(); // since ping data changed } public int getPingInterval() { return pingIntervalSeconds; } /* * Maximum time allowed for the ping cycle */ public void setMaxTotalPingTime(int maxTotalPingTimeSeconds) { if (maxTotalPingTimeSeconds < 1) { return; } this.maxTotalPingTimeSeconds = maxTotalPingTimeSeconds; logger.debug("LoadBalancer [{}]: maxTotalPingTime set to {}", name, this.maxTotalPingTimeSeconds); } public int getMaxTotalPingTime() { return maxTotalPingTimeSeconds; } public IPing getPing() { return ping; } public IRule getRule() { return rule; } public boolean isPingInProgress() { return pingInProgress.get(); } /* Specify the object which is used to send pings. */ public void setPing(IPing ping) { if (ping != null) { if (!ping.equals(this.ping)) { this.ping = ping; setupPingTask(); // since ping data changed } } else { this.ping = null; // cancel the timer task lbTimer.cancel(); } } /* Ignore null rules */ public void setRule(IRule rule) { if (rule != null) { this.rule = rule; } else { /* default rule */ this.rule = new RoundRobinRule(); } if (this.rule.getLoadBalancer() != this) { this.rule.setLoadBalancer(this); } } /** * get the count of servers. * * @param onlyAvailable * if true, return only up servers. */ public int getServerCount(boolean onlyAvailable) { if (onlyAvailable) { return upServerList.size(); } else { return allServerList.size(); } } /** * Add a server to the 'allServer' list; does not verify uniqueness, so you * could give a server a greater share by adding it more than once. */ public void addServer(Server newServer) { if (newServer != null) { try { ArrayList<Server> newList = new ArrayList<Server>(); newList.addAll(allServerList); newList.add(newServer); setServersList(newList); } catch (Exception e) { logger.error("LoadBalancer [{}]: Error adding newServer {}", name, newServer.getHost(), e); } } } /** * Add a list of servers to the 'allServer' list; does not verify * uniqueness, so you could give a server a greater share by adding it more * than once */ @Override public void addServers(List<Server> newServers) { if (newServers != null && newServers.size() > 0) { try { ArrayList<Server> newList = new ArrayList<Server>(); newList.addAll(allServerList); newList.addAll(newServers); setServersList(newList); } catch (Exception e) { logger.error("LoadBalancer [{}]: Exception while adding Servers", name, e); } } } /* * Add a list of servers to the 'allServer' list; does not verify * uniqueness, so you could give a server a greater share by adding it more * than once USED by Test Cases only for legacy reason. DO NOT USE!! */ void addServers(Object[] newServers) { if ((newServers != null) && (newServers.length > 0)) { try { ArrayList<Server> newList = new ArrayList<Server>(); newList.addAll(allServerList); for (Object server : newServers) { if (server != null) { if (server instanceof String) { server = new Server((String) server); } if (server instanceof Server) { newList.add((Server) server); } } } setServersList(newList); } catch (Exception e) { logger.error("LoadBalancer [{}]: Exception while adding Servers", name, e); } } } /** * Set the list of servers used as the server pool. This overrides existing * server list. */ public void setServersList(List lsrv) { Lock writeLock = allServerLock.writeLock(); logger.debug("LoadBalancer [{}]: clearing server list (SET op)", name); ArrayList<Server> newServers = new ArrayList<Server>(); writeLock.lock(); try { ArrayList<Server> allServers = new ArrayList<Server>(); for (Object server : lsrv) { if (server == null) { continue; } if (server instanceof String) { server = new Server((String) server); } if (server instanceof Server) { logger.debug("LoadBalancer [{}]: addServer [{}]", name, ((Server) server).getId()); allServers.add((Server) server); } else { throw new IllegalArgumentException( "Type String or Server expected, instead found:" + server.getClass()); } } boolean listChanged = false; if (!allServerList.equals(allServers)) { listChanged = true; if (changeListeners != null && changeListeners.size() > 0) { List<Server> oldList = ImmutableList.copyOf(allServerList); List<Server> newList = ImmutableList.copyOf(allServers); for (ServerListChangeListener l: changeListeners) { try { l.serverListChanged(oldList, newList); } catch (Exception e) { logger.error("LoadBalancer [{}]: Error invoking server list change listener", name, e); } } } } if (isEnablePrimingConnections()) { for (Server server : allServers) { if (!allServerList.contains(server)) { server.setReadyToServe(false); newServers.add((Server) server); } } if (primeConnections != null) { primeConnections.primeConnectionsAsync(newServers, this); } } // This will reset readyToServe flag to true on all servers // regardless whether // previous priming connections are success or not allServerList = allServers; if (canSkipPing()) { for (Server s : allServerList) { s.setAlive(true); } upServerList = allServerList; } else if (listChanged) { forceQuickPing(); } } finally { writeLock.unlock(); } } /* List in string form. SETS, does not add. */ void setServers(String srvString) { if (srvString != null) { try { String[] serverArr = srvString.split(","); ArrayList<Server> newList = new ArrayList<Server>(); for (String serverString : serverArr) { if (serverString != null) { serverString = serverString.trim(); if (serverString.length() > 0) { Server svr = new Server(serverString); newList.add(svr); } } } setServersList(newList); } catch (Exception e) { logger.error("LoadBalancer [{}]: Exception while adding Servers", name, e); } } } /** * return the server * * @param index * @param availableOnly */ public Server getServerByIndex(int index, boolean availableOnly) { try { return (availableOnly ? upServerList.get(index) : allServerList .get(index)); } catch (Exception e) { return null; } } @Override public List<Server> getServerList(boolean availableOnly) { return (availableOnly ? getReachableServers() : getAllServers()); } @Override public List<Server> getReachableServers() { return Collections.unmodifiableList(upServerList); } @Override public List<Server> getAllServers() { return Collections.unmodifiableList(allServerList); } @Override public List<Server> getServerList(ServerGroup serverGroup) { switch (serverGroup) { case ALL: return allServerList; case STATUS_UP: return upServerList; case STATUS_NOT_UP: ArrayList<Server> notAvailableServers = new ArrayList<Server>( allServerList); ArrayList<Server> upServers = new ArrayList<Server>(upServerList); notAvailableServers.removeAll(upServers); return notAvailableServers; } return new ArrayList<Server>(); } public void cancelPingTask() { if (lbTimer != null) { lbTimer.cancel(); } } /** * TimerTask that keeps runs every X seconds to check the status of each * server/node in the Server List * * @author stonse * */ class PingTask extends TimerTask { public void run() { try { new Pinger(pingStrategy).runPinger(); } catch (Exception e) { logger.error("LoadBalancer [{}]: Error pinging", name, e); } } } /** * Class that contains the mechanism to "ping" all the instances * * @author stonse * */ class Pinger { private final IPingStrategy pingerStrategy; public Pinger(IPingStrategy pingerStrategy) { this.pingerStrategy = pingerStrategy; } public void runPinger() throws Exception { if (!pingInProgress.compareAndSet(false, true)) { return; // Ping in progress - nothing to do } // we are "in" - we get to Ping Server[] allServers = null; boolean[] results = null; Lock allLock = null; Lock upLock = null; try { /* * The readLock should be free unless an addServer operation is * going on... */ allLock = allServerLock.readLock(); allLock.lock(); allServers = allServerList.toArray(new Server[allServerList.size()]); allLock.unlock(); int numCandidates = allServers.length; results = pingerStrategy.pingServers(ping, allServers); final List<Server> newUpList = new ArrayList<Server>(); final List<Server> changedServers = new ArrayList<Server>(); for (int i = 0; i < numCandidates; i++) { boolean isAlive = results[i]; Server svr = allServers[i]; boolean oldIsAlive = svr.isAlive(); svr.setAlive(isAlive); if (oldIsAlive != isAlive) { changedServers.add(svr); logger.debug("LoadBalancer [{}]: Server [{}] status changed to {}", name, svr.getId(), (isAlive ? "ALIVE" : "DEAD")); } if (isAlive) { newUpList.add(svr); } } upLock = upServerLock.writeLock(); upLock.lock(); upServerList = newUpList; upLock.unlock(); notifyServerStatusChangeListener(changedServers); } finally { pingInProgress.set(false); } } } private void notifyServerStatusChangeListener(final Collection<Server> changedServers) { if (changedServers != null && !changedServers.isEmpty() && !serverStatusListeners.isEmpty()) { for (ServerStatusChangeListener listener : serverStatusListeners) { try { listener.serverStatusChanged(changedServers); } catch (Exception e) { logger.error("LoadBalancer [{}]: Error invoking server status change listener", name, e); } } } } private final Counter createCounter() { return Monitors.newCounter("LoadBalancer_ChooseServer"); } /* * Get the alive server dedicated to key * * @return the dedicated server */ public Server chooseServer(Object key) { if (counter == null) { counter = createCounter(); } counter.increment(); if (rule == null) { return null; } else { try { return rule.choose(key); } catch (Exception e) { logger.warn("LoadBalancer [{}]: Error choosing server for key {}", name, key, e); return null; } } } /* Returns either null, or "server:port/servlet" */ public String choose(Object key) { if (rule == null) { return null; } else { try { Server svr = rule.choose(key); return ((svr == null) ? null : svr.getId()); } catch (Exception e) { logger.warn("LoadBalancer [{}]: Error choosing server", name, e); return null; } } } public void markServerDown(Server server) { if (server == null || !server.isAlive()) { return; } logger.error("LoadBalancer [{}]: markServerDown called on [{}]", name, server.getId()); server.setAlive(false); // forceQuickPing(); notifyServerStatusChangeListener(singleton(server)); } public void markServerDown(String id) { boolean triggered = false; id = Server.normalizeId(id); if (id == null) { return; } Lock writeLock = upServerLock.writeLock(); writeLock.lock(); try { final List<Server> changedServers = new ArrayList<Server>(); for (Server svr : upServerList) { if (svr.isAlive() && (svr.getId().equals(id))) { triggered = true; svr.setAlive(false); changedServers.add(svr); } } if (triggered) { logger.error("LoadBalancer [{}]: markServerDown called for server [{}]", name, id); notifyServerStatusChangeListener(changedServers); } } finally { writeLock.unlock(); } } /* * Force an immediate ping, if we're not currently pinging and don't have a * quick-ping already scheduled. */ public void forceQuickPing() { if (canSkipPing()) { return; } logger.debug("LoadBalancer [{}]: forceQuickPing invoking", name); try { new Pinger(pingStrategy).runPinger(); } catch (Exception e) { logger.error("LoadBalancer [{}]: Error running forceQuickPing()", name, e); } } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{NFLoadBalancer:name=").append(this.getName()) .append(",current list of Servers=").append(this.allServerList) .append(",Load balancer stats=") .append(this.lbStats.toString()).append("}"); return sb.toString(); } /** * Register with monitors and start priming connections if it is set. */ protected void init() { Monitors.registerObject("LoadBalancer_" + name, this); // register the rule as it contains metric for available servers count Monitors.registerObject("Rule_" + name, this.getRule()); if (enablePrimingConnections && primeConnections != null) { primeConnections.primeConnections(getReachableServers()); } } public final PrimeConnections getPrimeConnections() { return primeConnections; } public final void setPrimeConnections(PrimeConnections primeConnections) { this.primeConnections = primeConnections; } @Override public void primeCompleted(Server s, Throwable lastException) { s.setReadyToServe(true); } public boolean isEnablePrimingConnections() { return enablePrimingConnections; } public final void setEnablePrimingConnections( boolean enablePrimingConnections) { this.enablePrimingConnections = enablePrimingConnections; } public void shutdown() { cancelPingTask(); if (primeConnections != null) { primeConnections.shutdown(); } Monitors.unregisterObject("LoadBalancer_" + name, this); Monitors.unregisterObject("Rule_" + name, this.getRule()); } /** * Default implementation for <c>IPingStrategy</c>, performs ping * serially, which may not be desirable, if your <c>IPing</c> * implementation is slow, or you have large number of servers. */ private static class SerialPingStrategy implements IPingStrategy { @Override public boolean[] pingServers(IPing ping, Server[] servers) { int numCandidates = servers.length; boolean[] results = new boolean[numCandidates]; logger.debug("LoadBalancer: PingTask executing [{}] servers configured", numCandidates); for (int i = 0; i < numCandidates; i++) { results[i] = false; /* Default answer is DEAD. */ try { // NOTE: IFF we were doing a real ping // assuming we had a large set of servers (say 15) // the logic below will run them serially // hence taking 15 times the amount of time it takes // to ping each server // A better method would be to put this in an executor // pool // But, at the time of this writing, we dont REALLY // use a Real Ping (its mostly in memory eureka call) // hence we can afford to simplify this design and run // this // serially if (ping != null) { results[i] = ping.isAlive(servers[i]); } } catch (Exception e) { logger.error("Exception while pinging Server: '{}'", servers[i], e); } } return results; } } }
7,026
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/AbstractLoadBalancerPing.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.loadbalancer; import com.netflix.client.IClientConfigAware; /** * Class that provides the basic implementation of detmerining the "liveness" or * suitability of a Server (a node) * * @author stonse * */ public abstract class AbstractLoadBalancerPing implements IPing, IClientConfigAware{ AbstractLoadBalancer lb; @Override public boolean isAlive(Server server) { return true; } public void setLoadBalancer(AbstractLoadBalancer lb){ this.lb = lb; } public AbstractLoadBalancer getLoadBalancer(){ return lb; } }
7,027
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/RoundRobinRule.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.loadbalancer; import com.netflix.client.config.IClientConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; /** * The most well known and basic load balancing strategy, i.e. Round Robin Rule. * * @author stonse * @author <a href="mailto:nikos@netflix.com">Nikos Michalakis</a> * */ public class RoundRobinRule extends AbstractLoadBalancerRule { private AtomicInteger nextServerCyclicCounter; private static final boolean AVAILABLE_ONLY_SERVERS = true; private static final boolean ALL_SERVERS = false; private static Logger log = LoggerFactory.getLogger(RoundRobinRule.class); public RoundRobinRule() { nextServerCyclicCounter = new AtomicInteger(0); } public RoundRobinRule(ILoadBalancer lb) { this(); setLoadBalancer(lb); } public Server choose(ILoadBalancer lb, Object key) { if (lb == null) { log.warn("no load balancer"); return null; } Server server = null; int count = 0; while (server == null && count++ < 10) { List<Server> reachableServers = lb.getReachableServers(); List<Server> allServers = lb.getAllServers(); int upCount = reachableServers.size(); int serverCount = allServers.size(); if ((upCount == 0) || (serverCount == 0)) { log.warn("No up servers available from load balancer: " + lb); return null; } int nextServerIndex = incrementAndGetModulo(serverCount); server = allServers.get(nextServerIndex); if (server == null) { /* Transient. */ Thread.yield(); continue; } if (server.isAlive() && (server.isReadyToServe())) { return (server); } // Next. server = null; } if (count >= 10) { log.warn("No available alive servers after 10 tries from load balancer: " + lb); } return server; } /** * Inspired by the implementation of {@link AtomicInteger#incrementAndGet()}. * * @param modulo The modulo to bound the value of the counter. * @return The next value. */ private int incrementAndGetModulo(int modulo) { for (;;) { int current = nextServerCyclicCounter.get(); int next = (current + 1) % modulo; if (nextServerCyclicCounter.compareAndSet(current, next)) return next; } } @Override public Server choose(Object key) { return choose(getLoadBalancer(), key); } }
7,028
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ZoneAffinityPredicate.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.loadbalancer; /** * A predicate the filters out servers that are not in the same zone as the client's current * zone. * * @author awang * */ public class ZoneAffinityPredicate extends AbstractServerPredicate { private final String zone; public ZoneAffinityPredicate(String zone) { this.zone = zone; } @Override public boolean apply(PredicateKey input) { Server s = input.getServer(); String az = s.getZone(); if (az != null && zone != null && az.toLowerCase().equals(zone.toLowerCase())) { return true; } else { return false; } } }
7,029
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ZoneSnapshot.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.loadbalancer; /** * Captures the metrics on a Per Zone basis (Zone is modeled after the Amazon Availability Zone) * @author awang * */ public class ZoneSnapshot { final int instanceCount; final double loadPerServer; final int circuitTrippedCount; final int activeRequestsCount; public ZoneSnapshot() { this(0, 0, 0, 0d); } public ZoneSnapshot(int instanceCount, int circuitTrippedCount, int activeRequestsCount, double loadPerServer) { this.instanceCount = instanceCount; this.loadPerServer = loadPerServer; this.circuitTrippedCount = circuitTrippedCount; this.activeRequestsCount = activeRequestsCount; } public final int getInstanceCount() { return instanceCount; } public final double getLoadPerServer() { return loadPerServer; } public final int getCircuitTrippedCount() { return circuitTrippedCount; } public final int getActiveRequestsCount() { return activeRequestsCount; } @Override public String toString() { return "ZoneSnapshot [instanceCount=" + instanceCount + ", loadPerServer=" + loadPerServer + ", circuitTrippedCount=" + circuitTrippedCount + ", activeRequestsCount=" + activeRequestsCount + "]"; } }
7,030
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/LoadBalancerStats.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.loadbalancer; import com.google.common.base.Preconditions; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.cache.RemovalListener; import com.netflix.client.IClientConfigAware; import com.netflix.client.config.ClientConfigFactory; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import com.netflix.client.config.UnboxedIntProperty; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.annotations.Monitor; import com.netflix.servo.monitor.Monitors; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; /** * Class that acts as a repository of operational charateristics and statistics * of every Node/Server in the LaodBalancer. * * This information can be used to just observe and understand the runtime * behavior of the loadbalancer or more importantly for the basis that * determines the loadbalacing strategy * * @author stonse * */ public class LoadBalancerStats implements IClientConfigAware { private static final String PREFIX = "LBStats_"; public static final IClientConfigKey<Integer> ACTIVE_REQUESTS_COUNT_TIMEOUT = new CommonClientConfigKey<Integer>( "niws.loadbalancer.serverStats.activeRequestsCount.effectiveWindowSeconds", 60 * 10) {}; public static final IClientConfigKey<Integer> CONNECTION_FAILURE_COUNT_THRESHOLD = new CommonClientConfigKey<Integer>( "niws.loadbalancer.%s.connectionFailureCountThreshold", 3) {}; public static final IClientConfigKey<Integer> CIRCUIT_TRIP_TIMEOUT_FACTOR_SECONDS = new CommonClientConfigKey<Integer>( "niws.loadbalancer.%s.circuitTripTimeoutFactorSeconds", 10) {}; public static final IClientConfigKey<Integer> CIRCUIT_TRIP_MAX_TIMEOUT_SECONDS = new CommonClientConfigKey<Integer>( "niws.loadbalancer.%s.circuitTripMaxTimeoutSeconds", 30) {}; public static final IClientConfigKey<Integer> DEFAULT_CONNECTION_FAILURE_COUNT_THRESHOLD = new CommonClientConfigKey<Integer>( "niws.loadbalancer.default.connectionFailureCountThreshold", 3) {}; public static final IClientConfigKey<Integer> DEFAULT_CIRCUIT_TRIP_TIMEOUT_FACTOR_SECONDS = new CommonClientConfigKey<Integer>( "niws.loadbalancer.default.circuitTripTimeoutFactorSeconds", 10) {}; public static final IClientConfigKey<Integer> DEFAULT_CIRCUIT_TRIP_MAX_TIMEOUT_SECONDS = new CommonClientConfigKey<Integer>( "niws.loadbalancer.default.circuitTripMaxTimeoutSeconds", 30) {}; private String name; volatile Map<String, ZoneStats> zoneStatsMap = new ConcurrentHashMap<>(); volatile Map<String, List<? extends Server>> upServerListZoneMap = new ConcurrentHashMap<>(); private UnboxedIntProperty connectionFailureThreshold = new UnboxedIntProperty(CONNECTION_FAILURE_COUNT_THRESHOLD.defaultValue()); private UnboxedIntProperty circuitTrippedTimeoutFactor = new UnboxedIntProperty(CIRCUIT_TRIP_TIMEOUT_FACTOR_SECONDS.defaultValue()); private UnboxedIntProperty maxCircuitTrippedTimeout = new UnboxedIntProperty(CIRCUIT_TRIP_MAX_TIMEOUT_SECONDS.defaultValue()); private UnboxedIntProperty activeRequestsCountTimeout = new UnboxedIntProperty(ACTIVE_REQUESTS_COUNT_TIMEOUT.defaultValue()); private final LoadingCache<Server, ServerStats> serverStatsCache = CacheBuilder.newBuilder() .expireAfterAccess(30, TimeUnit.MINUTES) .removalListener((RemovalListener<Server, ServerStats>) notification -> notification.getValue().close()) .build(new CacheLoader<Server, ServerStats>() { public ServerStats load(Server server) { return createServerStats(server); } }); protected ServerStats createServerStats(Server server) { ServerStats ss = new ServerStats(this); //configure custom settings ss.setBufferSize(1000); ss.setPublishInterval(1000); ss.initialize(server); return ss; } public LoadBalancerStats() { } public LoadBalancerStats(String name) { this.name = name; Monitors.registerObject(name, this); } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { this.name = clientConfig.getClientName(); Preconditions.checkArgument(name != null, "IClientConfig#getCLientName() must not be null"); this.connectionFailureThreshold = new UnboxedIntProperty( clientConfig.getGlobalProperty(CONNECTION_FAILURE_COUNT_THRESHOLD.format(name)) .fallbackWith(clientConfig.getGlobalProperty(DEFAULT_CONNECTION_FAILURE_COUNT_THRESHOLD)) ); this.circuitTrippedTimeoutFactor = new UnboxedIntProperty( clientConfig.getGlobalProperty(CIRCUIT_TRIP_TIMEOUT_FACTOR_SECONDS.format(name)) .fallbackWith(clientConfig.getGlobalProperty(DEFAULT_CIRCUIT_TRIP_TIMEOUT_FACTOR_SECONDS)) ); this.maxCircuitTrippedTimeout = new UnboxedIntProperty( clientConfig.getGlobalProperty(CIRCUIT_TRIP_MAX_TIMEOUT_SECONDS.format(name)) .fallbackWith(clientConfig.getGlobalProperty(DEFAULT_CIRCUIT_TRIP_MAX_TIMEOUT_SECONDS)) ); this.activeRequestsCountTimeout = new UnboxedIntProperty( clientConfig.getGlobalProperty(ACTIVE_REQUESTS_COUNT_TIMEOUT)); } public String getName() { return name; } public void setName(String name) { this.name = name; } UnboxedIntProperty getConnectionFailureCountThreshold() { return connectionFailureThreshold; } UnboxedIntProperty getCircuitTrippedTimeoutFactor() { return circuitTrippedTimeoutFactor; } UnboxedIntProperty getCircuitTripMaxTimeoutSeconds() { return maxCircuitTrippedTimeout; } UnboxedIntProperty getActiveRequestsCountTimeout() { return activeRequestsCountTimeout; } /** * The caller o this class is tasked to call this method every so often if * the servers participating in the LoadBalancer changes * @param servers */ public void updateServerList(List<Server> servers){ for (Server s: servers){ addServer(s); } } public void addServer(Server server) { if (server != null) { try { serverStatsCache.get(server); } catch (ExecutionException e) { ServerStats stats = createServerStats(server); serverStatsCache.asMap().putIfAbsent(server, stats); } } } /** * Method that updates the internal stats of Response times maintained on a per Server * basis * @param server * @param msecs */ public void noteResponseTime(Server server, double msecs){ ServerStats ss = getServerStats(server); ss.noteResponseTime(msecs); } protected ServerStats getServerStats(Server server) { if (server == null) { return null; } try { return serverStatsCache.get(server); } catch (ExecutionException e) { ServerStats stats = createServerStats(server); serverStatsCache.asMap().putIfAbsent(server, stats); return serverStatsCache.asMap().get(server); } } public void incrementActiveRequestsCount(Server server) { ServerStats ss = getServerStats(server); ss.incrementActiveRequestsCount(); } public void decrementActiveRequestsCount(Server server) { ServerStats ss = getServerStats(server); ss.decrementActiveRequestsCount(); } private ZoneStats getZoneStats(String zone) { zone = zone.toLowerCase(); ZoneStats zs = zoneStatsMap.get(zone); if (zs == null){ zoneStatsMap.put(zone, new ZoneStats(this.getName(), zone, this)); zs = zoneStatsMap.get(zone); } return zs; } public boolean isCircuitBreakerTripped(Server server) { ServerStats ss = getServerStats(server); return ss.isCircuitBreakerTripped(); } public void incrementSuccessiveConnectionFailureCount(Server server) { ServerStats ss = getServerStats(server); ss.incrementSuccessiveConnectionFailureCount(); } public void clearSuccessiveConnectionFailureCount(Server server) { ServerStats ss = getServerStats(server); ss.clearSuccessiveConnectionFailureCount(); } public void incrementNumRequests(Server server){ ServerStats ss = getServerStats(server); ss.incrementNumRequests(); } public void incrementZoneCounter(Server server) { String zone = server.getZone(); if (zone != null) { getZoneStats(zone).incrementCounter(); } } public void updateZoneServerMapping(Map<String, List<Server>> map) { upServerListZoneMap = new ConcurrentHashMap<String, List<? extends Server>>(map); // make sure ZoneStats object exist for available zones for monitoring purpose for (String zone: map.keySet()) { getZoneStats(zone); } } public int getInstanceCount(String zone) { if (zone == null) { return 0; } zone = zone.toLowerCase(); List<? extends Server> currentList = upServerListZoneMap.get(zone); if (currentList == null) { return 0; } return currentList.size(); } public int getActiveRequestsCount(String zone) { return getZoneSnapshot(zone).getActiveRequestsCount(); } public double getActiveRequestsPerServer(String zone) { return getZoneSnapshot(zone).getLoadPerServer(); } public ZoneSnapshot getZoneSnapshot(String zone) { if (zone == null) { return new ZoneSnapshot(); } zone = zone.toLowerCase(); List<? extends Server> currentList = upServerListZoneMap.get(zone); return getZoneSnapshot(currentList); } /** * This is the core function to get zone stats. All stats are reported to avoid * going over the list again for a different stat. * * @param servers */ public ZoneSnapshot getZoneSnapshot(List<? extends Server> servers) { if (servers == null || servers.size() == 0) { return new ZoneSnapshot(); } int instanceCount = servers.size(); int activeConnectionsCount = 0; int activeConnectionsCountOnAvailableServer = 0; int circuitBreakerTrippedCount = 0; double loadPerServer = 0; long currentTime = System.currentTimeMillis(); for (Server server: servers) { ServerStats stat = getSingleServerStat(server); if (stat.isCircuitBreakerTripped(currentTime)) { circuitBreakerTrippedCount++; } else { activeConnectionsCountOnAvailableServer += stat.getActiveRequestsCount(currentTime); } activeConnectionsCount += stat.getActiveRequestsCount(currentTime); } if (circuitBreakerTrippedCount == instanceCount) { if (instanceCount > 0) { // should be NaN, but may not be displayable on Epic loadPerServer = -1; } } else { loadPerServer = ((double) activeConnectionsCountOnAvailableServer) / (instanceCount - circuitBreakerTrippedCount); } return new ZoneSnapshot(instanceCount, circuitBreakerTrippedCount, activeConnectionsCount, loadPerServer); } public int getCircuitBreakerTrippedCount(String zone) { return getZoneSnapshot(zone).getCircuitTrippedCount(); } @Monitor(name=PREFIX + "CircuitBreakerTrippedCount", type = DataSourceType.GAUGE) public int getCircuitBreakerTrippedCount() { int count = 0; for (String zone: upServerListZoneMap.keySet()) { count += getCircuitBreakerTrippedCount(zone); } return count; } public long getMeasuredZoneHits(String zone) { if (zone == null) { return 0; } zone = zone.toLowerCase(); long count = 0; List<? extends Server> currentList = upServerListZoneMap.get(zone); if (currentList == null) { return 0; } for (Server server: currentList) { ServerStats stat = getSingleServerStat(server); count += stat.getMeasuredRequestsCount(); } return count; } public int getCongestionRatePercentage(String zone) { if (zone == null) { return 0; } zone = zone.toLowerCase(); List<? extends Server> currentList = upServerListZoneMap.get(zone); if (currentList == null || currentList.size() == 0) { return 0; } int serverCount = currentList.size(); int activeConnectionsCount = 0; int circuitBreakerTrippedCount = 0; for (Server server: currentList) { ServerStats stat = getSingleServerStat(server); activeConnectionsCount += stat.getActiveRequestsCount(); if (stat.isCircuitBreakerTripped()) { circuitBreakerTrippedCount++; } } return (int) ((activeConnectionsCount + circuitBreakerTrippedCount) * 100L / serverCount); } @Monitor(name=PREFIX + "AvailableZones", type = DataSourceType.INFORMATIONAL) public Set<String> getAvailableZones() { return upServerListZoneMap.keySet(); } public ServerStats getSingleServerStat(Server server) { return getServerStats(server); } /** * returns map of Stats for all servers */ public Map<Server,ServerStats> getServerStats(){ return serverStatsCache.asMap(); } public Map<String, ZoneStats> getZoneStats() { return zoneStatsMap; } @Override public String toString() { return "Zone stats: " + zoneStatsMap.toString() + "," + "Server stats: " + getSortedServerStats(getServerStats().values()).toString(); } private static Comparator<ServerStats> serverStatsComparator = new Comparator<ServerStats>() { @Override public int compare(ServerStats o1, ServerStats o2) { String zone1 = ""; String zone2 = ""; if (o1.server != null && o1.server.getZone() != null) { zone1 = o1.server.getZone(); } if (o2.server != null && o2.server.getZone() != null) { zone2 = o2.server.getZone(); } return zone1.compareTo(zone2); } }; private static Collection<ServerStats> getSortedServerStats(Collection<ServerStats> stats) { List<ServerStats> list = new ArrayList<ServerStats>(stats); Collections.sort(list, serverStatsComparator); return list; } }
7,031
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ConfigurationBasedServerList.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.loadbalancer; import java.util.List; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; /** * Utility class that can load the List of Servers from a Configuration (i.e * properties available via Archaius). The property name be defined in this format: * * <pre>{@code <clientName>.<nameSpace>.listOfServers=<comma delimited hostname:port strings> }</pre> * * @author awang * */ public class ConfigurationBasedServerList extends AbstractServerList<Server> { private IClientConfig clientConfig; @Override public List<Server> getInitialListOfServers() { return getUpdatedListOfServers(); } @Override public List<Server> getUpdatedListOfServers() { String listOfServers = clientConfig.get(CommonClientConfigKey.ListOfServers); return derive(listOfServers); } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { this.clientConfig = clientConfig; } protected List<Server> derive(String value) { List<Server> list = Lists.newArrayList(); if (!Strings.isNullOrEmpty(value)) { for (String s: value.split(",")) { list.add(new Server(s.trim())); } } return list; } @Override public String toString() { return "ConfigurationBasedServerList:" + getUpdatedListOfServers(); } }
7,032
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/AbstractServerPredicate.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.loadbalancer; import java.util.List; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.netflix.client.config.IClientConfig; /** * A basic building block for server filtering logic which can be used in rules and server list filters. * The input object of the predicate is {@link PredicateKey}, which has Server and load balancer key * information. Therefore, it is possible to develop logic to filter servers by both Server and load balancer * key or either one of them. * * @author awang * */ public abstract class AbstractServerPredicate implements Predicate<PredicateKey> { protected IRule rule; private volatile LoadBalancerStats lbStats; private final Random random = new Random(); private final AtomicInteger nextIndex = new AtomicInteger(); private final Predicate<Server> serverOnlyPredicate = new Predicate<Server>() { @Override public boolean apply(@Nullable Server input) { return AbstractServerPredicate.this.apply(new PredicateKey(input)); } }; public static AbstractServerPredicate alwaysTrue() { return new AbstractServerPredicate() { @Override public boolean apply(@Nullable PredicateKey input) { return true; } }; } public AbstractServerPredicate() { } public AbstractServerPredicate(IRule rule) { this.rule = rule; } @Deprecated public AbstractServerPredicate(IRule rule, IClientConfig clientConfig) { this(rule); } @Deprecated public AbstractServerPredicate(LoadBalancerStats lbStats, IClientConfig clientConfig) { this(lbStats); } public AbstractServerPredicate(LoadBalancerStats lbStats) { this.lbStats = lbStats; } protected LoadBalancerStats getLBStats() { if (lbStats != null) { return lbStats; } else if (rule != null) { ILoadBalancer lb = rule.getLoadBalancer(); if (lb instanceof AbstractLoadBalancer) { LoadBalancerStats stats = ((AbstractLoadBalancer) lb).getLoadBalancerStats(); setLoadBalancerStats(stats); return stats; } else { return null; } } else { return null; } } public void setLoadBalancerStats(LoadBalancerStats stats) { this.lbStats = stats; } /** * Get the predicate to filter list of servers. The load balancer key is treated as null * as the input of this predicate. */ public Predicate<Server> getServerOnlyPredicate() { return serverOnlyPredicate; } /** * Get servers filtered by this predicate from list of servers. Load balancer key * is presumed to be null. * * @see #getEligibleServers(List, Object) * */ public List<Server> getEligibleServers(List<Server> servers) { return getEligibleServers(servers, null); } /** * Get servers filtered by this predicate from list of servers. */ public List<Server> getEligibleServers(List<Server> servers, Object loadBalancerKey) { if (loadBalancerKey == null) { return ImmutableList.copyOf(Iterables.filter(servers, this.getServerOnlyPredicate())); } else { List<Server> results = Lists.newArrayList(); for (Server server: servers) { if (this.apply(new PredicateKey(loadBalancerKey, server))) { results.add(server); } } return results; } } /** * Referenced from RoundRobinRule * Inspired by the implementation of {@link AtomicInteger#incrementAndGet()}. * * @param modulo The modulo to bound the value of the counter. * @return The next value. */ private int incrementAndGetModulo(int modulo) { for (;;) { int current = nextIndex.get(); int next = (current + 1) % modulo; if (nextIndex.compareAndSet(current, next) && current < modulo) return current; } } /** * Choose a random server after the predicate filters a list of servers. Load balancer key * is presumed to be null. * */ public Optional<Server> chooseRandomlyAfterFiltering(List<Server> servers) { List<Server> eligible = getEligibleServers(servers); if (eligible.size() == 0) { return Optional.absent(); } return Optional.of(eligible.get(random.nextInt(eligible.size()))); } /** * Choose a server in a round robin fashion after the predicate filters a list of servers. Load balancer key * is presumed to be null. */ public Optional<Server> chooseRoundRobinAfterFiltering(List<Server> servers) { List<Server> eligible = getEligibleServers(servers); if (eligible.size() == 0) { return Optional.absent(); } return Optional.of(eligible.get(incrementAndGetModulo(eligible.size()))); } /** * Choose a random server after the predicate filters list of servers given list of servers and * load balancer key. * */ public Optional<Server> chooseRandomlyAfterFiltering(List<Server> servers, Object loadBalancerKey) { List<Server> eligible = getEligibleServers(servers, loadBalancerKey); if (eligible.size() == 0) { return Optional.absent(); } return Optional.of(eligible.get(random.nextInt(eligible.size()))); } /** * Choose a server in a round robin fashion after the predicate filters a given list of servers and load balancer key. */ public Optional<Server> chooseRoundRobinAfterFiltering(List<Server> servers, Object loadBalancerKey) { List<Server> eligible = getEligibleServers(servers, loadBalancerKey); if (eligible.size() == 0) { return Optional.absent(); } return Optional.of(eligible.get(incrementAndGetModulo(eligible.size()))); } /** * Create an instance from a predicate. */ public static AbstractServerPredicate ofKeyPredicate(final Predicate<PredicateKey> p) { return new AbstractServerPredicate() { @Override @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "NP") public boolean apply(PredicateKey input) { return p.apply(input); } }; } /** * Create an instance from a predicate. */ public static AbstractServerPredicate ofServerPredicate(final Predicate<Server> p) { return new AbstractServerPredicate() { @Override @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "NP") public boolean apply(PredicateKey input) { return p.apply(input.getServer()); } }; } }
7,033
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ServerStatusChangeListener.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.loadbalancer; import java.util.Collection; public interface ServerStatusChangeListener { /** * Invoked by {@link BaseLoadBalancer} when server status has changed (e.g. when marked as down or found dead by ping). * * @param servers the servers that had their status changed, never {@code null} */ public void serverStatusChanged(Collection<Server> servers); }
7,034
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ServerStats.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.loadbalancer; import com.google.common.annotations.VisibleForTesting; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfigKey; import com.netflix.client.config.Property; import com.netflix.client.config.UnboxedIntProperty; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.annotations.Monitor; import com.netflix.stats.distribution.DataDistribution; import com.netflix.stats.distribution.DataPublisher; import com.netflix.stats.distribution.Distribution; import com.netflix.util.MeasuredRate; import java.util.Date; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; /** * Capture various stats per Server(node) in the LoadBalancer * @author stonse * */ public class ServerStats { private static final int DEFAULT_PUBLISH_INTERVAL = 60 * 1000; // = 1 minute private static final int DEFAULT_BUFFER_SIZE = 60 * 1000; // = 1000 requests/sec for 1 minute private final UnboxedIntProperty connectionFailureThreshold; private final UnboxedIntProperty circuitTrippedTimeoutFactor; private final UnboxedIntProperty maxCircuitTrippedTimeout; private final UnboxedIntProperty activeRequestsCountTimeout; private static final double[] PERCENTS = makePercentValues(); private DataDistribution dataDist = new DataDistribution(1, PERCENTS); // in case private DataPublisher publisher = null; private final Distribution responseTimeDist = new Distribution(); int bufferSize = DEFAULT_BUFFER_SIZE; int publishInterval = DEFAULT_PUBLISH_INTERVAL; long failureCountSlidingWindowInterval = 1000; private MeasuredRate serverFailureCounts = new MeasuredRate(failureCountSlidingWindowInterval); private MeasuredRate requestCountInWindow = new MeasuredRate(300000L); Server server; AtomicLong totalRequests = new AtomicLong(); @VisibleForTesting AtomicInteger successiveConnectionFailureCount = new AtomicInteger(0); @VisibleForTesting AtomicInteger activeRequestsCount = new AtomicInteger(0); @VisibleForTesting AtomicInteger openConnectionsCount = new AtomicInteger(0); private volatile long lastConnectionFailedTimestamp; private volatile long lastActiveRequestsCountChangeTimestamp; private AtomicLong totalCircuitBreakerBlackOutPeriod = new AtomicLong(0); private volatile long lastAccessedTimestamp; private volatile long firstConnectionTimestamp = 0; public ServerStats() { connectionFailureThreshold = new UnboxedIntProperty(Property.of(LoadBalancerStats.CONNECTION_FAILURE_COUNT_THRESHOLD.defaultValue())); circuitTrippedTimeoutFactor = new UnboxedIntProperty(LoadBalancerStats.CIRCUIT_TRIP_TIMEOUT_FACTOR_SECONDS.defaultValue()); maxCircuitTrippedTimeout = new UnboxedIntProperty(LoadBalancerStats.CIRCUIT_TRIP_MAX_TIMEOUT_SECONDS.defaultValue()); activeRequestsCountTimeout = new UnboxedIntProperty(LoadBalancerStats.ACTIVE_REQUESTS_COUNT_TIMEOUT.defaultValue()); } public ServerStats(LoadBalancerStats lbStats) { maxCircuitTrippedTimeout = lbStats.getCircuitTripMaxTimeoutSeconds(); circuitTrippedTimeoutFactor = lbStats.getCircuitTrippedTimeoutFactor(); connectionFailureThreshold = lbStats.getConnectionFailureCountThreshold(); activeRequestsCountTimeout = lbStats.getActiveRequestsCountTimeout(); } /** * Initializes the object, starting data collection and reporting. */ public void initialize(Server server) { serverFailureCounts = new MeasuredRate(failureCountSlidingWindowInterval); requestCountInWindow = new MeasuredRate(300000L); if (publisher == null) { dataDist = new DataDistribution(getBufferSize(), PERCENTS); publisher = new DataPublisher(dataDist, getPublishIntervalMillis()); publisher.start(); } this.server = server; } public void close() { if (publisher != null) publisher.stop(); } public Server getServer() { return server; } private int getBufferSize() { return bufferSize; } private long getPublishIntervalMillis() { return publishInterval; } public void setBufferSize(int bufferSize) { this.bufferSize = bufferSize; } public void setPublishInterval(int publishInterval) { this.publishInterval = publishInterval; } /** * The supported percentile values. * These correspond to the various Monitor methods defined below. * No, this is not pretty, but that's the way it is. */ private static enum Percent { TEN(10), TWENTY_FIVE(25), FIFTY(50), SEVENTY_FIVE(75), NINETY(90), NINETY_FIVE(95), NINETY_EIGHT(98), NINETY_NINE(99), NINETY_NINE_POINT_FIVE(99.5); private double val; Percent(double val) { this.val = val; } public double getValue() { return val; } } private static double[] makePercentValues() { Percent[] percents = Percent.values(); double[] p = new double[percents.length]; for (int i = 0; i < percents.length; i++) { p[i] = percents[i].getValue(); } return p; } public long getFailureCountSlidingWindowInterval() { return failureCountSlidingWindowInterval; } public void setFailureCountSlidingWindowInterval( long failureCountSlidingWindowInterval) { this.failureCountSlidingWindowInterval = failureCountSlidingWindowInterval; } // run time methods /** * Increment the count of failures for this Server * */ public void addToFailureCount(){ serverFailureCounts.increment(); } /** * Returns the count of failures in the current window * */ public long getFailureCount(){ return serverFailureCounts.getCurrentCount(); } /** * Call this method to note the response time after every request * @param msecs */ public void noteResponseTime(double msecs){ dataDist.noteValue(msecs); responseTimeDist.noteValue(msecs); } public void incrementNumRequests(){ totalRequests.incrementAndGet(); } public void incrementActiveRequestsCount() { activeRequestsCount.incrementAndGet(); requestCountInWindow.increment(); long currentTime = System.currentTimeMillis(); lastActiveRequestsCountChangeTimestamp = currentTime; lastAccessedTimestamp = currentTime; if (firstConnectionTimestamp == 0) { firstConnectionTimestamp = currentTime; } } public void incrementOpenConnectionsCount() { openConnectionsCount.incrementAndGet(); } public void decrementActiveRequestsCount() { activeRequestsCount.getAndUpdate(current -> Math.max(0, current - 1)); lastActiveRequestsCountChangeTimestamp = System.currentTimeMillis(); } public void decrementOpenConnectionsCount() { openConnectionsCount.getAndUpdate(current -> Math.max(0, current - 1)); } public int getActiveRequestsCount() { return getActiveRequestsCount(System.currentTimeMillis()); } public int getActiveRequestsCount(long currentTime) { int count = activeRequestsCount.get(); if (count == 0) { return 0; } else if (currentTime - lastActiveRequestsCountChangeTimestamp > activeRequestsCountTimeout.get() * 1000 || count < 0) { activeRequestsCount.set(0); return 0; } else { return count; } } public int getOpenConnectionsCount() { return openConnectionsCount.get(); } public long getMeasuredRequestsCount() { return requestCountInWindow.getCount(); } @Monitor(name="ActiveRequestsCount", type = DataSourceType.GAUGE) public int getMonitoredActiveRequestsCount() { return activeRequestsCount.get(); } @Monitor(name="CircuitBreakerTripped", type = DataSourceType.INFORMATIONAL) public boolean isCircuitBreakerTripped() { return isCircuitBreakerTripped(System.currentTimeMillis()); } public boolean isCircuitBreakerTripped(long currentTime) { long circuitBreakerTimeout = getCircuitBreakerTimeout(); if (circuitBreakerTimeout <= 0) { return false; } return circuitBreakerTimeout > currentTime; } private long getCircuitBreakerTimeout() { long blackOutPeriod = getCircuitBreakerBlackoutPeriod(); if (blackOutPeriod <= 0) { return 0; } return lastConnectionFailedTimestamp + blackOutPeriod; } private long getCircuitBreakerBlackoutPeriod() { int failureCount = successiveConnectionFailureCount.get(); int threshold = connectionFailureThreshold.get(); if (failureCount < threshold) { return 0; } int diff = Math.min(failureCount - threshold, 16); int blackOutSeconds = (1 << diff) * circuitTrippedTimeoutFactor.get(); if (blackOutSeconds > maxCircuitTrippedTimeout.get()) { blackOutSeconds = maxCircuitTrippedTimeout.get(); } return blackOutSeconds * 1000L; } public void incrementSuccessiveConnectionFailureCount() { lastConnectionFailedTimestamp = System.currentTimeMillis(); successiveConnectionFailureCount.incrementAndGet(); totalCircuitBreakerBlackOutPeriod.addAndGet(getCircuitBreakerBlackoutPeriod()); } public void clearSuccessiveConnectionFailureCount() { successiveConnectionFailureCount.set(0); } @Monitor(name="SuccessiveConnectionFailureCount", type = DataSourceType.GAUGE) public int getSuccessiveConnectionFailureCount() { return successiveConnectionFailureCount.get(); } /* * Response total times */ /** * Gets the average total amount of time to handle a request, in milliseconds. */ @Monitor(name = "OverallResponseTimeMillisAvg", type = DataSourceType.INFORMATIONAL, description = "Average total time for a request, in milliseconds") public double getResponseTimeAvg() { return responseTimeDist.getMean(); } /** * Gets the maximum amount of time spent handling a request, in milliseconds. */ @Monitor(name = "OverallResponseTimeMillisMax", type = DataSourceType.INFORMATIONAL, description = "Max total time for a request, in milliseconds") public double getResponseTimeMax() { return responseTimeDist.getMaximum(); } /** * Gets the minimum amount of time spent handling a request, in milliseconds. */ @Monitor(name = "OverallResponseTimeMillisMin", type = DataSourceType.INFORMATIONAL, description = "Min total time for a request, in milliseconds") public double getResponseTimeMin() { return responseTimeDist.getMinimum(); } /** * Gets the standard deviation in the total amount of time spent handling a request, in milliseconds. */ @Monitor(name = "OverallResponseTimeMillisStdDev", type = DataSourceType.INFORMATIONAL, description = "Standard Deviation in total time to handle a request, in milliseconds") public double getResponseTimeStdDev() { return responseTimeDist.getStdDev(); } /* * QOS percentile performance data for most recent period */ /** * Gets the number of samples used to compute the various response-time percentiles. */ @Monitor(name = "ResponseTimePercentileNumValues", type = DataSourceType.GAUGE, description = "The number of data points used to compute the currently reported percentile values") public int getResponseTimePercentileNumValues() { return dataDist.getSampleSize(); } /** * Gets the time when the varios percentile data was last updated. */ @Monitor(name = "ResponseTimePercentileWhen", type = DataSourceType.INFORMATIONAL, description = "The time the percentile values were computed") public String getResponseTimePercentileTime() { return dataDist.getTimestamp(); } /** * Gets the time when the varios percentile data was last updated, * in milliseconds since the epoch. */ @Monitor(name = "ResponseTimePercentileWhenMillis", type = DataSourceType.COUNTER, description = "The time the percentile values were computed in milliseconds since the epoch") public long getResponseTimePercentileTimeMillis() { return dataDist.getTimestampMillis(); } /** * Gets the average total amount of time to handle a request * in the recent time-slice, in milliseconds. */ @Monitor(name = "ResponseTimeMillisAvg", type = DataSourceType.GAUGE, description = "Average total time for a request in the recent time slice, in milliseconds") public double getResponseTimeAvgRecent() { return dataDist.getMean(); } /** * Gets the 10-th percentile in the total amount of time spent handling a request, in milliseconds. */ @Monitor(name = "ResponseTimeMillis10Percentile", type = DataSourceType.INFORMATIONAL, description = "10th percentile in total time to handle a request, in milliseconds") public double getResponseTime10thPercentile() { return getResponseTimePercentile(Percent.TEN); } /** * Gets the 25-th percentile in the total amount of time spent handling a request, in milliseconds. */ @Monitor(name = "ResponseTimeMillis25Percentile", type = DataSourceType.INFORMATIONAL, description = "25th percentile in total time to handle a request, in milliseconds") public double getResponseTime25thPercentile() { return getResponseTimePercentile(Percent.TWENTY_FIVE); } /** * Gets the 50-th percentile in the total amount of time spent handling a request, in milliseconds. */ @Monitor(name = "ResponseTimeMillis50Percentile", type = DataSourceType.INFORMATIONAL, description = "50th percentile in total time to handle a request, in milliseconds") public double getResponseTime50thPercentile() { return getResponseTimePercentile(Percent.FIFTY); } /** * Gets the 75-th percentile in the total amount of time spent handling a request, in milliseconds. */ @Monitor(name = "ResponseTimeMillis75Percentile", type = DataSourceType.INFORMATIONAL, description = "75th percentile in total time to handle a request, in milliseconds") public double getResponseTime75thPercentile() { return getResponseTimePercentile(Percent.SEVENTY_FIVE); } /** * Gets the 90-th percentile in the total amount of time spent handling a request, in milliseconds. */ @Monitor(name = "ResponseTimeMillis90Percentile", type = DataSourceType.INFORMATIONAL, description = "90th percentile in total time to handle a request, in milliseconds") public double getResponseTime90thPercentile() { return getResponseTimePercentile(Percent.NINETY); } /** * Gets the 95-th percentile in the total amount of time spent handling a request, in milliseconds. */ @Monitor(name = "ResponseTimeMillis95Percentile", type = DataSourceType.GAUGE, description = "95th percentile in total time to handle a request, in milliseconds") public double getResponseTime95thPercentile() { return getResponseTimePercentile(Percent.NINETY_FIVE); } /** * Gets the 98-th percentile in the total amount of time spent handling a request, in milliseconds. */ @Monitor(name = "ResponseTimeMillis98Percentile", type = DataSourceType.INFORMATIONAL, description = "98th percentile in total time to handle a request, in milliseconds") public double getResponseTime98thPercentile() { return getResponseTimePercentile(Percent.NINETY_EIGHT); } /** * Gets the 99-th percentile in the total amount of time spent handling a request, in milliseconds. */ @Monitor(name = "ResponseTimeMillis99Percentile", type = DataSourceType.GAUGE, description = "99th percentile in total time to handle a request, in milliseconds") public double getResponseTime99thPercentile() { return getResponseTimePercentile(Percent.NINETY_NINE); } /** * Gets the 99.5-th percentile in the total amount of time spent handling a request, in milliseconds. */ @Monitor(name = "ResponseTimeMillis99_5Percentile", type = DataSourceType.GAUGE, description = "99.5th percentile in total time to handle a request, in milliseconds") public double getResponseTime99point5thPercentile() { return getResponseTimePercentile(Percent.NINETY_NINE_POINT_FIVE); } public long getTotalRequestsCount() { return totalRequests.get(); } private double getResponseTimePercentile(Percent p) { return dataDist.getPercentiles()[p.ordinal()]; } public String toString(){ StringBuilder sb = new StringBuilder(); sb.append("[Server:" + server + ";"); sb.append("\tZone:" + server.getZone() + ";"); sb.append("\tTotal Requests:" + totalRequests + ";"); sb.append("\tSuccessive connection failure:" + getSuccessiveConnectionFailureCount() + ";"); if (isCircuitBreakerTripped()) { sb.append("\tBlackout until: " + new Date(getCircuitBreakerTimeout()) + ";"); } sb.append("\tTotal blackout seconds:" + totalCircuitBreakerBlackOutPeriod.get() / 1000 + ";"); sb.append("\tLast connection made:" + new Date(lastAccessedTimestamp) + ";"); if (lastConnectionFailedTimestamp > 0) { sb.append("\tLast connection failure: " + new Date(lastConnectionFailedTimestamp) + ";"); } sb.append("\tFirst connection made: " + new Date(firstConnectionTimestamp) + ";"); sb.append("\tActive Connections:" + getMonitoredActiveRequestsCount() + ";"); sb.append("\ttotal failure count in last (" + failureCountSlidingWindowInterval + ") msecs:" + getFailureCount() + ";"); sb.append("\taverage resp time:" + getResponseTimeAvg() + ";"); sb.append("\t90 percentile resp time:" + getResponseTime90thPercentile() + ";"); sb.append("\t95 percentile resp time:" + getResponseTime95thPercentile() + ";"); sb.append("\tmin resp time:" + getResponseTimeMin() + ";"); sb.append("\tmax resp time:" + getResponseTimeMax() + ";"); sb.append("\tstddev resp time:" + getResponseTimeStdDev()); sb.append("]\n"); return sb.toString(); } }
7,035
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/AbstractServerList.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.loadbalancer; import com.netflix.client.ClientFactory; import com.netflix.client.IClientConfigAware; import com.netflix.client.ClientException; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; /** * The class includes an API to create a filter to be use by load balancer * to filter the servers returned from {@link #getUpdatedListOfServers()} or {@link #getInitialListOfServers()}. * */ public abstract class AbstractServerList<T extends Server> implements ServerList<T>, IClientConfigAware { /** * Get a ServerListFilter instance. It uses {@link ClientFactory#instantiateInstanceWithClientConfig(String, IClientConfig)} * which in turn uses reflection to initialize the filter instance. * The filter class name is determined by the value of {@link CommonClientConfigKey#NIWSServerListFilterClassName} * in the {@link IClientConfig}. The default implementation is {@link ZoneAffinityServerListFilter}. */ public AbstractServerListFilter<T> getFilterImpl(IClientConfig niwsClientConfig) throws ClientException { String niwsServerListFilterClassName = null; try { niwsServerListFilterClassName = niwsClientConfig.get( CommonClientConfigKey.NIWSServerListFilterClassName, ZoneAffinityServerListFilter.class.getName()); AbstractServerListFilter<T> abstractNIWSServerListFilter = (AbstractServerListFilter<T>) ClientFactory.instantiateInstanceWithClientConfig(niwsServerListFilterClassName, niwsClientConfig); return abstractNIWSServerListFilter; } catch (Throwable e) { throw new ClientException( ClientException.ErrorType.CONFIGURATION, "Unable to get an instance of CommonClientConfigKey.NIWSServerListFilterClassName. Configured class:" + niwsServerListFilterClassName, e); } } }
7,036
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ZoneAwareLoadBalancer.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.loadbalancer; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.netflix.client.ClientFactory; import com.netflix.client.config.ClientConfigFactory; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import com.netflix.client.config.Property; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * Load balancer that can avoid a zone as a whole when choosing server. *<p> * The key metric used to measure the zone condition is Average Active Requests, which is aggregated per rest client per zone. It is the total outstanding requests in a zone divided by number of available targeted instances (excluding circuit breaker tripped instances). This metric is very effective when timeout occurs slowly on a bad zone. <p> The LoadBalancer will calculate and examine zone stats of all available zones. If the Average Active Requests for any zone has reached a configured threshold, this zone will be dropped from the active server list. In case more than one zone has reached the threshold, the zone with the most active requests per server will be dropped. Once the the worst zone is dropped, a zone will be chosen among the rest with the probability proportional to its number of instances. A server will be returned from the chosen zone with a given Rule (A Rule is a load balancing strategy, for example {@link AvailabilityFilteringRule}) For each request, the steps above will be repeated. That is to say, each zone related load balancing decisions are made at real time with the up-to-date statistics aiding the choice. * @author awang * * @param <T> */ public class ZoneAwareLoadBalancer<T extends Server> extends DynamicServerListLoadBalancer<T> { private ConcurrentHashMap<String, BaseLoadBalancer> balancers = new ConcurrentHashMap<String, BaseLoadBalancer>(); private static final Logger logger = LoggerFactory.getLogger(ZoneAwareLoadBalancer.class); private static final IClientConfigKey<Boolean> ENABLED = new CommonClientConfigKey<Boolean>( "ZoneAwareNIWSDiscoveryLoadBalancer.enabled", true){}; private static final IClientConfigKey<Double> TRIGGERING_LOAD_PER_SERVER_THRESHOLD = new CommonClientConfigKey<Double>( "ZoneAwareNIWSDiscoveryLoadBalancer.%s.triggeringLoadPerServerThreshold", 0.2d){}; private static final IClientConfigKey<Double> AVOID_ZONE_WITH_BLACKOUT_PERCENTAGE = new CommonClientConfigKey<Double>( "ZoneAwareNIWSDiscoveryLoadBalancer.%s.avoidZoneWithBlackoutPercetage", 0.99999d){}; private Property<Double> triggeringLoad = Property.of(TRIGGERING_LOAD_PER_SERVER_THRESHOLD.defaultValue()); private Property<Double> triggeringBlackoutPercentage = Property.of(AVOID_ZONE_WITH_BLACKOUT_PERCENTAGE.defaultValue()); private Property<Boolean> enabled = Property.of(ENABLED.defaultValue()); void setUpServerList(List<Server> upServerList) { this.upServerList = upServerList; } @Deprecated public ZoneAwareLoadBalancer(IClientConfig clientConfig, IRule rule, IPing ping, ServerList<T> serverList, ServerListFilter<T> filter) { super(clientConfig, rule, ping, serverList, filter); String name = Optional.ofNullable(getName()).orElse("default"); this.enabled = clientConfig.getGlobalProperty(ENABLED); this.triggeringLoad = clientConfig.getGlobalProperty(TRIGGERING_LOAD_PER_SERVER_THRESHOLD.format(name)); this.triggeringBlackoutPercentage = clientConfig.getGlobalProperty(AVOID_ZONE_WITH_BLACKOUT_PERCENTAGE.format(name)); } public ZoneAwareLoadBalancer(IClientConfig clientConfig, IRule rule, IPing ping, ServerList<T> serverList, ServerListFilter<T> filter, ServerListUpdater serverListUpdater) { super(clientConfig, rule, ping, serverList, filter, serverListUpdater); String name = Optional.ofNullable(getName()).orElse("default"); this.enabled = clientConfig.getGlobalProperty(ENABLED); this.triggeringLoad = clientConfig.getGlobalProperty(TRIGGERING_LOAD_PER_SERVER_THRESHOLD.format(name)); this.triggeringBlackoutPercentage = clientConfig.getGlobalProperty(AVOID_ZONE_WITH_BLACKOUT_PERCENTAGE.format(name)); } public ZoneAwareLoadBalancer() { super(); } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { super.initWithNiwsConfig(clientConfig); String name = Optional.ofNullable(getName()).orElse("default"); this.enabled = clientConfig.getGlobalProperty(ENABLED); this.triggeringLoad = clientConfig.getGlobalProperty(TRIGGERING_LOAD_PER_SERVER_THRESHOLD.format(name)); this.triggeringBlackoutPercentage = clientConfig.getGlobalProperty(AVOID_ZONE_WITH_BLACKOUT_PERCENTAGE.format(name)); } @Override protected void setServerListForZones(Map<String, List<Server>> zoneServersMap) { super.setServerListForZones(zoneServersMap); if (balancers == null) { balancers = new ConcurrentHashMap<String, BaseLoadBalancer>(); } for (Map.Entry<String, List<Server>> entry: zoneServersMap.entrySet()) { String zone = entry.getKey().toLowerCase(); getLoadBalancer(zone).setServersList(entry.getValue()); } // check if there is any zone that no longer has a server // and set the list to empty so that the zone related metrics does not // contain stale data for (Map.Entry<String, BaseLoadBalancer> existingLBEntry: balancers.entrySet()) { if (!zoneServersMap.keySet().contains(existingLBEntry.getKey())) { existingLBEntry.getValue().setServersList(Collections.emptyList()); } } } @Override public Server chooseServer(Object key) { if (!enabled.getOrDefault() || getLoadBalancerStats().getAvailableZones().size() <= 1) { logger.debug("Zone aware logic disabled or there is only one zone"); return super.chooseServer(key); } Server server = null; try { LoadBalancerStats lbStats = getLoadBalancerStats(); Map<String, ZoneSnapshot> zoneSnapshot = ZoneAvoidanceRule.createSnapshot(lbStats); logger.debug("Zone snapshots: {}", zoneSnapshot); Set<String> availableZones = ZoneAvoidanceRule.getAvailableZones(zoneSnapshot, triggeringLoad.getOrDefault(), triggeringBlackoutPercentage.getOrDefault()); logger.debug("Available zones: {}", availableZones); if (availableZones != null && availableZones.size() < zoneSnapshot.keySet().size()) { String zone = ZoneAvoidanceRule.randomChooseZone(zoneSnapshot, availableZones); logger.debug("Zone chosen: {}", zone); if (zone != null) { BaseLoadBalancer zoneLoadBalancer = getLoadBalancer(zone); server = zoneLoadBalancer.chooseServer(key); } } } catch (Exception e) { logger.error("Error choosing server using zone aware logic for load balancer={}", name, e); } if (server != null) { return server; } else { logger.debug("Zone avoidance logic is not invoked."); return super.chooseServer(key); } } @VisibleForTesting BaseLoadBalancer getLoadBalancer(String zone) { zone = zone.toLowerCase(); BaseLoadBalancer loadBalancer = balancers.get(zone); if (loadBalancer == null) { // We need to create rule object for load balancer for each zone IRule rule = cloneRule(this.getRule()); loadBalancer = new BaseLoadBalancer(this.getName() + "_" + zone, rule, this.getLoadBalancerStats()); BaseLoadBalancer prev = balancers.putIfAbsent(zone, loadBalancer); if (prev != null) { loadBalancer = prev; } } return loadBalancer; } private IRule cloneRule(IRule toClone) { IRule rule; if (toClone == null) { rule = new AvailabilityFilteringRule(); } else { String ruleClass = toClone.getClass().getName(); try { rule = (IRule) ClientFactory.instantiateInstanceWithClientConfig(ruleClass, this.getClientConfig()); } catch (Exception e) { throw new RuntimeException("Unexpected exception creating rule for ZoneAwareLoadBalancer", e); } } return rule; } @Override public void setRule(IRule rule) { super.setRule(rule); if (balancers != null) { for (String zone: balancers.keySet()) { balancers.get(zone).setRule(cloneRule(rule)); } } } }
7,037
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/AbstractServerListFilter.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.loadbalancer; /** * Class that is responsible to Filter out list of servers from the ones * currently available in the Load Balancer * @author stonse * * @param <T> */ public abstract class AbstractServerListFilter<T extends Server> implements ServerListFilter<T> { private volatile LoadBalancerStats stats; public void setLoadBalancerStats(LoadBalancerStats stats) { this.stats = stats; } public LoadBalancerStats getLoadBalancerStats() { return stats; } }
7,038
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/AbstractLoadBalancerRule.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.loadbalancer; import com.netflix.client.IClientConfigAware; /** * Class that provides a default implementation for setting and getting load balancer * @author stonse * */ public abstract class AbstractLoadBalancerRule implements IRule, IClientConfigAware { private ILoadBalancer lb; @Override public void setLoadBalancer(ILoadBalancer lb){ this.lb = lb; } @Override public ILoadBalancer getLoadBalancer(){ return lb; } }
7,039
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/AvailabilityFilteringRule.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.loadbalancer; import java.util.List; import com.google.common.collect.Collections2; import com.netflix.client.config.IClientConfig; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.annotations.Monitor; /** * A load balancer rule that filters out servers that: * <ul> * <li> are in circuit breaker tripped state due to consecutive connection or read failures, or</li> * <li> have active connections that exceeds a configurable limit (default is Integer.MAX_VALUE).</li> * </ul> * The property * to change this limit is * <pre>{@code * * <clientName>.<nameSpace>.ActiveConnectionsLimit * * }</pre> * * <p> * * @author awang * */ public class AvailabilityFilteringRule extends PredicateBasedRule { private AbstractServerPredicate predicate; public AvailabilityFilteringRule() { super(); predicate = CompositePredicate.withPredicate(new AvailabilityPredicate(this, null)) .addFallbackPredicate(AbstractServerPredicate.alwaysTrue()) .build(); } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { predicate = CompositePredicate.withPredicate(new AvailabilityPredicate(this, clientConfig)) .addFallbackPredicate(AbstractServerPredicate.alwaysTrue()) .build(); } @Monitor(name="AvailableServersCount", type = DataSourceType.GAUGE) public int getAvailableServersCount() { ILoadBalancer lb = getLoadBalancer(); List<Server> servers = lb.getAllServers(); if (servers == null) { return 0; } return Collections2.filter(servers, predicate.getServerOnlyPredicate()).size(); } /** * This method is overridden to provide a more efficient implementation which does not iterate through * all servers. This is under the assumption that in most cases, there are more available instances * than not. */ @Override public Server choose(Object key) { int count = 0; Server server = roundRobinRule.choose(key); while (count++ <= 10) { if (server != null && predicate.apply(new PredicateKey(server))) { return server; } server = roundRobinRule.choose(key); } return super.choose(key); } @Override public AbstractServerPredicate getPredicate() { return predicate; } }
7,040
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/IPingStrategy.java
package com.netflix.loadbalancer; /** * Defines the strategy, used to ping all servers, registered in * <b>com.netflix.loadbalancer.BaseLoadBalancer</b>. You would * typically create custom implementation of this interface, if you * want your servers to be pinged in parallel. <b>Please note, * that implementations of this interface should be immutable.</b> * * @author Dmitry_Cherkas * @see Server * @see IPing */ public interface IPingStrategy { boolean[] pingServers(IPing ping, Server[] servers); }
7,041
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/BestAvailableRule.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.loadbalancer; import java.util.List; /** * A rule that skips servers with "tripped" circuit breaker and picks the * server with lowest concurrent requests. * <p> * This rule should typically work with {@link ServerListSubsetFilter} which puts a limit on the * servers that is visible to the rule. This ensure that it only needs to find the minimal * concurrent requests among a small number of servers. Also, each client will get a random list of * servers which avoids the problem that one server with the lowest concurrent requests is * chosen by a large number of clients and immediately gets overwhelmed. * * @author awang * */ public class BestAvailableRule extends ClientConfigEnabledRoundRobinRule { private LoadBalancerStats loadBalancerStats; @Override public Server choose(Object key) { if (loadBalancerStats == null) { return super.choose(key); } List<Server> serverList = getLoadBalancer().getAllServers(); int minimalConcurrentConnections = Integer.MAX_VALUE; long currentTime = System.currentTimeMillis(); Server chosen = null; for (Server server: serverList) { ServerStats serverStats = loadBalancerStats.getSingleServerStat(server); if (!serverStats.isCircuitBreakerTripped(currentTime)) { int concurrentConnections = serverStats.getActiveRequestsCount(currentTime); if (concurrentConnections < minimalConcurrentConnections) { minimalConcurrentConnections = concurrentConnections; chosen = server; } } } if (chosen == null) { return super.choose(key); } else { return chosen; } } @Override public void setLoadBalancer(ILoadBalancer lb) { super.setLoadBalancer(lb); if (lb instanceof AbstractLoadBalancer) { loadBalancerStats = ((AbstractLoadBalancer) lb).getLoadBalancerStats(); } } }
7,042
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ServerListFilter.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.loadbalancer; import java.util.List; /** * This interface allows for filtering the configured or dynamically obtained * List of candidate servers with desirable characteristics. * * @author stonse * * @param <T> */ public interface ServerListFilter<T extends Server> { public List<T> getFilteredListOfServers(List<T> servers); }
7,043
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ZoneAvoidanceRule.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.loadbalancer; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Random; import java.util.Set; import com.netflix.client.config.IClientConfig; /** * A rule that uses the a {@link CompositePredicate} to filter servers based on zone and availability. The primary predicate is composed of * a {@link ZoneAvoidancePredicate} and {@link AvailabilityPredicate}, with the fallbacks to {@link AvailabilityPredicate} * and an "always true" predicate returned from {@link AbstractServerPredicate#alwaysTrue()} * * @author awang * */ public class ZoneAvoidanceRule extends PredicateBasedRule { private static final Random random = new Random(); private CompositePredicate compositePredicate; public ZoneAvoidanceRule() { ZoneAvoidancePredicate zonePredicate = new ZoneAvoidancePredicate(this); AvailabilityPredicate availabilityPredicate = new AvailabilityPredicate(this); compositePredicate = createCompositePredicate(zonePredicate, availabilityPredicate); } private CompositePredicate createCompositePredicate(ZoneAvoidancePredicate p1, AvailabilityPredicate p2) { return CompositePredicate.withPredicates(p1, p2) .addFallbackPredicate(p2) .addFallbackPredicate(AbstractServerPredicate.alwaysTrue()) .build(); } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { ZoneAvoidancePredicate zonePredicate = new ZoneAvoidancePredicate(this, clientConfig); AvailabilityPredicate availabilityPredicate = new AvailabilityPredicate(this, clientConfig); compositePredicate = createCompositePredicate(zonePredicate, availabilityPredicate); } static Map<String, ZoneSnapshot> createSnapshot(LoadBalancerStats lbStats) { Map<String, ZoneSnapshot> map = new HashMap<String, ZoneSnapshot>(); for (String zone : lbStats.getAvailableZones()) { ZoneSnapshot snapshot = lbStats.getZoneSnapshot(zone); map.put(zone, snapshot); } return map; } static String randomChooseZone(Map<String, ZoneSnapshot> snapshot, Set<String> chooseFrom) { if (chooseFrom == null || chooseFrom.size() == 0) { return null; } String selectedZone = chooseFrom.iterator().next(); if (chooseFrom.size() == 1) { return selectedZone; } int totalServerCount = 0; for (String zone : chooseFrom) { totalServerCount += snapshot.get(zone).getInstanceCount(); } int index = random.nextInt(totalServerCount) + 1; int sum = 0; for (String zone : chooseFrom) { sum += snapshot.get(zone).getInstanceCount(); if (index <= sum) { selectedZone = zone; break; } } return selectedZone; } public static Set<String> getAvailableZones( Map<String, ZoneSnapshot> snapshot, double triggeringLoad, double triggeringBlackoutPercentage) { if (snapshot.isEmpty()) { return null; } Set<String> availableZones = new HashSet<String>(snapshot.keySet()); if (availableZones.size() == 1) { return availableZones; } Set<String> worstZones = new HashSet<String>(); double maxLoadPerServer = 0; boolean limitedZoneAvailability = false; for (Map.Entry<String, ZoneSnapshot> zoneEntry : snapshot.entrySet()) { String zone = zoneEntry.getKey(); ZoneSnapshot zoneSnapshot = zoneEntry.getValue(); int instanceCount = zoneSnapshot.getInstanceCount(); if (instanceCount == 0) { availableZones.remove(zone); limitedZoneAvailability = true; } else { double loadPerServer = zoneSnapshot.getLoadPerServer(); if (((double) zoneSnapshot.getCircuitTrippedCount()) / instanceCount >= triggeringBlackoutPercentage || loadPerServer < 0) { availableZones.remove(zone); limitedZoneAvailability = true; } else { if (Math.abs(loadPerServer - maxLoadPerServer) < 0.000001d) { // they are the same considering double calculation // round error worstZones.add(zone); } else if (loadPerServer > maxLoadPerServer) { maxLoadPerServer = loadPerServer; worstZones.clear(); worstZones.add(zone); } } } } if (maxLoadPerServer < triggeringLoad && !limitedZoneAvailability) { // zone override is not needed here return availableZones; } String zoneToAvoid = randomChooseZone(snapshot, worstZones); if (zoneToAvoid != null) { availableZones.remove(zoneToAvoid); } return availableZones; } public static Set<String> getAvailableZones(LoadBalancerStats lbStats, double triggeringLoad, double triggeringBlackoutPercentage) { if (lbStats == null) { return null; } Map<String, ZoneSnapshot> snapshot = createSnapshot(lbStats); return getAvailableZones(snapshot, triggeringLoad, triggeringBlackoutPercentage); } @Override public AbstractServerPredicate getPredicate() { return compositePredicate; } }
7,044
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ServerListChangeListener.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.loadbalancer; import java.util.List; public interface ServerListChangeListener { /** * Invoked by {@link BaseLoadBalancer} when server list is changed */ public void serverListChanged(List<Server> oldList, List<Server> newList); }
7,045
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/DynamicServerListLoadBalancer.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.loadbalancer; import com.google.common.annotations.VisibleForTesting; import com.netflix.client.ClientFactory; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.annotations.Monitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; /** * A LoadBalancer that has the capabilities to obtain the candidate list of * servers using a dynamic source. i.e. The list of servers can potentially be * changed at Runtime. It also contains facilities wherein the list of servers * can be passed through a Filter criteria to filter out servers that do not * meet the desired criteria. * * @author stonse * */ public class DynamicServerListLoadBalancer<T extends Server> extends BaseLoadBalancer { private static final Logger LOGGER = LoggerFactory.getLogger(DynamicServerListLoadBalancer.class); boolean isSecure = false; boolean useTunnel = false; // to keep track of modification of server lists protected AtomicBoolean serverListUpdateInProgress = new AtomicBoolean(false); volatile ServerList<T> serverListImpl; volatile ServerListFilter<T> filter; protected final ServerListUpdater.UpdateAction updateAction = new ServerListUpdater.UpdateAction() { @Override public void doUpdate() { updateListOfServers(); } }; protected volatile ServerListUpdater serverListUpdater; public DynamicServerListLoadBalancer() { super(); } @Deprecated public DynamicServerListLoadBalancer(IClientConfig clientConfig, IRule rule, IPing ping, ServerList<T> serverList, ServerListFilter<T> filter) { this( clientConfig, rule, ping, serverList, filter, new PollingServerListUpdater() ); } public DynamicServerListLoadBalancer(IClientConfig clientConfig, IRule rule, IPing ping, ServerList<T> serverList, ServerListFilter<T> filter, ServerListUpdater serverListUpdater) { super(clientConfig, rule, ping); this.serverListImpl = serverList; this.filter = filter; this.serverListUpdater = serverListUpdater; if (filter instanceof AbstractServerListFilter) { ((AbstractServerListFilter) filter).setLoadBalancerStats(getLoadBalancerStats()); } restOfInit(clientConfig); } public DynamicServerListLoadBalancer(IClientConfig clientConfig) { initWithNiwsConfig(clientConfig); } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { this.initWithNiwsConfig(clientConfig, ClientFactory::instantiateInstanceWithClientConfig); } @Override public void initWithNiwsConfig(IClientConfig clientConfig, Factory factory) { try { super.initWithNiwsConfig(clientConfig, factory); String niwsServerListClassName = clientConfig.getOrDefault(CommonClientConfigKey.NIWSServerListClassName); ServerList<T> niwsServerListImpl = (ServerList<T>) factory.create(niwsServerListClassName, clientConfig); this.serverListImpl = niwsServerListImpl; if (niwsServerListImpl instanceof AbstractServerList) { AbstractServerListFilter<T> niwsFilter = ((AbstractServerList) niwsServerListImpl) .getFilterImpl(clientConfig); niwsFilter.setLoadBalancerStats(getLoadBalancerStats()); this.filter = niwsFilter; } String serverListUpdaterClassName = clientConfig.getOrDefault( CommonClientConfigKey.ServerListUpdaterClassName); this.serverListUpdater = (ServerListUpdater) factory.create(serverListUpdaterClassName, clientConfig); restOfInit(clientConfig); } catch (Exception e) { throw new RuntimeException( "Exception while initializing NIWSDiscoveryLoadBalancer:" + clientConfig.getClientName() + ", niwsClientConfig:" + clientConfig, e); } } void restOfInit(IClientConfig clientConfig) { boolean primeConnection = this.isEnablePrimingConnections(); // turn this off to avoid duplicated asynchronous priming done in BaseLoadBalancer.setServerList() this.setEnablePrimingConnections(false); enableAndInitLearnNewServersFeature(); updateListOfServers(); if (primeConnection && this.getPrimeConnections() != null) { this.getPrimeConnections() .primeConnections(getReachableServers()); } this.setEnablePrimingConnections(primeConnection); LOGGER.info("DynamicServerListLoadBalancer for client {} initialized: {}", clientConfig.getClientName(), this.toString()); } @Override public void setServersList(List lsrv) { super.setServersList(lsrv); List<T> serverList = (List<T>) lsrv; Map<String, List<Server>> serversInZones = new HashMap<String, List<Server>>(); for (Server server : serverList) { // make sure ServerStats is created to avoid creating them on hot // path getLoadBalancerStats().getSingleServerStat(server); String zone = server.getZone(); if (zone != null) { zone = zone.toLowerCase(); List<Server> servers = serversInZones.get(zone); if (servers == null) { servers = new ArrayList<Server>(); serversInZones.put(zone, servers); } servers.add(server); } } setServerListForZones(serversInZones); } protected void setServerListForZones( Map<String, List<Server>> zoneServersMap) { LOGGER.debug("Setting server list for zones: {}", zoneServersMap); getLoadBalancerStats().updateZoneServerMapping(zoneServersMap); } public ServerList<T> getServerListImpl() { return serverListImpl; } public void setServerListImpl(ServerList<T> niwsServerList) { this.serverListImpl = niwsServerList; } public ServerListFilter<T> getFilter() { return filter; } public void setFilter(ServerListFilter<T> filter) { this.filter = filter; } public ServerListUpdater getServerListUpdater() { return serverListUpdater; } public void setServerListUpdater(ServerListUpdater serverListUpdater) { this.serverListUpdater = serverListUpdater; } @Override /** * Makes no sense to ping an inmemory disc client * */ public void forceQuickPing() { // no-op } /** * Feature that lets us add new instances (from AMIs) to the list of * existing servers that the LB will use Call this method if you want this * feature enabled */ public void enableAndInitLearnNewServersFeature() { LOGGER.info("Using serverListUpdater {}", serverListUpdater.getClass().getSimpleName()); serverListUpdater.start(updateAction); } private String getIdentifier() { return this.getClientConfig().getClientName(); } public void stopServerListRefreshing() { if (serverListUpdater != null) { serverListUpdater.stop(); } } @VisibleForTesting public void updateListOfServers() { List<T> servers = new ArrayList<T>(); if (serverListImpl != null) { servers = serverListImpl.getUpdatedListOfServers(); LOGGER.debug("List of Servers for {} obtained from Discovery client: {}", getIdentifier(), servers); if (filter != null) { servers = filter.getFilteredListOfServers(servers); LOGGER.debug("Filtered List of Servers for {} obtained from Discovery client: {}", getIdentifier(), servers); } } updateAllServerList(servers); } /** * Update the AllServer list in the LoadBalancer if necessary and enabled * * @param ls */ protected void updateAllServerList(List<T> ls) { // other threads might be doing this - in which case, we pass if (serverListUpdateInProgress.compareAndSet(false, true)) { try { for (T s : ls) { s.setAlive(true); // set so that clients can start using these // servers right away instead // of having to wait out the ping cycle. } setServersList(ls); super.forceQuickPing(); } finally { serverListUpdateInProgress.set(false); } } } @Override public String toString() { StringBuilder sb = new StringBuilder("DynamicServerListLoadBalancer:"); sb.append(super.toString()); sb.append("ServerList:" + String.valueOf(serverListImpl)); return sb.toString(); } @Override public void shutdown() { super.shutdown(); stopServerListRefreshing(); } @Monitor(name="LastUpdated", type=DataSourceType.INFORMATIONAL) public String getLastUpdate() { return serverListUpdater.getLastUpdate(); } @Monitor(name="DurationSinceLastUpdateMs", type= DataSourceType.GAUGE) public long getDurationSinceLastUpdateMs() { return serverListUpdater.getDurationSinceLastUpdateMs(); } @Monitor(name="NumUpdateCyclesMissed", type=DataSourceType.GAUGE) public int getNumberMissedCycles() { return serverListUpdater.getNumberMissedCycles(); } @Monitor(name="NumThreads", type=DataSourceType.GAUGE) public int getCoreThreads() { return serverListUpdater.getCoreThreads(); } }
7,046
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/PingConstant.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.loadbalancer; /** * A utility Ping Implementation that returns whatever its been set to return * (alive or dead) * @author stonse * */ public class PingConstant implements IPing { boolean constant = true; public void setConstant(String constantStr) { constant = (constantStr != null) && (constantStr.toLowerCase().equals("true")); } public void setConstant(boolean constant) { this.constant = constant; } public boolean getConstant() { return constant; } public boolean isAlive(Server server) { return constant; } }
7,047
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/LoadBalancerBuilder.java
package com.netflix.loadbalancer; import com.netflix.client.ClientFactory; import com.netflix.client.IClientConfigAware; import com.netflix.client.config.ClientConfigFactory; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import java.util.List; public class LoadBalancerBuilder<T extends Server> { private IClientConfig config = ClientConfigFactory.findDefaultConfigFactory().newConfig(); private ServerListFilter serverListFilter; private IRule rule; private IPing ping = new DummyPing(); private ServerList serverListImpl; private ServerListUpdater serverListUpdater; private IClientConfigAware.Factory factory = ClientFactory::instantiateInstanceWithClientConfig; private LoadBalancerBuilder() { } public static <T extends Server> LoadBalancerBuilder<T> newBuilder() { return new LoadBalancerBuilder<T>(); } public LoadBalancerBuilder<T> withFactory(IClientConfigAware.Factory factory) { this.factory = factory; return this; } public LoadBalancerBuilder<T> withClientConfig(IClientConfig config) { this.config = config; return this; } public LoadBalancerBuilder<T> withRule(IRule rule) { this.rule = rule; return this; } public LoadBalancerBuilder<T> withPing(IPing ping) { this.ping = ping; return this; } public LoadBalancerBuilder<T> withDynamicServerList(ServerList<T> serverListImpl) { this.serverListImpl = serverListImpl; return this; } public LoadBalancerBuilder<T> withServerListFilter(ServerListFilter<T> serverListFilter) { this.serverListFilter = serverListFilter; return this; } public LoadBalancerBuilder<T> withServerListUpdater(ServerListUpdater serverListUpdater) { this.serverListUpdater = serverListUpdater; return this; } public BaseLoadBalancer buildFixedServerListLoadBalancer(List<T> servers) { if (rule == null) { rule = createRuleFromConfig(config, factory); } BaseLoadBalancer lb = new BaseLoadBalancer(config, rule, ping); lb.setServersList(servers); return lb; } private static IRule createRuleFromConfig(IClientConfig config, IClientConfigAware.Factory factory) { String ruleClassName = config.getOrDefault(IClientConfigKey.Keys.NFLoadBalancerRuleClassName); if (ruleClassName == null) { throw new IllegalArgumentException("NFLoadBalancerRuleClassName is not specified in the config"); } IRule rule; try { rule = (IRule) factory.create(ruleClassName, config); } catch (Exception e) { throw new RuntimeException(e); } return rule; } private static ServerListUpdater createServerListUpdaterFromConfig(IClientConfig config, IClientConfigAware.Factory factory) { String serverListUpdaterClassName = config.getOrDefault(IClientConfigKey.Keys.ServerListUpdaterClassName); if (serverListUpdaterClassName == null) { throw new IllegalArgumentException("NIWSServerListClassName is not specified in the config"); } ServerListUpdater updater; try { updater = (ServerListUpdater) factory.create(serverListUpdaterClassName, config); } catch (Exception e) { throw new RuntimeException(e); } return updater; } private static ServerList<Server> createServerListFromConfig(IClientConfig config, IClientConfigAware.Factory factory) { String serverListClassName = config.get(IClientConfigKey.Keys.NIWSServerListClassName); if (serverListClassName == null) { throw new IllegalArgumentException("NIWSServerListClassName is not specified in the config"); } ServerList<Server> list; try { list = (ServerList<Server>) factory.create(serverListClassName, config); } catch (Exception e) { throw new RuntimeException(e); } return list; } /** * Build a {@link ZoneAwareLoadBalancer} with a dynamic {@link ServerList} and an {@link IRule}. The {@link ServerList} can be * either set in the {@link #withDynamicServerList(ServerList)} or in the {@link IClientConfig} using {@link CommonClientConfigKey#NIWSServerListClassName}. * The {@link IRule} can be either set by {@link #withRule(IRule)} or in the {@link IClientConfig} using * {@link CommonClientConfigKey#NFLoadBalancerRuleClassName}. */ public ZoneAwareLoadBalancer<T> buildDynamicServerListLoadBalancer() { if (serverListImpl == null) { serverListImpl = createServerListFromConfig(config, factory); } if (rule == null) { rule = createRuleFromConfig(config, factory); } return new ZoneAwareLoadBalancer<T>(config, rule, ping, serverListImpl, serverListFilter); } /** * Build a {@link ZoneAwareLoadBalancer} with a dynamic {@link ServerList} and an {@link IRule} and a {@link ServerListUpdater}. * * The {@link ServerList} can be either set in the {@link #withDynamicServerList(ServerList)} or in the {@link IClientConfig} * using {@link CommonClientConfigKey#NIWSServerListClassName}. * The {@link IRule} can be either set by {@link #withRule(IRule)} or in the {@link IClientConfig} using * {@link CommonClientConfigKey#NFLoadBalancerRuleClassName}. * The {@link ServerListUpdater} can be either set by {@link #withServerListUpdater(ServerListUpdater)} or * in the {@link IClientConfig} using {@link CommonClientConfigKey#ServerListUpdaterClassName}. */ public ZoneAwareLoadBalancer<T> buildDynamicServerListLoadBalancerWithUpdater() { if (serverListImpl == null) { serverListImpl = createServerListFromConfig(config, factory); } if (rule == null) { rule = createRuleFromConfig(config, factory); } if (serverListUpdater == null) { serverListUpdater = createServerListUpdaterFromConfig(config, factory); } return new ZoneAwareLoadBalancer<T>(config, rule, ping, serverListImpl, serverListFilter, serverListUpdater); } /** * Build a load balancer using the configuration from the {@link IClientConfig} only. It uses reflection to initialize necessary load balancer * components. */ public ILoadBalancer buildLoadBalancerFromConfigWithReflection() { String loadBalancerClassName = config.get(CommonClientConfigKey.NFLoadBalancerClassName); if (loadBalancerClassName == null) { throw new IllegalArgumentException("NFLoadBalancerClassName is not specified in the IClientConfig"); } ILoadBalancer lb; try { lb = (ILoadBalancer) factory.create(loadBalancerClassName, config); } catch (Exception e) { throw new RuntimeException(e); } return lb; } }
7,048
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ServerComparator.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.loadbalancer; import java.io.Serializable; import java.util.Comparator; /** * Class to help establishing equality for Hash/Key operations. * * @author stonse * */ public class ServerComparator implements Comparator<Server>, Serializable { /** * */ private static final long serialVersionUID = 1L; public int compare(Server s1, Server s2) { return s1.getHostPort().compareTo(s2.getId()); } }
7,049
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ZoneStats.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.loadbalancer; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.annotations.Monitor; import com.netflix.servo.monitor.Counter; import com.netflix.servo.monitor.Monitors; /** * Class that stores Statistics per Zone (where Zone is typically a Amazon * Availability Zone) * * @author awang * * @param <T> */ public class ZoneStats<T extends Server> { private final LoadBalancerStats loadBalancerStats; private final String zone; private static final String PREFIX = "ZoneStats_"; private final Counter counter; final String monitorId; public ZoneStats(String name, String zone, LoadBalancerStats loadBalancerStats) { this.zone = zone; this.loadBalancerStats = loadBalancerStats; monitorId = name + ":" + zone; counter = Monitors.newCounter(PREFIX + name + "_" + zone + "_Counter"); Monitors.registerObject(monitorId, this); } public final String getZone() { return zone; } @Monitor(name=PREFIX + "ActiveRequestsCount", type = DataSourceType.INFORMATIONAL) public int getActiveRequestsCount() { return loadBalancerStats.getActiveRequestsCount(zone); } @Monitor(name=PREFIX + "InstanceCount", type = DataSourceType.GAUGE) public int getInstanceCount() { return loadBalancerStats.getInstanceCount(zone); } @Monitor(name=PREFIX + "CircuitBreakerTrippedCount", type = DataSourceType.GAUGE) public int getCircuitBreakerTrippedCount() { return loadBalancerStats.getCircuitBreakerTrippedCount(zone); } @Monitor(name=PREFIX + "ActiveRequestsPerServer", type = DataSourceType.GAUGE) public double getActiveRequestsPerServer() { return loadBalancerStats.getActiveRequestsPerServer(zone); } // @Monitor(name=PREFIX + "RequestsMadeLast5Minutes", type = DataSourceType.GAUGE) public long getMeasuredZoneHits() { return loadBalancerStats.getMeasuredZoneHits(zone); } @Monitor(name=PREFIX + "CircuitBreakerTrippedPercentage", type = DataSourceType.INFORMATIONAL) public double getCircuitBreakerTrippedPercentage() { ZoneSnapshot snapShot = loadBalancerStats.getZoneSnapshot(zone); int totalCount = snapShot.getInstanceCount(); int circuitTrippedCount = snapShot.getCircuitTrippedCount(); if (totalCount == 0) { if (circuitTrippedCount != 0) { return -1; } else { return 0; } } else { return snapShot.getCircuitTrippedCount() / ((double) totalCount); } } void incrementCounter() { counter.increment(); } @Override public String toString(){ StringBuilder sb = new StringBuilder(); sb.append("[Zone:" + zone + ";"); sb.append("\tInstance count:" + getInstanceCount() + ";"); sb.append("\tActive connections count: " + getActiveRequestsCount() + ";"); sb.append("\tCircuit breaker tripped count: " + getCircuitBreakerTrippedCount() + ";"); sb.append("\tActive connections per server: " + getActiveRequestsPerServer() + ";"); sb.append("]\n"); return sb.toString(); } }
7,050
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/Server.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.loadbalancer; import com.netflix.util.Pair; /** * Class that represents a typical Server (or an addressable Node) i.e. a * Host:port identifier * * @author stonse * */ public class Server { /** * Additional meta information of a server, which contains * information of the targeting application, as well as server identification * specific for a deployment environment, for example, AWS. */ public static interface MetaInfo { /** * @return the name of application that runs on this server, null if not available */ public String getAppName(); /** * @return the group of the server, for example, auto scaling group ID in AWS. * Null if not available */ public String getServerGroup(); /** * @return A virtual address used by the server to register with discovery service. * Null if not available */ public String getServiceIdForDiscovery(); /** * @return ID of the server */ public String getInstanceId(); } public static final String UNKNOWN_ZONE = "UNKNOWN"; private String host; private int port = 80; private String scheme; private volatile String id; private volatile boolean isAliveFlag; private String zone = UNKNOWN_ZONE; private volatile boolean readyToServe = true; private MetaInfo simpleMetaInfo = new MetaInfo() { @Override public String getAppName() { return null; } @Override public String getServerGroup() { return null; } @Override public String getServiceIdForDiscovery() { return null; } @Override public String getInstanceId() { return id; } }; public Server(String host, int port) { this(null, host, port); } public Server(String scheme, String host, int port) { this.scheme = scheme; this.host = host; this.port = port; this.id = host + ":" + port; isAliveFlag = false; } /* host:port combination */ public Server(String id) { setId(id); isAliveFlag = false; } // No reason to synchronize this, I believe. // The assignment should be atomic, and two setAlive calls // with conflicting results will still give nonsense(last one wins) // synchronization or no. public void setAlive(boolean isAliveFlag) { this.isAliveFlag = isAliveFlag; } public boolean isAlive() { return isAliveFlag; } @Deprecated public void setHostPort(String hostPort) { setId(hostPort); } static public String normalizeId(String id) { Pair<String, Integer> hostPort = getHostPort(id); if (hostPort == null) { return null; } else { return hostPort.first() + ":" + hostPort.second(); } } private static String getScheme(String id) { if (id != null) { if (id.toLowerCase().startsWith("http://")) { return "http"; } else if (id.toLowerCase().startsWith("https://")) { return "https"; } } return null; } static Pair<String, Integer> getHostPort(String id) { if (id != null) { String host = null; int port = 80; if (id.toLowerCase().startsWith("http://")) { id = id.substring(7); port = 80; } else if (id.toLowerCase().startsWith("https://")) { id = id.substring(8); port = 443; } if (id.contains("/")) { int slash_idx = id.indexOf("/"); id = id.substring(0, slash_idx); } int colon_idx = id.indexOf(':'); if (colon_idx == -1) { host = id; // default } else { host = id.substring(0, colon_idx); try { port = Integer.parseInt(id.substring(colon_idx + 1)); } catch (NumberFormatException e) { throw e; } } return new Pair<String, Integer>(host, port); } else { return null; } } public void setId(String id) { Pair<String, Integer> hostPort = getHostPort(id); if (hostPort != null) { this.id = hostPort.first() + ":" + hostPort.second(); this.host = hostPort.first(); this.port = hostPort.second(); this.scheme = getScheme(id); } else { this.id = null; } } public void setSchemea(String scheme) { this.scheme = scheme; } public void setPort(int port) { this.port = port; if (host != null) { id = host + ":" + port; } } public void setHost(String host) { if (host != null) { this.host = host; id = host + ":" + port; } } public String getId() { return id; } public String getHost() { return host; } public int getPort() { return port; } public String getScheme() { return scheme; } public String getHostPort() { return host + ":" + port; } public MetaInfo getMetaInfo() { return simpleMetaInfo; } public String toString() { return this.getId(); } public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Server)) return false; Server svc = (Server) obj; return svc.getId().equals(this.getId()); } public int hashCode() { int hash = 7; hash = 31 * hash + (null == this.getId() ? 0 : this.getId().hashCode()); return hash; } public final String getZone() { return zone; } public final void setZone(String zone) { this.zone = zone; } public final boolean isReadyToServe() { return readyToServe; } public final void setReadyToServe(boolean readyToServe) { this.readyToServe = readyToServe; } }
7,051
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ServerListUpdater.java
package com.netflix.loadbalancer; /** * strategy for {@link com.netflix.loadbalancer.DynamicServerListLoadBalancer} to use for different ways * of doing dynamic server list updates. * * @author David Liu */ public interface ServerListUpdater { /** * an interface for the updateAction that actually executes a server list update */ public interface UpdateAction { void doUpdate(); } /** * start the serverList updater with the given update action * This call should be idempotent. * * @param updateAction */ void start(UpdateAction updateAction); /** * stop the serverList updater. This call should be idempotent */ void stop(); /** * @return the last update timestamp as a {@link java.util.Date} string */ String getLastUpdate(); /** * @return the number of ms that has elapsed since last update */ long getDurationSinceLastUpdateMs(); /** * @return the number of update cycles missed, if valid */ int getNumberMissedCycles(); /** * @return the number of threads used, if vaid */ int getCoreThreads(); }
7,052
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/LoadBalancerContext.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.loadbalancer; import com.google.common.base.Strings; import com.netflix.client.ClientException; import com.netflix.client.ClientRequest; import com.netflix.client.DefaultLoadBalancerRetryHandler; import com.netflix.client.IClientConfigAware; import com.netflix.client.RetryHandler; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import com.netflix.servo.monitor.Monitors; import com.netflix.servo.monitor.Timer; import com.netflix.util.Pair; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.net.URI; import java.net.URISyntaxException; import java.util.concurrent.TimeUnit; /** * A class contains APIs intended to be used be load balancing client which is subclass of this class. * * @author awang */ public class LoadBalancerContext implements IClientConfigAware { private static final Logger logger = LoggerFactory.getLogger(LoadBalancerContext.class); protected String clientName = "default"; protected String vipAddresses; protected int maxAutoRetriesNextServer = CommonClientConfigKey.MaxAutoRetriesNextServer.defaultValue(); protected int maxAutoRetries = CommonClientConfigKey.MaxAutoRetries.defaultValue(); protected RetryHandler defaultRetryHandler = new DefaultLoadBalancerRetryHandler(); protected boolean okToRetryOnAllOperations = CommonClientConfigKey.OkToRetryOnAllOperations.defaultValue(); private ILoadBalancer lb; private volatile Timer tracer; public LoadBalancerContext(ILoadBalancer lb) { this.lb = lb; } /** * Delegate to {@link #initWithNiwsConfig(IClientConfig)} * @param clientConfig */ public LoadBalancerContext(ILoadBalancer lb, IClientConfig clientConfig) { this.lb = lb; initWithNiwsConfig(clientConfig); } public LoadBalancerContext(ILoadBalancer lb, IClientConfig clientConfig, RetryHandler handler) { this(lb, clientConfig); this.defaultRetryHandler = handler; } /** * Set necessary parameters from client configuration and register with Servo monitors. */ @Override public void initWithNiwsConfig(IClientConfig clientConfig) { if (clientConfig == null) { return; } clientName = clientConfig.getClientName(); if (StringUtils.isEmpty(clientName)) { clientName = "default"; } vipAddresses = clientConfig.resolveDeploymentContextbasedVipAddresses(); maxAutoRetries = clientConfig.getOrDefault(CommonClientConfigKey.MaxAutoRetries); maxAutoRetriesNextServer = clientConfig.getOrDefault(CommonClientConfigKey.MaxAutoRetriesNextServer); okToRetryOnAllOperations = clientConfig.getOrDefault(CommonClientConfigKey.OkToRetryOnAllOperations); defaultRetryHandler = new DefaultLoadBalancerRetryHandler(clientConfig); tracer = getExecuteTracer(); Monitors.registerObject("Client_" + clientName, this); } public Timer getExecuteTracer() { if (tracer == null) { synchronized(this) { if (tracer == null) { tracer = Monitors.newTimer(clientName + "_LoadBalancerExecutionTimer", TimeUnit.MILLISECONDS); } } } return tracer; } public String getClientName() { return clientName; } public ILoadBalancer getLoadBalancer() { return lb; } public void setLoadBalancer(ILoadBalancer lb) { this.lb = lb; } /** * Use {@link #getRetryHandler()} */ @Deprecated public int getMaxAutoRetriesNextServer() { return maxAutoRetriesNextServer; } /** * Use {@link #setRetryHandler(RetryHandler)} */ @Deprecated public void setMaxAutoRetriesNextServer(int maxAutoRetriesNextServer) { this.maxAutoRetriesNextServer = maxAutoRetriesNextServer; } /** * Use {@link #getRetryHandler()} */ @Deprecated public int getMaxAutoRetries() { return maxAutoRetries; } /** * Use {@link #setRetryHandler(RetryHandler)} */ @Deprecated public void setMaxAutoRetries(int maxAutoRetries) { this.maxAutoRetries = maxAutoRetries; } protected Throwable getDeepestCause(Throwable e) { if(e != null) { int infiniteLoopPreventionCounter = 10; while (e.getCause() != null && infiniteLoopPreventionCounter > 0) { infiniteLoopPreventionCounter--; e = e.getCause(); } } return e; } private boolean isPresentAsCause(Throwable throwableToSearchIn, Class<? extends Throwable> throwableToSearchFor) { return isPresentAsCauseHelper(throwableToSearchIn, throwableToSearchFor) != null; } static Throwable isPresentAsCauseHelper(Throwable throwableToSearchIn, Class<? extends Throwable> throwableToSearchFor) { int infiniteLoopPreventionCounter = 10; while (throwableToSearchIn != null && infiniteLoopPreventionCounter > 0) { infiniteLoopPreventionCounter--; if (throwableToSearchIn.getClass().isAssignableFrom( throwableToSearchFor)) { return throwableToSearchIn; } else { throwableToSearchIn = throwableToSearchIn.getCause(); } } return null; } protected ClientException generateNIWSException(String uri, Throwable e){ ClientException niwsClientException; if (isPresentAsCause(e, java.net.SocketTimeoutException.class)) { niwsClientException = generateTimeoutNIWSException(uri, e); }else if (e.getCause() instanceof java.net.UnknownHostException){ niwsClientException = new ClientException( ClientException.ErrorType.UNKNOWN_HOST_EXCEPTION, "Unable to execute RestClient request for URI:" + uri, e); }else if (e.getCause() instanceof java.net.ConnectException){ niwsClientException = new ClientException( ClientException.ErrorType.CONNECT_EXCEPTION, "Unable to execute RestClient request for URI:" + uri, e); }else if (e.getCause() instanceof java.net.NoRouteToHostException){ niwsClientException = new ClientException( ClientException.ErrorType.NO_ROUTE_TO_HOST_EXCEPTION, "Unable to execute RestClient request for URI:" + uri, e); }else if (e instanceof ClientException){ niwsClientException = (ClientException)e; }else { niwsClientException = new ClientException( ClientException.ErrorType.GENERAL, "Unable to execute RestClient request for URI:" + uri, e); } return niwsClientException; } private boolean isPresentAsCause(Throwable throwableToSearchIn, Class<? extends Throwable> throwableToSearchFor, String messageSubStringToSearchFor) { Throwable throwableFound = isPresentAsCauseHelper(throwableToSearchIn, throwableToSearchFor); if(throwableFound != null) { return throwableFound.getMessage().contains(messageSubStringToSearchFor); } return false; } private ClientException generateTimeoutNIWSException(String uri, Throwable e){ ClientException niwsClientException; if (isPresentAsCause(e, java.net.SocketTimeoutException.class, "Read timed out")) { niwsClientException = new ClientException( ClientException.ErrorType.READ_TIMEOUT_EXCEPTION, "Unable to execute RestClient request for URI:" + uri + ":" + getDeepestCause(e).getMessage(), e); } else { niwsClientException = new ClientException( ClientException.ErrorType.SOCKET_TIMEOUT_EXCEPTION, "Unable to execute RestClient request for URI:" + uri + ":" + getDeepestCause(e).getMessage(), e); } return niwsClientException; } private void recordStats(ServerStats stats, long responseTime) { if (stats == null) { return; } stats.decrementActiveRequestsCount(); stats.incrementNumRequests(); stats.noteResponseTime(responseTime); } protected void noteRequestCompletion(ServerStats stats, Object response, Throwable e, long responseTime) { if (stats == null) { return; } noteRequestCompletion(stats, response, e, responseTime, null); } /** * This is called after a response is received or an exception is thrown from the client * to update related stats. */ public void noteRequestCompletion(ServerStats stats, Object response, Throwable e, long responseTime, RetryHandler errorHandler) { if (stats == null) { return; } try { recordStats(stats, responseTime); RetryHandler callErrorHandler = errorHandler == null ? getRetryHandler() : errorHandler; if (callErrorHandler != null && response != null) { stats.clearSuccessiveConnectionFailureCount(); } else if (callErrorHandler != null && e != null) { if (callErrorHandler.isCircuitTrippingException(e)) { stats.incrementSuccessiveConnectionFailureCount(); stats.addToFailureCount(); } else { stats.clearSuccessiveConnectionFailureCount(); } } } catch (Exception ex) { logger.error("Error noting stats for client {}", clientName, ex); } } /** * This is called after an error is thrown from the client * to update related stats. */ protected void noteError(ServerStats stats, ClientRequest request, Throwable e, long responseTime) { if (stats == null) { return; } try { recordStats(stats, responseTime); RetryHandler errorHandler = getRetryHandler(); if (errorHandler != null && e != null) { if (errorHandler.isCircuitTrippingException(e)) { stats.incrementSuccessiveConnectionFailureCount(); stats.addToFailureCount(); } else { stats.clearSuccessiveConnectionFailureCount(); } } } catch (Exception ex) { logger.error("Error noting stats for client {}", clientName, ex); } } /** * This is called after a response is received from the client * to update related stats. */ protected void noteResponse(ServerStats stats, ClientRequest request, Object response, long responseTime) { if (stats == null) { return; } try { recordStats(stats, responseTime); RetryHandler errorHandler = getRetryHandler(); if (errorHandler != null && response != null) { stats.clearSuccessiveConnectionFailureCount(); } } catch (Exception ex) { logger.error("Error noting stats for client {}", clientName, ex); } } /** * This is usually called just before client execute a request. */ public void noteOpenConnection(ServerStats serverStats) { if (serverStats == null) { return; } try { serverStats.incrementActiveRequestsCount(); } catch (Exception ex) { logger.error("Error noting stats for client {}", clientName, ex); } } /** * Derive scheme and port from a partial URI. For example, for HTTP based client, the URI with * only path "/" should return "http" and 80, whereas the URI constructed with scheme "https" and * path "/" should return "https" and 443. * This method is called by {@link #getServerFromLoadBalancer(java.net.URI, Object)} and * {@link #reconstructURIWithServer(Server, java.net.URI)} methods to get the complete executable URI. */ protected Pair<String, Integer> deriveSchemeAndPortFromPartialUri(URI uri) { boolean isSecure = false; String scheme = uri.getScheme(); if (scheme != null) { isSecure = scheme.equalsIgnoreCase("https"); } int port = uri.getPort(); if (port < 0 && !isSecure){ port = 80; } else if (port < 0 && isSecure){ port = 443; } if (scheme == null){ if (isSecure) { scheme = "https"; } else { scheme = "http"; } } return new Pair<String, Integer>(scheme, port); } /** * Get the default port of the target server given the scheme of vip address if it is available. * Subclass should override it to provider protocol specific default port number if any. * * @param scheme from the vip address. null if not present. * @return 80 if scheme is http, 443 if scheme is https, -1 else. */ protected int getDefaultPortFromScheme(String scheme) { if (scheme == null) { return -1; } if (scheme.equals("http")) { return 80; } else if (scheme.equals("https")) { return 443; } else { return -1; } } /** * Derive the host and port from virtual address if virtual address is indeed contains the actual host * and port of the server. This is the final resort to compute the final URI in {@link #getServerFromLoadBalancer(java.net.URI, Object)} * if there is no load balancer available and the request URI is incomplete. Sub classes can override this method * to be more accurate or throws ClientException if it does not want to support virtual address to be the * same as physical server address. * <p> * The virtual address is used by certain load balancers to filter the servers of the same function * to form the server pool. * */ protected Pair<String, Integer> deriveHostAndPortFromVipAddress(String vipAddress) throws URISyntaxException, ClientException { Pair<String, Integer> hostAndPort = new Pair<String, Integer>(null, -1); URI uri = new URI(vipAddress); String scheme = uri.getScheme(); if (scheme == null) { uri = new URI("http://" + vipAddress); } String host = uri.getHost(); if (host == null) { throw new ClientException("Unable to derive host/port from vip address " + vipAddress); } int port = uri.getPort(); if (port < 0) { port = getDefaultPortFromScheme(scheme); } if (port < 0) { throw new ClientException("Unable to derive host/port from vip address " + vipAddress); } hostAndPort.setFirst(host); hostAndPort.setSecond(port); return hostAndPort; } private boolean isVipRecognized(String vipEmbeddedInUri) { if (vipEmbeddedInUri == null) { return false; } if (vipAddresses == null) { return false; } String[] addresses = vipAddresses.split(","); for (String address: addresses) { if (vipEmbeddedInUri.equalsIgnoreCase(address.trim())) { return true; } } return false; } /** * Compute the final URI from a partial URI in the request. The following steps are performed: * <ul> * <li> if host is missing and there is a load balancer, get the host/port from server chosen from load balancer * <li> if host is missing and there is no load balancer, try to derive host/port from virtual address set with the client * <li> if host is present and the authority part of the URI is a virtual address set for the client, * and there is a load balancer, get the host/port from server chosen from load balancer * <li> if host is present but none of the above applies, interpret the host as the actual physical address * <li> if host is missing but none of the above applies, throws ClientException * </ul> * * @param original Original URI passed from caller */ public Server getServerFromLoadBalancer(@Nullable URI original, @Nullable Object loadBalancerKey) throws ClientException { String host = null; int port = -1; if (original != null) { host = original.getHost(); } if (original != null) { Pair<String, Integer> schemeAndPort = deriveSchemeAndPortFromPartialUri(original); port = schemeAndPort.second(); } // Various Supported Cases // The loadbalancer to use and the instances it has is based on how it was registered // In each of these cases, the client might come in using Full Url or Partial URL ILoadBalancer lb = getLoadBalancer(); if (host == null) { // Partial URI or no URI Case // well we have to just get the right instances from lb - or we fall back if (lb != null){ Server svc = lb.chooseServer(loadBalancerKey); if (svc == null){ throw new ClientException(ClientException.ErrorType.GENERAL, "Load balancer does not have available server for client: " + clientName); } host = svc.getHost(); if (host == null){ throw new ClientException(ClientException.ErrorType.GENERAL, "Invalid Server for :" + svc); } logger.debug("{} using LB returned Server: {} for request {}", new Object[]{clientName, svc, original}); return svc; } else { // No Full URL - and we dont have a LoadBalancer registered to // obtain a server // if we have a vipAddress that came with the registration, we // can use that else we // bail out if (vipAddresses != null && vipAddresses.contains(",")) { throw new ClientException( ClientException.ErrorType.GENERAL, "Method is invoked for client " + clientName + " with partial URI of (" + original + ") with no load balancer configured." + " Also, there are multiple vipAddresses and hence no vip address can be chosen" + " to complete this partial uri"); } else if (vipAddresses != null) { try { Pair<String,Integer> hostAndPort = deriveHostAndPortFromVipAddress(vipAddresses); host = hostAndPort.first(); port = hostAndPort.second(); } catch (URISyntaxException e) { throw new ClientException( ClientException.ErrorType.GENERAL, "Method is invoked for client " + clientName + " with partial URI of (" + original + ") with no load balancer configured. " + " Also, the configured/registered vipAddress is unparseable (to determine host and port)"); } } else { throw new ClientException( ClientException.ErrorType.GENERAL, this.clientName + " has no LoadBalancer registered and passed in a partial URL request (with no host:port)." + " Also has no vipAddress registered"); } } } else { // Full URL Case // This could either be a vipAddress or a hostAndPort or a real DNS // if vipAddress or hostAndPort, we just have to consult the loadbalancer // but if it does not return a server, we should just proceed anyways // and assume its a DNS // For restClients registered using a vipAddress AND executing a request // by passing in the full URL (including host and port), we should only // consult lb IFF the URL passed is registered as vipAddress in Discovery boolean shouldInterpretAsVip = false; if (lb != null) { shouldInterpretAsVip = isVipRecognized(original.getAuthority()); } if (shouldInterpretAsVip) { Server svc = lb.chooseServer(loadBalancerKey); if (svc != null){ host = svc.getHost(); if (host == null){ throw new ClientException(ClientException.ErrorType.GENERAL, "Invalid Server for :" + svc); } logger.debug("using LB returned Server: {} for request: {}", svc, original); return svc; } else { // just fall back as real DNS logger.debug("{}:{} assumed to be a valid VIP address or exists in the DNS", host, port); } } else { // consult LB to obtain vipAddress backed instance given full URL //Full URL execute request - where url!=vipAddress logger.debug("Using full URL passed in by caller (not using load balancer): {}", original); } } // end of creating final URL if (host == null){ throw new ClientException(ClientException.ErrorType.GENERAL,"Request contains no HOST to talk to"); } // just verify that at this point we have a full URL return new Server(host, port); } public URI reconstructURIWithServer(Server server, URI original) { String host = server.getHost(); int port = server.getPort(); String scheme = server.getScheme(); if (host.equals(original.getHost()) && port == original.getPort() && scheme == original.getScheme()) { return original; } if (scheme == null) { scheme = original.getScheme(); } if (scheme == null) { scheme = deriveSchemeAndPortFromPartialUri(original).first(); } try { StringBuilder sb = new StringBuilder(); sb.append(scheme).append("://"); if (!Strings.isNullOrEmpty(original.getRawUserInfo())) { sb.append(original.getRawUserInfo()).append("@"); } sb.append(host); if (port >= 0) { sb.append(":").append(port); } sb.append(original.getRawPath()); if (!Strings.isNullOrEmpty(original.getRawQuery())) { sb.append("?").append(original.getRawQuery()); } if (!Strings.isNullOrEmpty(original.getRawFragment())) { sb.append("#").append(original.getRawFragment()); } URI newURI = new URI(sb.toString()); return newURI; } catch (URISyntaxException e) { throw new RuntimeException(e); } } protected int getRetriesNextServer(IClientConfig overriddenClientConfig) { int numRetries = maxAutoRetriesNextServer; if (overriddenClientConfig != null) { numRetries = overriddenClientConfig.get(CommonClientConfigKey.MaxAutoRetriesNextServer, maxAutoRetriesNextServer); } return numRetries; } public final ServerStats getServerStats(Server server) { ServerStats serverStats = null; ILoadBalancer lb = this.getLoadBalancer(); if (lb instanceof AbstractLoadBalancer){ LoadBalancerStats lbStats = ((AbstractLoadBalancer) lb).getLoadBalancerStats(); serverStats = lbStats.getSingleServerStat(server); } return serverStats; } protected int getNumberRetriesOnSameServer(IClientConfig overriddenClientConfig) { int numRetries = maxAutoRetries; if (overriddenClientConfig!=null){ try { numRetries = overriddenClientConfig.get(CommonClientConfigKey.MaxAutoRetries, maxAutoRetries); } catch (Exception e) { logger.warn("Invalid maxRetries requested for RestClient:" + this.clientName); } } return numRetries; } public boolean handleSameServerRetry(Server server, int currentRetryCount, int maxRetries, Throwable e) { if (currentRetryCount > maxRetries) { return false; } logger.debug("Exception while executing request which is deemed retry-able, retrying ..., SAME Server Retry Attempt#: {}", currentRetryCount, server); return true; } public final RetryHandler getRetryHandler() { return defaultRetryHandler; } public final void setRetryHandler(RetryHandler retryHandler) { this.defaultRetryHandler = retryHandler; } public final boolean isOkToRetryOnAllOperations() { return okToRetryOnAllOperations; } public final void setOkToRetryOnAllOperations(boolean okToRetryOnAllOperations) { this.okToRetryOnAllOperations = okToRetryOnAllOperations; } }
7,053
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/IRule.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.loadbalancer; /** * Interface that defines a "Rule" for a LoadBalancer. A Rule can be thought of * as a Strategy for loadbalacing. Well known loadbalancing strategies include * Round Robin, Response Time based etc. * * @author stonse * */ public interface IRule{ /* * choose one alive server from lb.allServers or * lb.upServers according to key * * @return choosen Server object. NULL is returned if none * server is available */ public Server choose(Object key); public void setLoadBalancer(ILoadBalancer lb); public ILoadBalancer getLoadBalancer(); }
7,054
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/ZoneAvoidancePredicate.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.loadbalancer; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import com.netflix.client.config.Property; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.util.Map; import java.util.Set; /** * A server predicate that filters out all servers in a worst zone if the aggregated metric for that zone reaches a threshold. * The logic to determine the worst zone is described in class {@link ZoneAwareLoadBalancer}. * * @author awang * */ public class ZoneAvoidancePredicate extends AbstractServerPredicate { private static final Logger logger = LoggerFactory.getLogger(ZoneAvoidancePredicate.class); private static final IClientConfigKey<Double> TRIGGERING_LOAD_PER_SERVER_THRESHOLD = new CommonClientConfigKey<Double>( "ZoneAwareNIWSDiscoveryLoadBalancer.%s.triggeringLoadPerServerThreshold", 0.2d) {}; private static final IClientConfigKey<Double> AVOID_ZONE_WITH_BLACKOUT_PERCENTAGE = new CommonClientConfigKey<Double>( "ZoneAwareNIWSDiscoveryLoadBalancer.%s.avoidZoneWithBlackoutPercetage", 0.99999d) {}; private static final IClientConfigKey<Boolean> ENABLED = new CommonClientConfigKey<Boolean>( "niws.loadbalancer.zoneAvoidanceRule.enabled", true) {}; private Property<Double> triggeringLoad = Property.of(TRIGGERING_LOAD_PER_SERVER_THRESHOLD.defaultValue()); private Property<Double> triggeringBlackoutPercentage = Property.of(AVOID_ZONE_WITH_BLACKOUT_PERCENTAGE.defaultValue()); private Property<Boolean> enabled = Property.of(ENABLED.defaultValue()); public ZoneAvoidancePredicate(IRule rule, IClientConfig clientConfig) { super(rule); initDynamicProperties(clientConfig); } public ZoneAvoidancePredicate(LoadBalancerStats lbStats, IClientConfig clientConfig) { super(lbStats); initDynamicProperties(clientConfig); } ZoneAvoidancePredicate(IRule rule) { super(rule); } private void initDynamicProperties(IClientConfig clientConfig) { if (clientConfig != null) { enabled = clientConfig.getGlobalProperty(ENABLED); triggeringLoad = clientConfig.getGlobalProperty(TRIGGERING_LOAD_PER_SERVER_THRESHOLD.format(clientConfig.getClientName())); triggeringBlackoutPercentage = clientConfig.getGlobalProperty(AVOID_ZONE_WITH_BLACKOUT_PERCENTAGE.format(clientConfig.getClientName())); } } @Override public boolean apply(@Nullable PredicateKey input) { if (!enabled.getOrDefault()) { return true; } String serverZone = input.getServer().getZone(); if (serverZone == null) { // there is no zone information from the server, we do not want to filter // out this server return true; } LoadBalancerStats lbStats = getLBStats(); if (lbStats == null) { // no stats available, do not filter return true; } if (lbStats.getAvailableZones().size() <= 1) { // only one zone is available, do not filter return true; } Map<String, ZoneSnapshot> zoneSnapshot = ZoneAvoidanceRule.createSnapshot(lbStats); if (!zoneSnapshot.keySet().contains(serverZone)) { // The server zone is unknown to the load balancer, do not filter it out return true; } logger.debug("Zone snapshots: {}", zoneSnapshot); Set<String> availableZones = ZoneAvoidanceRule.getAvailableZones(zoneSnapshot, triggeringLoad.getOrDefault(), triggeringBlackoutPercentage.getOrDefault()); logger.debug("Available zones: {}", availableZones); if (availableZones != null) { return availableZones.contains(input.getServer().getZone()); } else { return false; } } }
7,055
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/NoOpPing.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.loadbalancer; /** * No Op Ping * @author stonse * */ public class NoOpPing implements IPing { @Override public boolean isAlive(Server server) { return true; } }
7,056
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/reactive/ExecutionContextListenerInvoker.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.loadbalancer.reactive; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import com.netflix.loadbalancer.reactive.ExecutionListener.AbortExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentHashMap; /** * Utility class to invoke the list of {@link ExecutionListener} with {@link ExecutionContext} * * @author Allen Wang */ public class ExecutionContextListenerInvoker<I, O> { private final static Logger logger = LoggerFactory.getLogger(ExecutionContextListenerInvoker.class); private final ExecutionContext<I> context; private final List<ExecutionListener<I, O>> listeners; private final IClientConfig clientConfig; private final ConcurrentHashMap<String, IClientConfigKey> classConfigKeyMap; public ExecutionContextListenerInvoker(ExecutionContext<I> context, List<ExecutionListener<I, O>> listeners) { this(context, listeners, null); } public ExecutionContextListenerInvoker(List<ExecutionListener<I, O>> listeners, IClientConfig config) { this(null, listeners, config); } public ExecutionContextListenerInvoker(ExecutionContext<I> context, List<ExecutionListener<I, O>> listeners, IClientConfig config) { this.listeners = Collections.unmodifiableList(listeners); this.context = context; this.clientConfig = config; if (clientConfig != null) { classConfigKeyMap = new ConcurrentHashMap<String, IClientConfigKey>(); } else { classConfigKeyMap = null; } } public ExecutionContextListenerInvoker(List<ExecutionListener<I, O>> listeners) { this(null, listeners); } public void onExecutionStart() { onExecutionStart(this.context); } public void onExecutionStart(ExecutionContext<I> context) { for (ExecutionListener<I, O> listener : listeners) { try { if (!isListenerDisabled(listener)) { listener.onExecutionStart(context.getChildContext(listener)); } } catch (Throwable e) { if (e instanceof AbortExecutionException) { throw (AbortExecutionException) e; } logger.error("Error invoking listener " + listener, e); } } } public void onStartWithServer(ExecutionInfo info) { onStartWithServer(this.context, info); } /** * Called when a server is chosen and the request is going to be executed on the server. * */ public void onStartWithServer(ExecutionContext<I> context, ExecutionInfo info) { for (ExecutionListener<I, O> listener: listeners) { try { if (!isListenerDisabled(listener)) { listener.onStartWithServer(context.getChildContext(listener), info); } } catch (Throwable e) { if (e instanceof AbortExecutionException) { throw (AbortExecutionException) e; } logger.error("Error invoking listener " + listener, e); } } } public void onExceptionWithServer(Throwable exception, ExecutionInfo info) { onExceptionWithServer(this.context, exception, info); } /** * Called when an exception is received from executing the request on a server. * * @param exception Exception received */ public void onExceptionWithServer(ExecutionContext<I> context, Throwable exception, ExecutionInfo info) { for (ExecutionListener<I, O> listener: listeners) { try { if (!isListenerDisabled(listener)) { listener.onExceptionWithServer(context.getChildContext(listener), exception, info); } } catch (Throwable e) { logger.error("Error invoking listener " + listener, e); } } } public void onExecutionSuccess(O response, ExecutionInfo info) { onExecutionSuccess(this.context, response, info); } /** * Called when the request is executed successfully on the server * * @param response Object received from the execution */ public void onExecutionSuccess(ExecutionContext<I> context, O response, ExecutionInfo info) { for (ExecutionListener<I, O> listener: listeners) { try { if (!isListenerDisabled(listener)) { listener.onExecutionSuccess(context.getChildContext(listener), response, info); } } catch (Throwable e) { logger.error("Error invoking listener " + listener, e); } } } public void onExecutionFailed(Throwable finalException, ExecutionInfo info) { onExecutionFailed(this.context, finalException, info); } /** * Called when the request is considered failed after all retries. * * @param finalException Final exception received. */ public void onExecutionFailed(ExecutionContext<I> context, Throwable finalException, ExecutionInfo info) { for (ExecutionListener<I, O> listener: listeners) { try { if (!isListenerDisabled(listener)) { listener.onExecutionFailed(context.getChildContext(listener), finalException, info); } } catch (Throwable e) { logger.error("Error invoking listener " + listener, e); } } } private boolean isListenerDisabled(ExecutionListener<?, ?> listener) { if (clientConfig == null) { return false; } else { String className = listener.getClass().getName(); IClientConfigKey key = classConfigKeyMap.get(className); if (key == null) { key = CommonClientConfigKey.valueOf("listener." + className + ".disabled"); IClientConfigKey old = classConfigKeyMap.putIfAbsent(className, key); if (old != null) { key = old; } } return clientConfig.get(key, false); } } }
7,057
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/reactive/ExecutionInfo.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.loadbalancer.reactive; import com.netflix.loadbalancer.Server; /** * Represents the state of execution for an instance of {@link com.netflix.loadbalancer.reactive.LoadBalancerCommand} * and is passed to {@link ExecutionListener} * * @author Allen Wang */ public class ExecutionInfo { private final Server server; private final int numberOfPastAttemptsOnServer; private final int numberOfPastServersAttempted; private ExecutionInfo(Server server, int numberOfPastAttemptsOnServer, int numberOfPastServersAttempted) { this.server = server; this.numberOfPastAttemptsOnServer = numberOfPastAttemptsOnServer; this.numberOfPastServersAttempted = numberOfPastServersAttempted; } public static ExecutionInfo create(Server server, int numberOfPastAttemptsOnServer, int numberOfPastServersAttempted) { return new ExecutionInfo(server, numberOfPastAttemptsOnServer, numberOfPastServersAttempted); } public Server getServer() { return server; } public int getNumberOfPastAttemptsOnServer() { return numberOfPastAttemptsOnServer; } public int getNumberOfPastServersAttempted() { return numberOfPastServersAttempted; } @Override public String toString() { return "ExecutionInfo{" + "server=" + server + ", numberOfPastAttemptsOnServer=" + numberOfPastAttemptsOnServer + ", numberOfPastServersAttempted=" + numberOfPastServersAttempted + '}'; } }
7,058
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/reactive/ExecutionContext.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.loadbalancer.reactive; import com.netflix.client.RetryHandler; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * A context object that is created at start of each load balancer execution * and contains certain meta data of the load balancer and mutable state data of * execution per listener per request. Each listener will get its own context * to work with. But it can also call {@link ExecutionContext#getGlobalContext()} to * get the shared context between all listeners. * * @author Allen Wang * */ public class ExecutionContext<T> { private final Map<String, Object> context; private final ConcurrentHashMap<Object, ChildContext<T>> subContexts; private final T request; private final IClientConfig requestConfig; private final RetryHandler retryHandler; private final IClientConfig clientConfig; private static class ChildContext<T> extends ExecutionContext<T> { private final ExecutionContext<T> parent; ChildContext(ExecutionContext<T> parent) { super(parent.request, parent.requestConfig, parent.clientConfig, parent.retryHandler, null); this.parent = parent; } @Override public ExecutionContext<T> getGlobalContext() { return parent; } } public ExecutionContext(T request, IClientConfig requestConfig, IClientConfig clientConfig, RetryHandler retryHandler) { this.request = request; this.requestConfig = requestConfig; this.clientConfig = clientConfig; this.context = new ConcurrentHashMap<>(); this.subContexts = new ConcurrentHashMap<>(); this.retryHandler = retryHandler; } ExecutionContext(T request, IClientConfig requestConfig, IClientConfig clientConfig, RetryHandler retryHandler, ConcurrentHashMap<Object, ChildContext<T>> subContexts) { this.request = request; this.requestConfig = requestConfig; this.clientConfig = clientConfig; this.context = new ConcurrentHashMap<>(); this.subContexts = subContexts; this.retryHandler = retryHandler; } ExecutionContext<T> getChildContext(Object obj) { if (subContexts == null) { return null; } ChildContext<T> subContext = subContexts.get(obj); if (subContext == null) { subContext = new ChildContext<T>(this); ChildContext<T> old = subContexts.putIfAbsent(obj, subContext); if (old != null) { subContext = old; } } return subContext; } public T getRequest() { return request; } public Object get(String name) { return context.get(name); } public <S> S getClientProperty(IClientConfigKey<S> key) { S value; if (requestConfig != null) { value = requestConfig.get(key); if (value != null) { return value; } } value = clientConfig.get(key); return value; } public void put(String name, Object value) { context.put(name, value); } /** * @return The IClientConfig object used to override the client's default configuration * for this specific execution. */ public IClientConfig getRequestConfig() { return requestConfig; } /** * * @return The shared context for all listeners. */ public ExecutionContext<T> getGlobalContext() { return this; } public RetryHandler getRetryHandler() { return retryHandler; } }
7,059
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/reactive/ServerOperation.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.loadbalancer.reactive; import rx.Observable; import rx.functions.Func1; import com.netflix.loadbalancer.Server; /** * Provide the {@link rx.Observable} for a specified server. Used by {@link com.netflix.loadbalancer.reactive.LoadBalancerCommand} * * @param <T> Output type */ public interface ServerOperation<T> extends Func1<Server, Observable<T>> { /** * @return A lazy {@link Observable} for the server supplied. It is expected * that the actual execution is not started until the returned {@link Observable} is subscribed to. */ @Override public Observable<T> call(Server server); }
7,060
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/reactive/ExecutionListener.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.loadbalancer.reactive; /** * A listener to be invoked by load balancer at different stage of execution. * * @param <I> Input type used by {@link ExecutionContext} passed to * listener where it can call {@link ExecutionContext#getRequest()} to examine the * request object of the execution * @param <O> Output type from the load balancer execution, used by {@link #onExecutionSuccess(ExecutionContext, Object, com.netflix.loadbalancer.reactive.ExecutionInfo)} * API */ public interface ExecutionListener<I, O> { /** * An exception to indicate that the listener wants to abort execution */ class AbortExecutionException extends RuntimeException { public AbortExecutionException(String message) { super(message); } public AbortExecutionException(String message, Throwable cause) { super(message, cause); } } /** * Called when execution is about to start. * * @throws ExecutionListener.AbortExecutionException if the listener would * like to abort the execution */ public void onExecutionStart(ExecutionContext<I> context) throws AbortExecutionException; /** * Called when a server is chosen and the request is going to be executed on the server. * * @throws ExecutionListener.AbortExecutionException if the listener would * like to abort the execution */ public void onStartWithServer(ExecutionContext<I> context, ExecutionInfo info) throws AbortExecutionException; /** * Called when an exception is received from executing the request on a server. * * @param exception Exception received */ public void onExceptionWithServer(ExecutionContext<I> context, Throwable exception, ExecutionInfo info); /** * Called when the request is executed successfully on the server * * @param response Object received from the execution */ public void onExecutionSuccess(ExecutionContext<I> context, O response, ExecutionInfo info); /** * Called when the request is considered failed after all retries. * * @param finalException Final exception received. This may be a wrapped exception indicating that all * retries have been exhausted. */ public void onExecutionFailed(ExecutionContext<I> context, Throwable finalException, ExecutionInfo info); }
7,061
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/loadbalancer/reactive/LoadBalancerCommand.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.loadbalancer.reactive; import java.net.URI; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Observer; import rx.Subscriber; import rx.functions.Func1; import rx.functions.Func2; import com.netflix.client.ClientException; import com.netflix.client.RetryHandler; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.LoadBalancerContext; import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.ServerStats; import com.netflix.loadbalancer.reactive.ExecutionListener.AbortExecutionException; import com.netflix.servo.monitor.Stopwatch; /** * A command that is used to produce the Observable from the load balancer execution. The load balancer is responsible for * the following: * * <ul> * <li>Choose a server</li> * <li>Invoke the {@link com.netflix.loadbalancer.Server} onSubscribe call method</li> * <li>Invoke the {@link ExecutionListener} if any</li> * <li>Retry on exception, controlled by {@link com.netflix.client.RetryHandler}</li> * <li>Provide feedback to the {@link com.netflix.loadbalancer.LoadBalancerStats}</li> * </ul> * * @author Allen Wang */ public class LoadBalancerCommand<T> { private static final Logger logger = LoggerFactory.getLogger(LoadBalancerCommand.class); public static class Builder<T> { private RetryHandler retryHandler; private ILoadBalancer loadBalancer; private IClientConfig config; private LoadBalancerContext loadBalancerContext; private List<? extends ExecutionListener<?, T>> listeners; private Object loadBalancerKey; private ExecutionContext<?> executionContext; private ExecutionContextListenerInvoker invoker; private URI loadBalancerURI; private Server server; private Builder() {} public Builder<T> withLoadBalancer(ILoadBalancer loadBalancer) { this.loadBalancer = loadBalancer; return this; } public Builder<T> withLoadBalancerURI(URI loadBalancerURI) { this.loadBalancerURI = loadBalancerURI; return this; } public Builder<T> withListeners(List<? extends ExecutionListener<?, T>> listeners) { if (this.listeners == null) { this.listeners = new LinkedList<ExecutionListener<?, T>>(listeners); } else { this.listeners.addAll((Collection) listeners); } return this; } public Builder<T> withRetryHandler(RetryHandler retryHandler) { this.retryHandler = retryHandler; return this; } public Builder<T> withClientConfig(IClientConfig config) { this.config = config; return this; } /** * Pass in an optional key object to help the load balancer to choose a specific server among its * server list, depending on the load balancer implementation. */ public Builder<T> withServerLocator(Object key) { this.loadBalancerKey = key; return this; } public Builder<T> withLoadBalancerContext(LoadBalancerContext loadBalancerContext) { this.loadBalancerContext = loadBalancerContext; return this; } public Builder<T> withExecutionContext(ExecutionContext<?> executionContext) { this.executionContext = executionContext; return this; } /** * Pin the operation to a specific server. Otherwise run on any server returned by the load balancer * * @param server */ public Builder<T> withServer(Server server) { this.server = server; return this; } public LoadBalancerCommand<T> build() { if (loadBalancerContext == null && loadBalancer == null) { throw new IllegalArgumentException("Either LoadBalancer or LoadBalancerContext needs to be set"); } if (listeners != null && listeners.size() > 0) { this.invoker = new ExecutionContextListenerInvoker(executionContext, listeners, config); } if (loadBalancerContext == null) { loadBalancerContext = new LoadBalancerContext(loadBalancer, config); } return new LoadBalancerCommand<T>(this); } } public static <T> Builder<T> builder() { return new Builder<T>(); } private final URI loadBalancerURI; private final Object loadBalancerKey; private final LoadBalancerContext loadBalancerContext; private final RetryHandler retryHandler; private volatile ExecutionInfo executionInfo; private final Server server; private final ExecutionContextListenerInvoker<?, T> listenerInvoker; private LoadBalancerCommand(Builder<T> builder) { this.loadBalancerURI = builder.loadBalancerURI; this.loadBalancerKey = builder.loadBalancerKey; this.loadBalancerContext = builder.loadBalancerContext; this.retryHandler = builder.retryHandler != null ? builder.retryHandler : loadBalancerContext.getRetryHandler(); this.listenerInvoker = builder.invoker; this.server = builder.server; } /** * Return an Observable that either emits only the single requested server * or queries the load balancer for the next server on each subscription */ private Observable<Server> selectServer() { return Observable.create(new OnSubscribe<Server>() { @Override public void call(Subscriber<? super Server> next) { try { Server server = loadBalancerContext.getServerFromLoadBalancer(loadBalancerURI, loadBalancerKey); next.onNext(server); next.onCompleted(); } catch (Exception e) { next.onError(e); } } }); } class ExecutionInfoContext { Server server; int serverAttemptCount = 0; int attemptCount = 0; public void setServer(Server server) { this.server = server; this.serverAttemptCount++; this.attemptCount = 0; } public void incAttemptCount() { this.attemptCount++; } public int getAttemptCount() { return attemptCount; } public Server getServer() { return server; } public int getServerAttemptCount() { return this.serverAttemptCount; } public ExecutionInfo toExecutionInfo() { return ExecutionInfo.create(server, attemptCount-1, serverAttemptCount-1); } public ExecutionInfo toFinalExecutionInfo() { return ExecutionInfo.create(server, attemptCount, serverAttemptCount-1); } } private Func2<Integer, Throwable, Boolean> retryPolicy(final int maxRetrys, final boolean same) { return new Func2<Integer, Throwable, Boolean>() { @Override public Boolean call(Integer tryCount, Throwable e) { if (e instanceof AbortExecutionException) { return false; } if (tryCount > maxRetrys) { return false; } if (e.getCause() != null && e instanceof RuntimeException) { e = e.getCause(); } return retryHandler.isRetriableException(e, same); } }; } /** * Create an {@link Observable} that once subscribed execute network call asynchronously with a server chosen by load balancer. * If there are any errors that are indicated as retriable by the {@link RetryHandler}, they will be consumed internally by the * function and will not be observed by the {@link Observer} subscribed to the returned {@link Observable}. If number of retries has * exceeds the maximal allowed, a final error will be emitted by the returned {@link Observable}. Otherwise, the first successful * result during execution and retries will be emitted. */ public Observable<T> submit(final ServerOperation<T> operation) { final ExecutionInfoContext context = new ExecutionInfoContext(); if (listenerInvoker != null) { try { listenerInvoker.onExecutionStart(); } catch (AbortExecutionException e) { return Observable.error(e); } } final int maxRetrysSame = retryHandler.getMaxRetriesOnSameServer(); final int maxRetrysNext = retryHandler.getMaxRetriesOnNextServer(); // Use the load balancer Observable<T> o = (server == null ? selectServer() : Observable.just(server)) .concatMap(new Func1<Server, Observable<T>>() { @Override // Called for each server being selected public Observable<T> call(Server server) { context.setServer(server); final ServerStats stats = loadBalancerContext.getServerStats(server); // Called for each attempt and retry Observable<T> o = Observable .just(server) .concatMap(new Func1<Server, Observable<T>>() { @Override public Observable<T> call(final Server server) { context.incAttemptCount(); loadBalancerContext.noteOpenConnection(stats); if (listenerInvoker != null) { try { listenerInvoker.onStartWithServer(context.toExecutionInfo()); } catch (AbortExecutionException e) { return Observable.error(e); } } final Stopwatch tracer = loadBalancerContext.getExecuteTracer().start(); return operation.call(server).doOnEach(new Observer<T>() { private T entity; @Override public void onCompleted() { recordStats(tracer, stats, entity, null); // TODO: What to do if onNext or onError are never called? } @Override public void onError(Throwable e) { recordStats(tracer, stats, null, e); logger.debug("Got error {} when executed on server {}", e, server); if (listenerInvoker != null) { listenerInvoker.onExceptionWithServer(e, context.toExecutionInfo()); } } @Override public void onNext(T entity) { this.entity = entity; if (listenerInvoker != null) { listenerInvoker.onExecutionSuccess(entity, context.toExecutionInfo()); } } private void recordStats(Stopwatch tracer, ServerStats stats, Object entity, Throwable exception) { tracer.stop(); loadBalancerContext.noteRequestCompletion(stats, entity, exception, tracer.getDuration(TimeUnit.MILLISECONDS), retryHandler); } }); } }); if (maxRetrysSame > 0) o = o.retry(retryPolicy(maxRetrysSame, true)); return o; } }); if (maxRetrysNext > 0 && server == null) o = o.retry(retryPolicy(maxRetrysNext, false)); return o.onErrorResumeNext(new Func1<Throwable, Observable<T>>() { @Override public Observable<T> call(Throwable e) { if (context.getAttemptCount() > 0) { if (maxRetrysNext > 0 && context.getServerAttemptCount() == (maxRetrysNext + 1)) { e = new ClientException(ClientException.ErrorType.NUMBEROF_RETRIES_NEXTSERVER_EXCEEDED, "Number of retries on next server exceeded max " + maxRetrysNext + " retries, while making a call for: " + context.getServer(), e); } else if (maxRetrysSame > 0 && context.getAttemptCount() == (maxRetrysSame + 1)) { e = new ClientException(ClientException.ErrorType.NUMBEROF_RETRIES_EXEEDED, "Number of retries exceeded max " + maxRetrysSame + " retries, while making a call for: " + context.getServer(), e); } } if (listenerInvoker != null) { listenerInvoker.onExecutionFailed(e, context.toFinalExecutionInfo()); } return Observable.error(e); } }); } }
7,062
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/client/PrimeConnections.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.client; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.Server; import com.netflix.servo.monitor.Counter; import com.netflix.servo.monitor.Monitors; import com.netflix.servo.monitor.Stopwatch; import com.netflix.servo.monitor.Timer; /** * Prime the connections for a given Client (For those Client that * have a LoadBalancer that knows the set of Servers it will connect to) This is * mainly done to address those deployment environments (Read EC2) which benefit * from a firewall connection/path warmup prior to actual use for live requests. * <p> * This class is not protocol specific. Actual priming operation is delegated to * instance of {@link IPrimeConnection}, which is instantiated using reflection * according to property {@link CommonClientConfigKey#PrimeConnectionsClassName}. * * @author stonse * @author awang * @author aspyker * */ public class PrimeConnections { public static interface PrimeConnectionListener { public void primeCompleted(Server s, Throwable lastException); } public static class PrimeConnectionEndStats { public final int total; public final int success; public final int failure; public final long totalTime; public PrimeConnectionEndStats(int total, int success, int failure, long totalTime) { this.total = total; this.success = success; this.failure = failure; this.totalTime = totalTime; } @Override public String toString() { return "PrimeConnectionEndStats [total=" + total + ", success=" + success + ", failure=" + failure + ", totalTime=" + totalTime + "]"; } } private static final Logger logger = LoggerFactory.getLogger(PrimeConnections.class); // affordance to change the URI we connect to while "priming" // default of "/" is good for most - but if its heavy operation on // the server side, then a more lightweight URI can be chosen String primeConnectionsURIPath = "/"; /** * Executor service for executing asynchronous requests. */ private ExecutorService executorService; private int maxExecutorThreads = 5; private long executorThreadTimeout = 30000; private String name = "default"; private float primeRatio = 1.0f; int maxRetries = 9; long maxTotalTimeToPrimeConnections = 30 * 1000; // default time long totalTimeTaken = 0; // Total time taken private boolean aSync = true; Counter totalCounter; Counter successCounter; Timer initialPrimeTimer; private IPrimeConnection connector; private PrimeConnectionEndStats stats; private PrimeConnections() { } public PrimeConnections(String name, IClientConfig niwsClientConfig) { int maxRetriesPerServerPrimeConnection = CommonClientConfigKey.MaxRetriesPerServerPrimeConnection.defaultValue(); int maxTotalTimeToPrimeConnections = CommonClientConfigKey.MaxTotalTimeToPrimeConnections.defaultValue(); try { maxRetriesPerServerPrimeConnection = niwsClientConfig.getOrDefault(CommonClientConfigKey.MaxRetriesPerServerPrimeConnection); } catch (Exception e) { logger.warn("Invalid maxRetriesPerServerPrimeConnection"); } try { maxTotalTimeToPrimeConnections = niwsClientConfig.getOrDefault(CommonClientConfigKey.MaxTotalTimeToPrimeConnections); } catch (Exception e) { logger.warn("Invalid maxTotalTimeToPrimeConnections"); } final String primeConnectionsURI = niwsClientConfig.getOrDefault(CommonClientConfigKey.PrimeConnectionsURI); float primeRatio = niwsClientConfig.getOrDefault(CommonClientConfigKey.MinPrimeConnectionsRatio); final String className = niwsClientConfig.getOrDefault(CommonClientConfigKey.PrimeConnectionsClassName); try { connector = (IPrimeConnection) Class.forName(className).newInstance(); connector.initWithNiwsConfig(niwsClientConfig); } catch (Exception e) { throw new RuntimeException("Unable to initialize prime connections", e); } setUp(name, maxRetriesPerServerPrimeConnection, maxTotalTimeToPrimeConnections, primeConnectionsURI, primeRatio); } public PrimeConnections(String name, int maxRetries, long maxTotalTimeToPrimeConnections, String primeConnectionsURI) { setUp(name, maxRetries, maxTotalTimeToPrimeConnections, primeConnectionsURI, CommonClientConfigKey.MinPrimeConnectionsRatio.defaultValue()); } public PrimeConnections(String name, int maxRetries, long maxTotalTimeToPrimeConnections, String primeConnectionsURI, float primeRatio) { setUp(name, maxRetries, maxTotalTimeToPrimeConnections, primeConnectionsURI, primeRatio); } private void setUp(String name, int maxRetries, long maxTotalTimeToPrimeConnections, String primeConnectionsURI, float primeRatio) { this.name = name; this.maxRetries = maxRetries; this.maxTotalTimeToPrimeConnections = maxTotalTimeToPrimeConnections; this.primeConnectionsURIPath = primeConnectionsURI; this.primeRatio = primeRatio; executorService = new ThreadPoolExecutor(1 /* minimum */, maxExecutorThreads /* max threads */, executorThreadTimeout /* * timeout - same property as create * timeout */, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>() /* Bounded queue with FIFO- bounded to max tasks */, new ASyncPrimeConnectionsThreadFactory(name) /* * So we can give * our Thread a * name */ ); totalCounter = Monitors.newCounter(name + "_PrimeConnection_TotalCounter"); successCounter = Monitors.newCounter(name + "_PrimeConnection_SuccessCounter"); initialPrimeTimer = Monitors.newTimer(name + "_initialPrimeConnectionsTimer", TimeUnit.MILLISECONDS); Monitors.registerObject(name + "_PrimeConnection", this); } /** * Prime connections, blocking until configured percentage (default is 100%) of target servers are primed * or max time is reached. * * @see CommonClientConfigKey#MinPrimeConnectionsRatio * @see CommonClientConfigKey#MaxTotalTimeToPrimeConnections * */ public void primeConnections(List<Server> servers) { if (servers == null || servers.size() == 0) { logger.debug("No server to prime"); return; } for (Server server: servers) { server.setReadyToServe(false); } int totalCount = (int) (servers.size() * primeRatio); final CountDownLatch latch = new CountDownLatch(totalCount); final AtomicInteger successCount = new AtomicInteger(0); final AtomicInteger failureCount= new AtomicInteger(0); primeConnectionsAsync(servers, new PrimeConnectionListener() { @Override public void primeCompleted(Server s, Throwable lastException) { if (lastException == null) { successCount.incrementAndGet(); s.setReadyToServe(true); } else { failureCount.incrementAndGet(); } latch.countDown(); } }); Stopwatch stopWatch = initialPrimeTimer.start(); try { latch.await(maxTotalTimeToPrimeConnections, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { logger.error("Priming connection interrupted", e); } finally { stopWatch.stop(); } stats = new PrimeConnectionEndStats(totalCount, successCount.get(), failureCount.get(), stopWatch.getDuration(TimeUnit.MILLISECONDS)); printStats(stats); } public PrimeConnectionEndStats getEndStats() { return stats; } private void printStats(PrimeConnectionEndStats stats) { if (stats.total != stats.success) { logger.info("Priming Connections not fully successful"); } else { logger.info("Priming connections fully successful"); } logger.debug("numServers left to be 'primed'=" + (stats.total - stats.success)); logger.debug("numServers successfully 'primed'=" + stats.success); logger .debug("numServers whose attempts not complete exclusively due to max time allocated=" + (stats.total - (stats.success + stats.failure))); logger.debug("Total Time Taken=" + stats.totalTime + " msecs, out of an allocated max of (msecs)=" + maxTotalTimeToPrimeConnections); logger.debug("stats = " + stats); } /* private void makeConnectionsASync() { Callable<Void> ft = new Callable<Void>() { public Void call() throws Exception { logger.info("primeConnections ..."); makeConnections(); return null; } }; outerExecutorService.submit(ft); } */ /** * Prime servers asynchronously. * * @param servers * @param listener */ public List<Future<Boolean>> primeConnectionsAsync(final List<Server> servers, final PrimeConnectionListener listener) { if (servers == null) { return Collections.emptyList(); } List<Server> allServers = new ArrayList<Server>(); allServers.addAll(servers); if (allServers.size() == 0){ logger.debug("RestClient:" + name + ". No nodes/servers to prime connections"); return Collections.emptyList(); } logger.info("Priming Connections for RestClient:" + name + ", numServers:" + allServers.size()); List<Future<Boolean>> ftList = new ArrayList<Future<Boolean>>(); for (Server s : allServers) { // prevent the server to be used by load balancer // will be set to true when priming is done s.setReadyToServe(false); if (aSync) { Future<Boolean> ftC = null; try { ftC = makeConnectionASync(s, listener); ftList.add(ftC); } catch (RejectedExecutionException ree) { logger.error("executor submit failed", ree); } catch (Exception e) { logger.error("general error", e); // It does not really matter if there was an exception, // the goal here is to attempt "priming/opening" the route // in ec2 .. actual http results do not matter } } else { connectToServer(s, listener); } } return ftList; } private Future<Boolean> makeConnectionASync(final Server s, final PrimeConnectionListener listener) throws InterruptedException, RejectedExecutionException { Callable<Boolean> ftConn = new Callable<Boolean>() { public Boolean call() throws Exception { logger.debug("calling primeconnections ..."); return connectToServer(s, listener); } }; return executorService.submit(ftConn); } public void shutdown() { executorService.shutdown(); Monitors.unregisterObject(name + "_PrimeConnection", this); } private Boolean connectToServer(final Server s, final PrimeConnectionListener listener) { int tryNum = 0; Exception lastException = null; totalCounter.increment(); boolean success = false; do { try { logger.debug("Executing PrimeConnections request to server {} with path {}, tryNum={}", s, primeConnectionsURIPath, tryNum); success = connector.connect(s, primeConnectionsURIPath); successCounter.increment(); lastException = null; break; } catch (Exception e) { // It does not really matter if there was an exception, // the goal here is to attempt "priming/opening" the route // in ec2 .. actual http results do not matter logger.debug("Error connecting to server: {}", e.getMessage()); lastException = e; sleepBeforeRetry(tryNum); } logger.debug("server:{}, result={}, tryNum={}, maxRetries={}", s, success, tryNum, maxRetries); tryNum++; } while (!success && (tryNum <= maxRetries)); // set the alive flag so that it can be used by load balancers if (listener != null) { try { listener.primeCompleted(s, lastException); } catch (Exception e) { logger.error("Error calling PrimeComplete listener for server '{}'", s, e); } } logger.debug("Either done, or quitting server:{}, result={}, tryNum={}, maxRetries={}", s, success, tryNum, maxRetries); return success; } private void sleepBeforeRetry(int tryNum) { try { int sleep = (tryNum + 1) * 100; logger.debug("Sleeping for " + sleep + "ms ..."); Thread.sleep(sleep); // making this seconds based is too slow // i.e. 200ms, 400 ms, 800ms, 1600ms etc. } catch (InterruptedException ex) { } } static class ASyncPrimeConnectionsThreadFactory implements ThreadFactory { private static final AtomicInteger groupNumber = new AtomicInteger(1); private final ThreadGroup group; private final AtomicInteger threadNumber = new AtomicInteger(1); private final String namePrefix; ASyncPrimeConnectionsThreadFactory(String name) { SecurityManager s = System.getSecurityManager(); group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); // NOPMD namePrefix = "ASyncPrimeConnectionsThreadFactory-" + name + "-" + groupNumber.getAndIncrement() + "-thread-"; } public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); if (!t.isDaemon()) t.setDaemon(true); if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); return t; } } }
7,063
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/client/AbstractLoadBalancerAwareClient.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.client; import java.net.URI; import rx.Observable; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.AvailabilityFilteringRule; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.LoadBalancerContext; import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.reactive.LoadBalancerCommand; import com.netflix.loadbalancer.reactive.ServerOperation; /** * Abstract class that provides the integration of client with load balancers. * * @author awang * */ public abstract class AbstractLoadBalancerAwareClient<S extends ClientRequest, T extends IResponse> extends LoadBalancerContext implements IClient<S, T>, IClientConfigAware { public AbstractLoadBalancerAwareClient(ILoadBalancer lb) { super(lb); } /** * Delegate to {@link #initWithNiwsConfig(IClientConfig)} * @param clientConfig */ public AbstractLoadBalancerAwareClient(ILoadBalancer lb, IClientConfig clientConfig) { super(lb, clientConfig); } /** * Determine if an exception should contribute to circuit breaker trip. If such exceptions happen consecutively * on a server, it will be deemed as circuit breaker tripped and enter into a time out when it will be * skipped by the {@link AvailabilityFilteringRule}, which is the default rule for load balancers. */ @Deprecated protected boolean isCircuitBreakerException(Throwable e) { if (getRetryHandler() != null) { return getRetryHandler().isCircuitTrippingException(e); } return false; } /** * Determine if operation can be retried if an exception is thrown. For example, connect * timeout related exceptions * are typically retriable. * */ @Deprecated protected boolean isRetriableException(Throwable e) { if (getRetryHandler() != null) { return getRetryHandler().isRetriableException(e, true); } return false; } public T executeWithLoadBalancer(S request) throws ClientException { return executeWithLoadBalancer(request, null); } /** * This method should be used when the caller wants to dispatch the request to a server chosen by * the load balancer, instead of specifying the server in the request's URI. * It calculates the final URI by calling {@link #reconstructURIWithServer(com.netflix.loadbalancer.Server, java.net.URI)} * and then calls {@link #executeWithLoadBalancer(ClientRequest, com.netflix.client.config.IClientConfig)}. * * @param request request to be dispatched to a server chosen by the load balancer. The URI can be a partial * URI which does not contain the host name or the protocol. */ public T executeWithLoadBalancer(final S request, final IClientConfig requestConfig) throws ClientException { LoadBalancerCommand<T> command = buildLoadBalancerCommand(request, requestConfig); try { return command.submit( new ServerOperation<T>() { @Override public Observable<T> call(Server server) { URI finalUri = reconstructURIWithServer(server, request.getUri()); S requestForServer = (S) request.replaceUri(finalUri); try { return Observable.just(AbstractLoadBalancerAwareClient.this.execute(requestForServer, requestConfig)); } catch (Exception e) { return Observable.error(e); } } }) .toBlocking() .single(); } catch (Exception e) { Throwable t = e.getCause(); if (t instanceof ClientException) { throw (ClientException) t; } else { throw new ClientException(e); } } } public abstract RequestSpecificRetryHandler getRequestSpecificRetryHandler(S request, IClientConfig requestConfig); protected LoadBalancerCommand<T> buildLoadBalancerCommand(final S request, final IClientConfig config) { RequestSpecificRetryHandler handler = getRequestSpecificRetryHandler(request, config); LoadBalancerCommand.Builder<T> builder = LoadBalancerCommand.<T>builder() .withLoadBalancerContext(this) .withRetryHandler(handler) .withLoadBalancerURI(request.getUri()); customizeLoadBalancerCommandBuilder(request, config, builder); return builder.build(); } protected void customizeLoadBalancerCommandBuilder(final S request, final IClientConfig config, final LoadBalancerCommand.Builder<T> builder) { // do nothing by default, give a chance to its derived class to customize the builder } @Deprecated protected boolean isRetriable(S request) { if (request.isRetriable()) { return true; } else { boolean retryOkayOnOperation = okToRetryOnAllOperations; IClientConfig overriddenClientConfig = request.getOverrideConfig(); if (overriddenClientConfig != null) { retryOkayOnOperation = overriddenClientConfig.get(CommonClientConfigKey.RequestSpecificRetryOn, okToRetryOnAllOperations); } return retryOkayOnOperation; } } }
7,064
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/client/ClientFactory.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.client; import com.netflix.client.config.ClientConfigFactory; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.servo.monitor.Monitors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.InvocationTargetException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; /** * A factory that creates client, load balancer and client configuration instances from properties. It also keeps mappings of client names to * the created instances. * * @author awang * */ public class ClientFactory { private static Map<String, IClient<?,?>> simpleClientMap = new ConcurrentHashMap<String, IClient<?,?>>(); private static Map<String, ILoadBalancer> namedLBMap = new ConcurrentHashMap<String, ILoadBalancer>(); private static ConcurrentHashMap<String, IClientConfig> namedConfig = new ConcurrentHashMap<String, IClientConfig>(); private static Logger logger = LoggerFactory.getLogger(ClientFactory.class); /** * Utility method to create client and load balancer (if enabled in client config) given the name and client config. * Instances are created using reflection (see {@link #instantiateInstanceWithClientConfig(String, IClientConfig)} * * @param restClientName * @param clientConfig * @throws ClientException if any errors occurs in the process, or if the client with the same name already exists */ public static synchronized IClient<?, ?> registerClientFromProperties(String restClientName, IClientConfig clientConfig) throws ClientException { IClient<?, ?> client = null; ILoadBalancer loadBalancer = null; if (simpleClientMap.get(restClientName) != null) { throw new ClientException( ClientException.ErrorType.GENERAL, "A Rest Client with this name is already registered. Please use a different name"); } try { String clientClassName = clientConfig.getOrDefault(CommonClientConfigKey.ClientClassName); client = (IClient<?, ?>) instantiateInstanceWithClientConfig(clientClassName, clientConfig); boolean initializeNFLoadBalancer = clientConfig.getOrDefault(CommonClientConfigKey.InitializeNFLoadBalancer); if (initializeNFLoadBalancer) { loadBalancer = registerNamedLoadBalancerFromclientConfig(restClientName, clientConfig); } if (client instanceof AbstractLoadBalancerAwareClient) { ((AbstractLoadBalancerAwareClient) client).setLoadBalancer(loadBalancer); } } catch (Throwable e) { String message = "Unable to InitializeAndAssociateNFLoadBalancer set for RestClient:" + restClientName; logger.warn(message, e); throw new ClientException(ClientException.ErrorType.CONFIGURATION, message, e); } simpleClientMap.put(restClientName, client); Monitors.registerObject("Client_" + restClientName, client); logger.info("Client Registered:" + client.toString()); return client; } /** * Return the named client from map if already created. Otherwise creates the client using the configuration returned by {@link #getNamedConfig(String)}. * * @throws RuntimeException if an error occurs in creating the client. */ public static synchronized IClient getNamedClient(String name) { if (simpleClientMap.get(name) != null) { return simpleClientMap.get(name); } try { return registerClientFromProperties(name, getNamedConfig(name)); } catch (ClientException e) { throw new RuntimeException("Unable to create client", e); } } /** * Return the named client from map if already created. Otherwise creates the client using the configuration returned by {@link #createNamedClient(String, Class)}. * * @throws RuntimeException if an error occurs in creating the client. */ public static synchronized IClient getNamedClient(String name, Class<? extends IClientConfig> configClass) { if (simpleClientMap.get(name) != null) { return simpleClientMap.get(name); } try { return createNamedClient(name, configClass); } catch (ClientException e) { throw new RuntimeException("Unable to create client", e); } } /** * Creates a named client using a IClientConfig instance created off the configClass class object passed in as the parameter. * * @throws ClientException if any error occurs, or if the client with the same name already exists */ public static synchronized IClient createNamedClient(String name, Class<? extends IClientConfig> configClass) throws ClientException { IClientConfig config = getNamedConfig(name, configClass); return registerClientFromProperties(name, config); } /** * Get the load balancer associated with the name, or create one with the default {@link ClientConfigFactory} if does not exist * * @throws RuntimeException if any error occurs */ public static synchronized ILoadBalancer getNamedLoadBalancer(String name) { ILoadBalancer lb = namedLBMap.get(name); if (lb != null) { return lb; } else { try { lb = registerNamedLoadBalancerFromclientConfig(name, getNamedConfig(name)); } catch (ClientException e) { throw new RuntimeException("Unable to create load balancer", e); } namedLBMap.put(name, lb); return lb; } } /** * Get the load balancer associated with the name, or create one with an instance of configClass if does not exist * * @throws RuntimeException if any error occurs * @see #registerNamedLoadBalancerFromProperties(String, Class) */ public static synchronized ILoadBalancer getNamedLoadBalancer(String name, Class<? extends IClientConfig> configClass) { ILoadBalancer lb = namedLBMap.get(name); if (lb != null) { return lb; } else { try { lb = registerNamedLoadBalancerFromProperties(name, configClass); } catch (ClientException e) { throw new RuntimeException("Unable to create load balancer", e); } return lb; } } /** * Create and register a load balancer with the name and given the class of configClass. * * @throws ClientException if load balancer with the same name already exists or any error occurs * @see #instantiateInstanceWithClientConfig(String, IClientConfig) */ public static ILoadBalancer registerNamedLoadBalancerFromclientConfig(String name, IClientConfig clientConfig) throws ClientException { if (namedLBMap.get(name) != null) { throw new ClientException("LoadBalancer for name " + name + " already exists"); } ILoadBalancer lb = null; try { String loadBalancerClassName = clientConfig.getOrDefault(CommonClientConfigKey.NFLoadBalancerClassName); lb = (ILoadBalancer) ClientFactory.instantiateInstanceWithClientConfig(loadBalancerClassName, clientConfig); namedLBMap.put(name, lb); logger.info("Client: {} instantiated a LoadBalancer: {}", name, lb); return lb; } catch (Throwable e) { throw new ClientException("Unable to instantiate/associate LoadBalancer with Client:" + name, e); } } /** * Create and register a load balancer with the name and given the class of configClass. * * @throws ClientException if load balancer with the same name already exists or any error occurs * @see #instantiateInstanceWithClientConfig(String, IClientConfig) */ public static synchronized ILoadBalancer registerNamedLoadBalancerFromProperties(String name, Class<? extends IClientConfig> configClass) throws ClientException { if (namedLBMap.get(name) != null) { throw new ClientException("LoadBalancer for name " + name + " already exists"); } IClientConfig clientConfig = getNamedConfig(name, configClass); return registerNamedLoadBalancerFromclientConfig(name, clientConfig); } /** * Creates instance related to client framework using reflection. It first checks if the object is an instance of * {@link IClientConfigAware} and if so invoke {@link IClientConfigAware#initWithNiwsConfig(IClientConfig)}. If that does not * apply, it tries to find if there is a constructor with {@link IClientConfig} as a parameter and if so invoke that constructor. If neither applies, * it simply invokes the no-arg constructor and ignores the clientConfig parameter. * * @param className Class name of the object * @param clientConfig IClientConfig object used for initialization. */ @SuppressWarnings("unchecked") public static Object instantiateInstanceWithClientConfig(String className, IClientConfig clientConfig) throws InstantiationException, IllegalAccessException, ClassNotFoundException { Class clazz = Class.forName(className); if (IClientConfigAware.class.isAssignableFrom(clazz)) { IClientConfigAware obj = (IClientConfigAware) clazz.newInstance(); obj.initWithNiwsConfig(clientConfig); return obj; } else { try { if (clazz.getConstructor(IClientConfig.class) != null) { return clazz.getConstructor(IClientConfig.class).newInstance(clientConfig); } } catch (NoSuchMethodException ignored) { // OK for a class to not take an IClientConfig } catch (SecurityException | IllegalArgumentException | InvocationTargetException e) { logger.warn("Error getting/invoking IClientConfig constructor of {}", className, e); } } logger.warn("Class " + className + " neither implements IClientConfigAware nor provides a constructor with IClientConfig as the parameter. Only default constructor will be used."); return clazz.newInstance(); } /** * Get the client configuration given the name or create one with the resolved {@link ClientConfigFactory} if it does not exist. * * @see #getNamedConfig(String, Class) */ public static IClientConfig getNamedConfig(String name) { return getNamedConfig(name, ClientConfigFactory.DEFAULT::newConfig); } /** * Get the client configuration given the name or create one with clientConfigClass if it does not exist. An instance of IClientConfig * is created and {@link IClientConfig#loadProperties(String)} will be called. */ public static IClientConfig getNamedConfig(String name, Class<? extends IClientConfig> clientConfigClass) { return getNamedConfig(name, factoryFromConfigType(clientConfigClass)); } public static IClientConfig getNamedConfig(String name, Supplier<IClientConfig> factory) { return namedConfig.computeIfAbsent(name, ignore -> { try { IClientConfig config = factory.get(); config.loadProperties(name); return config; } catch (Exception e) { logger.error("Unable to create named client config '{}' instance for config factory {}", name, factory, e); return null; } }); } private static Supplier<IClientConfig> factoryFromConfigType(Class<? extends IClientConfig> clientConfigClass) { return () -> { try { return (IClientConfig) clientConfigClass.newInstance(); } catch (Exception e) { throw new RuntimeException(String.format("Failed to create config for class '%s'", clientConfigClass)); } }; } }
7,065
0
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix
Create_ds/ribbon/ribbon-loadbalancer/src/main/java/com/netflix/client/IPrimeConnection.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.client; import com.netflix.loadbalancer.Server; /** * Interface that defines operation for priming a connection. * * @author awang * */ public interface IPrimeConnection extends IClientConfigAware { /** * Sub classes should implement protocol specific operation to connect * to a server. * * @param server Server to connect * @param uriPath URI to use in server connection * @return if the priming is successful * @throws Exception Any network errors */ public boolean connect(Server server, String uriPath) throws Exception; }
7,066
0
Create_ds/ribbon/ribbon-transport/src/test/java/com/netflix/ribbon/transport
Create_ds/ribbon/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty/DynamicPropertyBasedPoolStrategyTest.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.ribbon.transport.netty; import static org.junit.Assert.*; import org.junit.Test; import com.netflix.config.ConfigurationManager; public class DynamicPropertyBasedPoolStrategyTest { @Test public void testResize() { ConfigurationManager.getConfigInstance().setProperty("foo", "150"); DynamicPropertyBasedPoolStrategy strategy = new DynamicPropertyBasedPoolStrategy(100, "foo"); assertEquals(150, strategy.getMaxConnections()); ConfigurationManager.getConfigInstance().setProperty("foo", "200"); assertEquals(200, strategy.getMaxConnections()); ConfigurationManager.getConfigInstance().setProperty("foo", "50"); assertEquals(50, strategy.getMaxConnections()); } }
7,067
0
Create_ds/ribbon/ribbon-transport/src/test/java/com/netflix/ribbon/transport
Create_ds/ribbon/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty/MyUDPClient.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.ribbon.transport.netty; import com.google.common.collect.Lists; import com.netflix.client.DefaultLoadBalancerRetryHandler; import com.netflix.client.config.IClientConfig; import com.netflix.ribbon.transport.netty.udp.LoadBalancingUdpClient; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.reactive.LoadBalancerCommand; import com.netflix.loadbalancer.reactive.ServerOperation; import com.netflix.loadbalancer.Server; import io.netty.channel.socket.DatagramPacket; import io.reactivex.netty.channel.ObservableConnection; import io.reactivex.netty.client.RxClient; import io.reactivex.netty.pipeline.PipelineConfigurator; import rx.Observable; import rx.functions.Func1; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Created by awang on 8/5/14. */ public class MyUDPClient extends LoadBalancingUdpClient<DatagramPacket, DatagramPacket> { private static final class MyRetryHandler extends DefaultLoadBalancerRetryHandler { @SuppressWarnings("unchecked") private List<Class<? extends Throwable>> timeoutExceptions = Lists.<Class<? extends Throwable>>newArrayList(TimeoutException.class); private MyRetryHandler(IClientConfig clientConfig) { super(clientConfig); } @Override protected List<Class<? extends Throwable>> getCircuitRelatedExceptions() { return timeoutExceptions; } } public MyUDPClient(IClientConfig config, PipelineConfigurator<DatagramPacket, DatagramPacket> pipelineConfigurator) { super(config, new MyRetryHandler(config), pipelineConfigurator); } public MyUDPClient(ILoadBalancer lb, IClientConfig config) { super(lb, config, new MyRetryHandler(config), null); } public Observable<DatagramPacket> submit(final String content) { return LoadBalancerCommand.<DatagramPacket>builder() .withLoadBalancerContext(lbContext) .build() .submit(new ServerOperation<DatagramPacket>() { @Override public Observable<DatagramPacket> call(Server server) { RxClient<DatagramPacket, DatagramPacket> rxClient = getOrCreateRxClient(server); return rxClient.connect().flatMap(new Func1<ObservableConnection<DatagramPacket, DatagramPacket>, Observable<? extends DatagramPacket>>() { @Override public Observable<? extends DatagramPacket> call(ObservableConnection<DatagramPacket, DatagramPacket> connection) { connection.writeStringAndFlush(content); return connection.getInput().timeout(10, TimeUnit.MILLISECONDS).take(1); } }); } }); } }
7,068
0
Create_ds/ribbon/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty
Create_ds/ribbon/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty/udp/HelloUdpServer.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.ribbon.transport.netty.udp; import io.netty.buffer.ByteBuf; import io.netty.channel.socket.DatagramPacket; import io.reactivex.netty.RxNetty; import io.reactivex.netty.channel.ConnectionHandler; import io.reactivex.netty.channel.ObservableConnection; import io.reactivex.netty.protocol.udp.server.UdpServer; import rx.Observable; import rx.functions.Func1; import java.net.InetSocketAddress; import java.nio.charset.Charset; import java.util.concurrent.TimeUnit; /** * Created by awang on 8/5/14. */ public final class HelloUdpServer { static final int DEFAULT_PORT = 8098; static final String WELCOME_MSG = "Welcome to the broadcast world!"; static final byte[] WELCOME_MSG_BYTES = WELCOME_MSG.getBytes(Charset.defaultCharset()); public final int port; public final int delay; public HelloUdpServer(int port, int delay) { this.port = port; this.delay = delay; } public HelloUdpServer(int port) { this.port = port; this.delay = 0; } public UdpServer<DatagramPacket, DatagramPacket> createServer() { UdpServer<DatagramPacket, DatagramPacket> server = RxNetty.createUdpServer(port, new ConnectionHandler<DatagramPacket, DatagramPacket>() { @Override public Observable<Void> handle(final ObservableConnection<DatagramPacket, DatagramPacket> newConnection) { return newConnection.getInput().flatMap(new Func1<DatagramPacket, Observable<Void>>() { @Override public Observable<Void> call(final DatagramPacket received) { return Observable.interval(delay, TimeUnit.MILLISECONDS).take(1).flatMap(new Func1<Long, Observable<Void>>() { @Override public Observable<Void> call(Long aLong) { InetSocketAddress sender = received.sender(); System.out.println("Received datagram. Sender: " + sender); ByteBuf data = newConnection.getChannel().alloc().buffer(WELCOME_MSG_BYTES.length); data.writeBytes(WELCOME_MSG_BYTES); return newConnection.writeAndFlush(new DatagramPacket(data, sender)); } }); } }); } }); System.out.println("UDP hello server started at port: " + port); return server; } public static void main(String[] args) { new HelloUdpServer(DEFAULT_PORT, 0).createServer().startAndWait(); } }
7,069
0
Create_ds/ribbon/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty
Create_ds/ribbon/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty/udp/UdpClientTest.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.ribbon.transport.netty.udp; import com.google.common.collect.Lists; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.ribbon.transport.netty.MyUDPClient; import com.netflix.ribbon.transport.netty.RibbonTransport; import com.netflix.loadbalancer.BaseLoadBalancer; import com.netflix.loadbalancer.Server; import io.netty.channel.socket.DatagramPacket; import io.reactivex.netty.channel.ObservableConnection; import io.reactivex.netty.client.RxClient; import io.reactivex.netty.protocol.udp.server.UdpServer; import org.junit.Test; import rx.Observable; import rx.functions.Func1; import java.net.DatagramSocket; import java.net.SocketException; import java.nio.charset.Charset; import java.util.concurrent.TimeoutException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Created by awang on 8/5/14. */ public class UdpClientTest { public int choosePort() throws SocketException { DatagramSocket serverSocket = new DatagramSocket(); int port = serverSocket.getLocalPort(); serverSocket.close(); return port; } @Test public void testUdpClientWithoutTimeout() throws Exception { int port = choosePort(); UdpServer<DatagramPacket, DatagramPacket> server = new HelloUdpServer(port, 0).createServer(); server.start(); BaseLoadBalancer lb = new BaseLoadBalancer(); lb.setServersList(Lists.newArrayList(new Server("localhost", port))); RxClient<DatagramPacket, DatagramPacket> client = RibbonTransport.newUdpClient(lb, DefaultClientConfigImpl.getClientConfigWithDefaultValues()); try { String response = client.connect().flatMap(new Func1<ObservableConnection<DatagramPacket, DatagramPacket>, Observable<DatagramPacket>>() { @Override public Observable<DatagramPacket> call(ObservableConnection<DatagramPacket, DatagramPacket> connection) { connection.writeStringAndFlush("Is there anybody out there?"); return connection.getInput(); } }).take(1) .map(new Func1<DatagramPacket, String>() { @Override public String call(DatagramPacket datagramPacket) { return datagramPacket.content().toString(Charset.defaultCharset()); } }) .toBlocking() .first(); assertEquals(HelloUdpServer.WELCOME_MSG, response); } finally { server.shutdown(); } } @Test public void testUdpClientTimeout() throws Exception { int port = choosePort(); UdpServer<DatagramPacket, DatagramPacket> server = new HelloUdpServer(port, 5000).createServer(); server.start(); BaseLoadBalancer lb = new BaseLoadBalancer(); Server myServer = new Server("localhost", port); lb.setServersList(Lists.newArrayList(myServer)); MyUDPClient client = new MyUDPClient(lb, DefaultClientConfigImpl.getClientConfigWithDefaultValues()); try { String response = client.submit("Is there anybody out there?") .map(new Func1<DatagramPacket, String>() { @Override public String call(DatagramPacket datagramPacket) { return datagramPacket.content().toString(Charset.defaultCharset()); } }) .toBlocking() .first(); fail("Exception expected"); } catch (Exception e) { assertTrue(e.getCause() instanceof TimeoutException); assertEquals(1, client.getLoadBalancerContext().getServerStats(myServer).getSuccessiveConnectionFailureCount()); } finally { server.shutdown(); } } }
7,070
0
Create_ds/ribbon/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty
Create_ds/ribbon/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty/http/NettyClientTest.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.ribbon.transport.netty.http; import static com.netflix.ribbon.testutils.TestUtils.waitUntilTrueOrTimeout; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufInputStream; import io.netty.buffer.Unpooled; import io.reactivex.netty.contexts.ContextsContainer; import io.reactivex.netty.contexts.ContextsContainerImpl; import io.reactivex.netty.contexts.MapBackedKeySupplier; import io.reactivex.netty.contexts.RxContexts; import io.reactivex.netty.protocol.http.client.HttpClient.HttpClientConfig; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import io.reactivex.netty.protocol.text.sse.ServerSentEvent; import io.reactivex.netty.servo.http.HttpClientListener; import java.io.IOException; import java.nio.charset.Charset; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; import org.codehaus.jackson.map.ObjectMapper; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import rx.Observable; import rx.functions.Action0; import rx.functions.Action1; import rx.functions.Func0; import rx.functions.Func1; import com.google.common.collect.Lists; import com.google.mockwebserver.MockResponse; import com.google.mockwebserver.MockWebServer; import com.netflix.client.ClientException; import com.netflix.client.RequestSpecificRetryHandler; import com.netflix.client.RetryHandler; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import com.netflix.loadbalancer.AvailabilityFilteringRule; import com.netflix.loadbalancer.BaseLoadBalancer; import com.netflix.loadbalancer.DummyPing; import com.netflix.loadbalancer.LoadBalancerBuilder; import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.ServerStats; import com.netflix.ribbon.test.resources.EmbeddedResources; import com.netflix.ribbon.test.resources.EmbeddedResources.Person; import com.netflix.ribbon.transport.netty.RibbonTransport; import com.netflix.serialization.JacksonCodec; import com.netflix.serialization.SerializationUtils; import com.netflix.serialization.TypeDef; import com.sun.jersey.api.container.httpserver.HttpServerFactory; import com.sun.jersey.api.core.PackagesResourceConfig; import com.sun.net.httpserver.HttpServer; public class NettyClientTest { private static HttpServer server = null; private static String SERVICE_URI; private static int port; private static final String host = "localhost"; static Observable<ServerSentEvent> transformSSE(Observable<HttpClientResponse<ServerSentEvent>> response) { return response.flatMap(new Func1<HttpClientResponse<ServerSentEvent>, Observable<ServerSentEvent>>() { @Override public Observable<ServerSentEvent> call(HttpClientResponse<ServerSentEvent> t1) { return t1.getContent(); } }); } @BeforeClass public static void init() throws Exception { PackagesResourceConfig resourceConfig = new PackagesResourceConfig("com.netflix.ribbon.test.resources"); port = (new Random()).nextInt(1000) + 4000; SERVICE_URI = "http://localhost:" + port + "/"; ExecutorService service = Executors.newFixedThreadPool(20); try{ server = HttpServerFactory.create(SERVICE_URI, resourceConfig); server.setExecutor(service); server.start(); } catch(Exception e) { e.printStackTrace(); fail("Unable to start server"); } // LogManager.getRootLogger().setLevel(Level.DEBUG); } private static Observable<Person> getPersonObservable(Observable<HttpClientResponse<ByteBuf>> response) { return response.flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>>() { @Override public Observable<ByteBuf> call(HttpClientResponse<ByteBuf> t1) { return t1.getContent(); } }).map(new Func1<ByteBuf, Person>() { @Override public Person call(ByteBuf t1) { try { return JacksonCodec.<Person>getInstance().deserialize(new ByteBufInputStream(t1), TypeDef.fromClass(Person.class)); } catch (IOException e) { e.printStackTrace(); return null; } } }); } @Test public void testObservable() throws Exception { HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet(SERVICE_URI + "testAsync/person"); LoadBalancingHttpClient<ByteBuf, ByteBuf> observableClient = RibbonTransport.newHttpClient(); Observable<HttpClientResponse<ByteBuf>> response = observableClient.submit(request); Person person = getPersonObservable(response).toBlocking().single(); assertEquals(EmbeddedResources.defaultPerson, person); final HttpClientListener listener = observableClient.getListener(); assertEquals(1, listener.getPoolAcquires()); assertEquals(1, listener.getConnectionCount()); waitUntilTrueOrTimeout(1000, new Func0<Boolean>() { @Override public Boolean call() { return listener.getPoolReleases() == 1; } }); } @Test public void testSubmitToAbsoluteURI() throws Exception { HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet(SERVICE_URI + "testAsync/person"); LoadBalancingHttpClient<ByteBuf, ByteBuf> observableClient = RibbonTransport.newHttpClient(); // final List<Person> result = Lists.newArrayList(); Observable<HttpClientResponse<ByteBuf>> response = observableClient.submit(request); Person person = getPersonObservable(response).toBlocking().single(); assertEquals(EmbeddedResources.defaultPerson, person); // need to sleep to wait until connection is released final HttpClientListener listener = observableClient.getListener(); assertEquals(1, listener.getConnectionCount()); assertEquals(1, listener.getPoolAcquires()); waitUntilTrueOrTimeout(1000, new Func0<Boolean>() { @Override public Boolean call() { return listener.getPoolReleases() == 1; } }); } @Test public void testPoolReuse() throws Exception { HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet(SERVICE_URI + "testAsync/person"); LoadBalancingHttpClient<ByteBuf, ByteBuf> observableClient = RibbonTransport.newHttpClient( IClientConfig.Builder.newBuilder().withDefaultValues() .withMaxAutoRetries(1) .withMaxAutoRetriesNextServer(1).build()); Observable<HttpClientResponse<ByteBuf>> response = observableClient.submit(request); Person person = getPersonObservable(response).toBlocking().single(); assertEquals(EmbeddedResources.defaultPerson, person); response = observableClient.submit(request); person = getPersonObservable(response).toBlocking().single(); assertEquals(EmbeddedResources.defaultPerson, person); final HttpClientListener listener = observableClient.getListener(); assertEquals(2, listener.getPoolAcquires()); waitUntilTrueOrTimeout(1000, new Func0<Boolean>() { @Override public Boolean call() { return listener.getPoolReleases() == 2; } }); assertEquals(1, listener.getConnectionCount()); assertEquals(1, listener.getPoolReuse()); } @Test public void testPostWithObservable() throws Exception { Person myPerson = new Person("netty", 5); HttpClientRequest<ByteBuf> request = HttpClientRequest.createPost(SERVICE_URI + "testAsync/person") .withHeader("Content-type", "application/json") .withContent(SerializationUtils.serializeToBytes(JacksonCodec.getInstance(), myPerson, null)); LoadBalancingHttpClient<ByteBuf, ByteBuf> observableClient = RibbonTransport.newHttpClient( DefaultClientConfigImpl.getClientConfigWithDefaultValues().set(CommonClientConfigKey.ReadTimeout, 10000)); Observable<HttpClientResponse<ByteBuf>> response = observableClient.submit(new Server(host, port), request); Person person = getPersonObservable(response).toBlocking().single(); assertEquals(myPerson, person); } @Test public void testPostWithByteBuf() throws Exception { Person myPerson = new Person("netty", 5); ObjectMapper mapper = new ObjectMapper(); byte[] raw = mapper.writeValueAsBytes(myPerson); ByteBuf buffer = Unpooled.copiedBuffer(raw); HttpClientRequest<ByteBuf> request = HttpClientRequest.createPost(SERVICE_URI + "testAsync/person") .withHeader("Content-type", "application/json") .withHeader("Content-length", String.valueOf(raw.length)) .withContent(buffer); LoadBalancingHttpClient<ByteBuf, ByteBuf> observableClient = RibbonTransport.newHttpClient( DefaultClientConfigImpl.getClientConfigWithDefaultValues().set(CommonClientConfigKey.ReadTimeout, 10000)); Observable<HttpClientResponse<ByteBuf>> response = observableClient.submit(request); Person person = getPersonObservable(response).toBlocking().single(); assertEquals(myPerson, person); } @Test public void testConnectTimeout() throws Exception { LoadBalancingHttpClient<ByteBuf, ByteBuf> observableClient = RibbonTransport.newHttpClient( DefaultClientConfigImpl.getClientConfigWithDefaultValues().withProperty(CommonClientConfigKey.ConnectTimeout, "1")); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("http://www.google.com:81/"); Observable<HttpClientResponse<ByteBuf>> observable = observableClient.submit(new Server("www.google.com", 81), request); ObserverWithLatch<HttpClientResponse<ByteBuf>> observer = new ObserverWithLatch<HttpClientResponse<ByteBuf>>(); observable.subscribe(observer); observer.await(); assertNotNull(observer.error); assertTrue(observer.error instanceof io.netty.channel.ConnectTimeoutException); } @Test public void testReadTimeout() throws Exception { LoadBalancingHttpClient<ByteBuf, ByteBuf> observableClient = RibbonTransport.newHttpClient( DefaultClientConfigImpl.getClientConfigWithDefaultValues().withProperty(CommonClientConfigKey.ReadTimeout, "100")); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet(SERVICE_URI + "testAsync/readTimeout"); Observable<HttpClientResponse<ByteBuf>> observable = observableClient.submit(request); ObserverWithLatch<HttpClientResponse<ByteBuf>> observer = new ObserverWithLatch<HttpClientResponse<ByteBuf>>(); observable.subscribe(observer); observer.await(); assertTrue(observer.error instanceof io.netty.handler.timeout.ReadTimeoutException); } @Test public void testObservableWithMultipleServers() throws Exception { IClientConfig config = DefaultClientConfigImpl .getClientConfigWithDefaultValues() .withProperty(CommonClientConfigKey.ConnectTimeout, "1000"); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/person"); Server badServer = new Server("localhost:12345"); Server goodServer = new Server("localhost:" + port); List<Server> servers = Lists.newArrayList(badServer, badServer, badServer, goodServer); BaseLoadBalancer lb = LoadBalancerBuilder.<Server>newBuilder() .withRule(new AvailabilityFilteringRule()) .withPing(new DummyPing()) .buildFixedServerListLoadBalancer(servers); LoadBalancingHttpClient<ByteBuf, ByteBuf> lbObservables = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(1, 3, true)); Person person = getPersonObservable(lbObservables.submit(request)).toBlocking().single(); assertEquals(EmbeddedResources.defaultPerson, person); ServerStats stats = lbObservables.getServerStats(badServer); // two requests to bad server because retry same server is set to 1 assertEquals(4, stats.getTotalRequestsCount()); assertEquals(0, stats.getActiveRequestsCount()); assertEquals(4, stats.getSuccessiveConnectionFailureCount()); stats = lbObservables.getServerStats(goodServer); assertEquals(1, stats.getTotalRequestsCount()); assertEquals(0, stats.getActiveRequestsCount()); assertEquals(0, stats.getSuccessiveConnectionFailureCount()); person = getPersonObservable(lbObservables.submit(request)).toBlocking().single(); assertEquals(EmbeddedResources.defaultPerson, person); HttpClientListener listener = lbObservables.getListener(); assertEquals(1, listener.getPoolReuse()); } @Test public void testObservableWithMultipleServersWithOverrideRxConfig() throws Exception { IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues().withProperty(CommonClientConfigKey.ConnectTimeout, "1000"); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/person"); Server badServer = new Server("localhost:12345"); Server goodServer = new Server("localhost:" + port); List<Server> servers = Lists.newArrayList(badServer, badServer, badServer, goodServer); BaseLoadBalancer lb = LoadBalancerBuilder.<Server>newBuilder() .withRule(new AvailabilityFilteringRule()) .withPing(new DummyPing()) .buildFixedServerListLoadBalancer(servers); LoadBalancingHttpClient<ByteBuf, ByteBuf> lbObservables = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(1, 3, true)); HttpClientConfig rxconfig = HttpClientConfig.Builder.newDefaultConfig(); Person person = getPersonObservable(lbObservables.submit(request, rxconfig)).toBlocking().single(); assertEquals(EmbeddedResources.defaultPerson, person); ServerStats stats = lbObservables.getServerStats(badServer); // two requests to bad server because retry same server is set to 1 assertEquals(4, stats.getTotalRequestsCount()); assertEquals(0, stats.getActiveRequestsCount()); assertEquals(4, stats.getSuccessiveConnectionFailureCount()); stats = lbObservables.getServerStats(goodServer); assertEquals(1, stats.getTotalRequestsCount()); assertEquals(0, stats.getActiveRequestsCount()); assertEquals(0, stats.getSuccessiveConnectionFailureCount()); final HttpClientListener listener = lbObservables.getListener(); assertEquals(1, listener.getConnectionCount()); waitUntilTrueOrTimeout(1000, new Func0<Boolean>() { @Override public Boolean call() { return listener.getPoolReleases() == 1; } }); } @Test public void testObservableWithRetrySameServer() throws Exception { IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues().withProperty(CommonClientConfigKey.ConnectTimeout, "1000"); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/person"); Server badServer = new Server("localhost:12345"); Server goodServer = new Server("localhost:" + port); List<Server> servers = Lists.newArrayList(badServer, badServer, goodServer); BaseLoadBalancer lb = LoadBalancerBuilder.<Server>newBuilder() .withRule(new AvailabilityFilteringRule()) .withPing(new DummyPing()) .buildFixedServerListLoadBalancer(servers); LoadBalancingHttpClient<ByteBuf, ByteBuf> lbObservables = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(1, 0, true)); Observable<Person> observableWithRetries = getPersonObservable(lbObservables.submit(request)); ObserverWithLatch<Person> observer = new ObserverWithLatch<Person>(); observableWithRetries.subscribe(observer); observer.await(); assertNull(observer.obj); assertTrue(observer.error instanceof ClientException); ServerStats stats = lbObservables.getServerStats(badServer); // two requests to bad server because retry same server is set to 1 assertEquals(2, stats.getTotalRequestsCount()); assertEquals(0, stats.getActiveRequestsCount()); stats = lbObservables.getServerStats(goodServer); assertEquals(0, stats.getTotalRequestsCount()); } @Test public void testLoadBalancingObservablesWithReadTimeout() throws Exception { NettyHttpLoadBalancerErrorHandler errorHandler = new NettyHttpLoadBalancerErrorHandler(1, 3, true); MockWebServer server = new MockWebServer(); String content = "{\"name\": \"ribbon\", \"age\": 2}"; server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-type", "application/json") .setBody(content)); server.play(); IClientConfig config = DefaultClientConfigImpl .getClientConfigWithDefaultValues() .set(CommonClientConfigKey.ReadTimeout, 100); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/readTimeout"); BaseLoadBalancer lb = new BaseLoadBalancer(new DummyPing(), new AvailabilityFilteringRule()); LoadBalancingHttpClient<ByteBuf, ByteBuf> lbObservables = RibbonTransport.newHttpClient(lb, config, errorHandler); Server goodServer = new Server("localhost:" + server.getPort()); Server badServer = new Server("localhost:" + port); lb.setServersList(Lists.newArrayList(goodServer, badServer, badServer, goodServer)); Observable<Person> observableWithRetries = getPersonObservable(lbObservables.submit(request)); ObserverWithLatch<Person> observer = new ObserverWithLatch<Person>(); observableWithRetries.subscribe(observer); observer.await(); if (observer.error != null) { observer.error.printStackTrace(); } assertEquals("ribbon", observer.obj.name); assertEquals(2, observer.obj.age); ServerStats stats = lbObservables.getServerStats(badServer); server.shutdown(); final HttpClientListener listener = lbObservables.getListener(); waitUntilTrueOrTimeout(1000, new Func0<Boolean>() { @Override public Boolean call() { return listener.getPoolReleases() == 5; } }); assertEquals(0, listener.getPoolReuse()); // two requests to bad server because retry same server is set to 1 assertEquals(4, stats.getTotalRequestsCount()); assertEquals(0, stats.getActiveRequestsCount()); assertEquals(4, stats.getSuccessiveConnectionFailureCount()); stats = lbObservables.getServerStats(goodServer); assertEquals(1, stats.getTotalRequestsCount()); assertEquals(0, stats.getActiveRequestsCount()); assertEquals(0, stats.getSuccessiveConnectionFailureCount()); } @Test public void testLoadBalancingWithTwoServers() throws Exception { MockWebServer server = new MockWebServer(); String content = "{\"name\": \"ribbon\", \"age\": 2}"; server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-type", "application/json") .setBody(content)); server.play(); IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues(); HttpClientRequest<ByteBuf> request = HttpClientRequest.createPost("/testAsync/person") .withContent(SerializationUtils.serializeToBytes(JacksonCodec.getInstance(), EmbeddedResources.defaultPerson, null)) .withHeader("Content-type", "application/json"); NettyHttpLoadBalancerErrorHandler errorHandler = new NettyHttpLoadBalancerErrorHandler(1, 3, true); BaseLoadBalancer lb = new BaseLoadBalancer(new DummyPing(), new AvailabilityFilteringRule()); LoadBalancingHttpClient<ByteBuf, ByteBuf> lbObservables = RibbonTransport.newHttpClient(lb, config, errorHandler); HttpClientListener externalListener = HttpClientListener.newHttpListener("external"); lbObservables.subscribe(externalListener); Server server1 = new Server("localhost:" + server.getPort()); Server server2 = new Server("localhost:" + port); lb.setServersList(Lists.newArrayList(server1, server2)); RetryHandler handler = new RequestSpecificRetryHandler(true, true, errorHandler, null) { @Override public boolean isRetriableException(Throwable e, boolean sameServer) { return true; } }; Observable<Person> observableWithRetries = getPersonObservable(lbObservables.submit(request, handler, null)); ObserverWithLatch<Person> observer = new ObserverWithLatch<Person>(); observableWithRetries.subscribe(observer); observer.await(); if (observer.error != null) { observer.error.printStackTrace(); } assertEquals("ribbon", observer.obj.name); assertEquals(EmbeddedResources.defaultPerson.age, observer.obj.age); observer = new ObserverWithLatch<Person>(); observableWithRetries = getPersonObservable(lbObservables.submit(request, handler, null)); observableWithRetries.subscribe(observer); observer.await(); if (observer.error != null) { observer.error.printStackTrace(); } assertEquals("ribbon", observer.obj.name); assertEquals(2, observer.obj.age); ServerStats stats = lbObservables.getServerStats(server1); server.shutdown(); // assertEquals(1, stats.getTotalRequestsCount()); assertEquals(0, stats.getActiveRequestsCount()); stats = lbObservables.getServerStats(server2); // two requests to bad server because retry same server is set to 1 assertEquals(1, stats.getTotalRequestsCount()); assertEquals(0, stats.getActiveRequestsCount()); assertEquals(0, stats.getSuccessiveConnectionFailureCount()); final HttpClientListener listener = lbObservables.getListener(); assertEquals(2, listener.getPoolAcquires()); waitUntilTrueOrTimeout(1000, new Func0<Boolean>() { @Override public Boolean call() { return listener.getPoolReleases() == 2; } }); assertEquals(2, listener.getConnectionCount()); assertEquals(0, listener.getPoolReuse()); assertEquals(2, externalListener.getPoolAcquires()); } @Test public void testLoadBalancingPostWithReadTimeout() throws Exception { MockWebServer server = new MockWebServer(); String content = "{\"name\": \"ribbon\", \"age\": 2}"; server.enqueue(new MockResponse() .setResponseCode(200) .setHeader("Content-type", "application/json") .setBody(content)); server.play(); IClientConfig config = DefaultClientConfigImpl .getClientConfigWithDefaultValues() .set(CommonClientConfigKey.ReadTimeout, 100); HttpClientRequest<ByteBuf> request = HttpClientRequest.createPost("/testAsync/postTimeout") .withContent(SerializationUtils.serializeToBytes(JacksonCodec.getInstance(), EmbeddedResources.defaultPerson, null)) .withHeader("Content-type", "application/json"); NettyHttpLoadBalancerErrorHandler errorHandler = new NettyHttpLoadBalancerErrorHandler(1, 3, true); BaseLoadBalancer lb = new BaseLoadBalancer(new DummyPing(), new AvailabilityFilteringRule()); LoadBalancingHttpClient<ByteBuf, ByteBuf> lbObservables = RibbonTransport.newHttpClient(lb, config, errorHandler); Server goodServer = new Server("localhost:" + server.getPort()); Server badServer = new Server("localhost:" + port); List<Server> servers = Lists.newArrayList(badServer, badServer, badServer, goodServer); lb.setServersList(servers); RetryHandler handler = new RequestSpecificRetryHandler(true, true, errorHandler, null) { @Override public boolean isRetriableException(Throwable e, boolean sameServer) { return true; } }; Observable<Person> observableWithRetries = getPersonObservable(lbObservables.submit(request, handler, null)); ObserverWithLatch<Person> observer = new ObserverWithLatch<Person>(); observableWithRetries.subscribe(observer); observer.await(); if (observer.error != null) { observer.error.printStackTrace(); } assertEquals("ribbon", observer.obj.name); assertEquals(2, observer.obj.age); ServerStats stats = lbObservables.getServerStats(badServer); server.shutdown(); assertEquals(4, stats.getTotalRequestsCount()); assertEquals(0, stats.getActiveRequestsCount()); assertEquals(4, stats.getSuccessiveConnectionFailureCount()); stats = lbObservables.getServerStats(goodServer); // two requests to bad server because retry same server is set to 1 assertEquals(1, stats.getTotalRequestsCount()); assertEquals(0, stats.getActiveRequestsCount()); assertEquals(0, stats.getSuccessiveConnectionFailureCount()); } @Test public void testLoadBalancingPostWithNoRetrySameServer() throws Exception { MockWebServer server = new MockWebServer(); String content = "{\"name\": \"ribbon\", \"age\": 2}"; server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-type", "application/json") .setBody(content)); server.play(); IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues() .set(CommonClientConfigKey.ReadTimeout, 100); HttpClientRequest<ByteBuf> request = HttpClientRequest.createPost("/testAsync/postTimeout") .withContent(SerializationUtils.serializeToBytes(JacksonCodec.getInstance(), EmbeddedResources.defaultPerson, null)) .withHeader("Content-type", "application/json"); NettyHttpLoadBalancerErrorHandler errorHandler = new NettyHttpLoadBalancerErrorHandler(0, 3, true); BaseLoadBalancer lb = new BaseLoadBalancer(new DummyPing(), new AvailabilityFilteringRule()); LoadBalancingHttpClient<ByteBuf, ByteBuf> lbObservables = RibbonTransport.newHttpClient(lb, config, errorHandler); Server goodServer = new Server("localhost:" + server.getPort()); Server badServer = new Server("localhost:" + port); List<Server> servers = Lists.newArrayList(badServer, badServer, badServer, goodServer); lb.setServersList(servers); RetryHandler handler = new RequestSpecificRetryHandler(true, true, errorHandler, null) { @Override public boolean isRetriableException(Throwable e, boolean sameServer) { return true; } }; Observable<Person> observableWithRetries = getPersonObservable(lbObservables.submit(request, handler, null)); ObserverWithLatch<Person> observer = new ObserverWithLatch<Person>(); observableWithRetries.subscribe(observer); observer.await(); if (observer.error != null) { observer.error.printStackTrace(); } server.shutdown(); assertEquals("ribbon", observer.obj.name); assertEquals(2, observer.obj.age); ServerStats stats = lbObservables.getServerStats(badServer); assertEquals(2, stats.getTotalRequestsCount()); assertEquals(0, stats.getActiveRequestsCount()); assertEquals(2, stats.getSuccessiveConnectionFailureCount()); stats = lbObservables.getServerStats(goodServer); assertEquals(1, stats.getTotalRequestsCount()); assertEquals(0, stats.getActiveRequestsCount()); assertEquals(0, stats.getSuccessiveConnectionFailureCount()); } @Test public void testObservableWithMultipleServersFailed() throws Exception { IClientConfig config = IClientConfig.Builder.newBuilder() .withDefaultValues() .withRetryOnAllOperations(true) .withMaxAutoRetries(1) .withMaxAutoRetriesNextServer(3) .withConnectTimeout(100) .build(); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/person"); BaseLoadBalancer lb = new BaseLoadBalancer(new DummyPing(), new AvailabilityFilteringRule()); LoadBalancingHttpClient<ByteBuf, ByteBuf> lbObservables = RibbonTransport.newHttpClient(lb, config); Server badServer = new Server("localhost:12345"); Server badServer1 = new Server("localhost:12346"); Server badServer2 = new Server("localhost:12347"); List<Server> servers = Lists.newArrayList(badServer, badServer1, badServer2); lb.setServersList(servers); Observable<Person> observableWithRetries = getPersonObservable(lbObservables.submit(request)); ObserverWithLatch<Person> observer = new ObserverWithLatch<Person>(); observableWithRetries.subscribe(observer); observer.await(); assertNull(observer.obj); observer.error.printStackTrace(); assertTrue(observer.error instanceof ClientException); ServerStats stats = lbObservables.getServerStats(badServer); // two requests to bad server because retry same server is set to 1 assertEquals(2, stats.getTotalRequestsCount()); assertEquals(0, stats.getActiveRequestsCount()); assertEquals(2, stats.getSuccessiveConnectionFailureCount()); } private static List<Person> getPersonListFromResponse(Observable<HttpClientResponse<ServerSentEvent>> response) { return getPersonList(transformSSE(response)); } private static List<Person> getPersonList(Observable<ServerSentEvent> events) { List<Person> result = Lists.newArrayList(); Iterator<Person> iterator = events.map(new Func1<ServerSentEvent, Person>() { @Override public Person call(ServerSentEvent t1) { String content = t1.getEventData(); try { return SerializationUtils.deserializeFromString(JacksonCodec.<Person>getInstance(), content, TypeDef.fromClass(Person.class)); } catch (IOException e) { e.printStackTrace(); return null; } } }).toBlocking().getIterator(); while (iterator.hasNext()) { result.add(iterator.next()); } return result; } @Test public void testStream() throws Exception { HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet(SERVICE_URI + "testAsync/personStream"); LoadBalancingHttpClient<ByteBuf, ServerSentEvent> observableClient = (LoadBalancingHttpClient<ByteBuf, ServerSentEvent>) RibbonTransport.newSSEClient(); List<Person> result = getPersonListFromResponse(observableClient.submit(new Server(host, port), request)); assertEquals(EmbeddedResources.entityStream, result); } @Test public void testStreamWithLoadBalancer() throws Exception { // NettyHttpLoadBalancerErrorHandler errorHandler = new NettyHttpLoadBalancerErrorHandler(1, 3, true); // IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues().withProperty(CommonClientConfigKey.ConnectTimeout, "1000"); IClientConfig config = IClientConfig.Builder.newBuilder().withRetryOnAllOperations(true) .withMaxAutoRetries(1) .withMaxAutoRetriesNextServer(3) .build(); BaseLoadBalancer lb = new BaseLoadBalancer(new DummyPing(), new AvailabilityFilteringRule()); LoadBalancingHttpClient<ByteBuf, ServerSentEvent> lbObservables = (LoadBalancingHttpClient<ByteBuf, ServerSentEvent>) RibbonTransport.newSSEClient(lb, config); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/personStream"); List<Person> result = Lists.newArrayList(); Server goodServer = new Server("localhost:" + port); Server badServer = new Server("localhost:12245"); List<Server> servers = Lists.newArrayList(badServer, badServer, badServer, goodServer); lb.setServersList(servers); result = getPersonListFromResponse(lbObservables.submit(request, null, null)); assertEquals(EmbeddedResources.entityStream, result); } @Test public void testQuery() throws Exception { Person myPerson = new Person("hello_world", 4); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet(SERVICE_URI + "testAsync/personQuery?name=" + myPerson.name + "&age=" + myPerson.age); LoadBalancingHttpClient<ByteBuf, ByteBuf> observableClient = RibbonTransport.newHttpClient(); Person person = getPersonObservable(observableClient.submit(new Server(host, port), request)).toBlocking().single(); assertEquals(myPerson, person); } @Test public void testUnexpectedResponse() throws Exception { HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet(SERVICE_URI + "testAsync/throttle"); LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(); Observable<HttpClientResponse<ByteBuf>> responseObservable = client.submit(new Server(host, port), request); final AtomicReference<Throwable> error = new AtomicReference<Throwable>(); final CountDownLatch latch = new CountDownLatch(1); responseObservable.subscribe(new Action1<HttpClientResponse<ByteBuf>>() { @Override public void call(HttpClientResponse<ByteBuf> t1) { latch.countDown(); } }, new Action1<Throwable>(){ @Override public void call(Throwable t1) { error.set(t1); latch.countDown(); } }); latch.await(); assertTrue(error.get() instanceof ClientException); ClientException ce = (ClientException) error.get(); assertTrue(ce.getErrorType() == ClientException.ErrorType.SERVER_THROTTLED); } @Test public void testLoadBalancerThrottle() throws Exception { HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/throttle"); IClientConfig config = DefaultClientConfigImpl .getClientConfigWithDefaultValues() .set(IClientConfigKey.Keys.MaxAutoRetriesNextServer, 1) .set(IClientConfigKey.Keys.OkToRetryOnAllOperations, true); BaseLoadBalancer lb = new BaseLoadBalancer(new DummyPing(), new AvailabilityFilteringRule()); LoadBalancingHttpClient<ByteBuf, ByteBuf> lbObservables = RibbonTransport.newHttpClient(lb, config); Server server = new Server(host, port); lb.setServersList(Lists.newArrayList(server, server, server)); Observable<HttpClientResponse<ByteBuf>> response = lbObservables.submit(request); final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> error = new AtomicReference<Throwable>(); response.subscribe(new Action1<HttpClientResponse<ByteBuf>>() { @Override public void call(HttpClientResponse<ByteBuf> t1) { System.err.println("Get response: " + t1.getStatus().code()); latch.countDown(); } }, new Action1<Throwable>(){ @Override public void call(Throwable t1) { error.set(t1); latch.countDown(); } }, new Action0() { @Override public void call() { Thread.dumpStack(); latch.countDown(); } }); latch.await(); assertTrue(error.get() instanceof ClientException); ClientException ce = (ClientException) error.get(); assertTrue(ce.toString(), ce.getErrorType() == ClientException.ErrorType.NUMBEROF_RETRIES_NEXTSERVER_EXCEEDED); assertEquals(2, lbObservables.getServerStats(server).getSuccessiveConnectionFailureCount()); } @Test public void testContext() throws Exception { HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet(SERVICE_URI + "testAsync/context"); LoadBalancingHttpClient<ByteBuf, ByteBuf> observableClient = RibbonTransport.newHttpClient(); String requestId = "xyz"; ContextsContainerImpl contextsContainer = new ContextsContainerImpl(new MapBackedKeySupplier()); contextsContainer.addContext("Context1", "value1"); RxContexts.DEFAULT_CORRELATOR.onNewServerRequest(requestId, contextsContainer); Observable<HttpClientResponse<ByteBuf>> response = observableClient.submit(new Server(host, port), request); final AtomicReference<ContextsContainer> responseContext = new AtomicReference<ContextsContainer>(); String requestIdSent = response.flatMap(new Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>>() { @Override public Observable<ByteBuf> call(HttpClientResponse<ByteBuf> t1) { return t1.getContent(); } }).map(new Func1<ByteBuf, String>() { @Override public String call(ByteBuf t1) { String requestId = RxContexts.DEFAULT_CORRELATOR.getRequestIdForClientRequest(); responseContext.set(RxContexts.DEFAULT_CORRELATOR.getContextForClientRequest(requestId)); return t1.toString(Charset.defaultCharset()); } }).toBlocking().single(); assertEquals(requestId, requestIdSent); assertEquals("value1", responseContext.get().getContext("Context1")); } @Test @Ignore public void testRedirect() throws Exception { HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet(SERVICE_URI + "testAsync/redirect?port=" + port); LoadBalancingHttpClient<ByteBuf, ByteBuf> observableClient = RibbonTransport.newHttpClient( IClientConfig.Builder.newBuilder().withDefaultValues() .withFollowRedirects(true) .build()); Person person = getPersonObservable(observableClient.submit(new Server(host, port), request)).toBlocking().single(); assertEquals(EmbeddedResources.defaultPerson, person); } }
7,071
0
Create_ds/ribbon/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty
Create_ds/ribbon/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty/http/ObserverWithLatch.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.ribbon.transport.netty.http; import rx.Observer; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.fail; public class ObserverWithLatch<T> implements Observer<T> { public volatile T obj; public volatile Throwable error; private CountDownLatch latch = new CountDownLatch(1); public AtomicInteger nextCounter = new AtomicInteger(); public AtomicInteger errorCounter = new AtomicInteger(); @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Throwable e) { this.error = e; errorCounter.incrementAndGet(); latch.countDown(); } @Override public void onNext(T obj) { this.obj = obj; nextCounter.incrementAndGet(); } public void await() { boolean completed = false; try { completed = latch.await(10, TimeUnit.SECONDS); } catch (Exception e) { // NOPMD } if (!completed) { fail("Observer not completed"); } if (nextCounter.get() == 0 && errorCounter.get() == 0) { fail("onNext() or onError() is not called"); } } }
7,072
0
Create_ds/ribbon/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty
Create_ds/ribbon/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty/http/ListenerTest.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.ribbon.transport.netty.http; import com.google.common.collect.Lists; import com.google.mockwebserver.MockResponse; import com.google.mockwebserver.MockWebServer; import com.netflix.client.ClientException; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfig; import com.netflix.config.ConfigurationManager; import com.netflix.loadbalancer.AvailabilityFilteringRule; import com.netflix.loadbalancer.BaseLoadBalancer; import com.netflix.loadbalancer.DummyPing; import com.netflix.loadbalancer.LoadBalancerBuilder; import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.reactive.ExecutionContext; import com.netflix.loadbalancer.reactive.ExecutionInfo; import com.netflix.loadbalancer.reactive.ExecutionListener; import com.netflix.loadbalancer.reactive.ExecutionListener.AbortExecutionException; import com.netflix.ribbon.transport.netty.RibbonTransport; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import org.junit.Ignore; import org.junit.Test; import rx.functions.Action1; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import static org.junit.Assert.*; /** * @author Allen Wang */ public class ListenerTest { @Test public void testFailedExecution() { IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues() .withProperty(CommonClientConfigKey.ConnectTimeout, "100") .withProperty(CommonClientConfigKey.MaxAutoRetries, 1) .withProperty(CommonClientConfigKey.MaxAutoRetriesNextServer, 1); System.out.println(config); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/person"); Server badServer = new Server("localhost:12345"); Server badServer2 = new Server("localhost:34567"); List<Server> servers = Lists.newArrayList(badServer, badServer2); BaseLoadBalancer lb = LoadBalancerBuilder.<Server>newBuilder() .withRule(new AvailabilityFilteringRule()) .withPing(new DummyPing()) .buildFixedServerListLoadBalancer(servers); IClientConfig overrideConfig = DefaultClientConfigImpl.getEmptyConfig(); TestExecutionListener<ByteBuf, ByteBuf> listener = new TestExecutionListener<ByteBuf, ByteBuf>(request, overrideConfig); List<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>> listeners = Lists.<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>>newArrayList(listener); LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(config), listeners); try { client.submit(request, null, overrideConfig).toBlocking().last(); fail("Exception expected"); } catch(Exception e) { assertNotNull(e); } assertEquals(1, listener.executionStartCounter.get()); assertEquals(4, listener.startWithServerCounter.get()); assertEquals(4, listener.exceptionWithServerCounter.get()); assertEquals(1, listener.executionFailedCounter.get()); assertTrue(listener.isContextChecked()); assertTrue(listener.isCheckExecutionInfo()); assertNotNull(listener.getFinalThrowable()); listener.getFinalThrowable().printStackTrace(); assertTrue(listener.getFinalThrowable() instanceof ClientException); assertEquals(100, listener.getContext().getClientProperty(CommonClientConfigKey.ConnectTimeout).intValue()); } @Test public void testFailedExecutionForAbsoluteURI() { IClientConfig config = DefaultClientConfigImpl .getClientConfigWithDefaultValues() .withProperty(CommonClientConfigKey.ConnectTimeout, "100") .withProperty(CommonClientConfigKey.MaxAutoRetries, 1) .withProperty(CommonClientConfigKey.MaxAutoRetriesNextServer, 1); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("http://xyz.unknowhost.xyz/testAsync/person"); Server badServer = new Server("localhost:12345"); Server badServer2 = new Server("localhost:34567"); List<Server> servers = Lists.newArrayList(badServer, badServer2); BaseLoadBalancer lb = LoadBalancerBuilder.<Server>newBuilder() .withRule(new AvailabilityFilteringRule()) .withPing(new DummyPing()) .buildFixedServerListLoadBalancer(servers); IClientConfig overrideConfig = DefaultClientConfigImpl.getEmptyConfig(); TestExecutionListener<ByteBuf, ByteBuf> listener = new TestExecutionListener<ByteBuf, ByteBuf>(request, overrideConfig); List<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>> listeners = Lists.<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>>newArrayList(listener); LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(config), listeners); try { client.submit(request, null, overrideConfig).toBlocking().last(); fail("Exception expected"); } catch(Exception e) { assertNotNull(e); } assertEquals(1, listener.executionStartCounter.get()); assertEquals(2, listener.startWithServerCounter.get()); assertEquals(2, listener.exceptionWithServerCounter.get()); assertEquals(1, listener.executionFailedCounter.get()); assertTrue(listener.isContextChecked()); assertTrue(listener.isCheckExecutionInfo()); assertTrue(listener.getFinalThrowable() instanceof ClientException); } @Test public void testSuccessExecution() throws IOException { MockWebServer server = new MockWebServer(); String content = "OK"; server.enqueue(new MockResponse() .setResponseCode(200) .setHeader("Content-type", "application/json") .setBody(content)); server.play(); IClientConfig config = DefaultClientConfigImpl .getClientConfigWithDefaultValues() .withProperty(CommonClientConfigKey.ConnectTimeout, "2000") .withProperty(CommonClientConfigKey.MaxAutoRetries, 1) .withProperty(CommonClientConfigKey.MaxAutoRetriesNextServer, 1); System.out.println(config); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/person"); Server badServer = new Server("localhost:12345"); Server goodServer = new Server("localhost:" + server.getPort()); List<Server> servers = Lists.newArrayList(goodServer, badServer); BaseLoadBalancer lb = LoadBalancerBuilder.newBuilder() .withRule(new AvailabilityFilteringRule()) .withPing(new DummyPing()) .buildFixedServerListLoadBalancer(servers); IClientConfig overrideConfig = DefaultClientConfigImpl .getEmptyConfig() .set(CommonClientConfigKey.ConnectTimeout, 500); TestExecutionListener<ByteBuf, ByteBuf> listener = new TestExecutionListener<>(request, overrideConfig); List<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>> listeners = Lists.newArrayList(listener); LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(config), listeners); HttpClientResponse<ByteBuf> response = client.submit(request, null, overrideConfig).toBlocking().last(); System.out.println(listener); assertEquals(200, response.getStatus().code()); assertEquals(1, listener.executionStartCounter.get()); assertEquals(3, listener.startWithServerCounter.get()); assertEquals(2, listener.exceptionWithServerCounter.get()); assertEquals(0, listener.executionFailedCounter.get()); assertEquals(1, listener.executionSuccessCounter.get()); assertEquals(500, listener.getContext().getClientProperty(CommonClientConfigKey.ConnectTimeout).intValue()); assertTrue(listener.isContextChecked()); assertTrue(listener.isCheckExecutionInfo()); assertSame(response, listener.getResponse()); } @Test public void testSuccessExecutionOnAbosoluteURI() throws IOException { MockWebServer server = new MockWebServer(); String content = "OK"; server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-type", "application/json") .setBody(content)); server.play(); IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues().withProperty(CommonClientConfigKey.ConnectTimeout, "2000") .withProperty(CommonClientConfigKey.MaxAutoRetries, 1) .withProperty(CommonClientConfigKey.MaxAutoRetriesNextServer, 1); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("http://localhost:" + server.getPort() + "/testAsync/person"); Server badServer = new Server("localhost:12345"); Server goodServer = new Server("localhost:" + server.getPort()); List<Server> servers = Lists.newArrayList(goodServer, badServer); BaseLoadBalancer lb = LoadBalancerBuilder.<Server>newBuilder() .withRule(new AvailabilityFilteringRule()) .withPing(new DummyPing()) .buildFixedServerListLoadBalancer(servers); IClientConfig overrideConfig = DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.ConnectTimeout, 500); TestExecutionListener<ByteBuf, ByteBuf> listener = new TestExecutionListener<ByteBuf, ByteBuf>(request, overrideConfig); List<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>> listeners = Lists.<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>>newArrayList(listener); LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(config), listeners); HttpClientResponse<ByteBuf> response = client.submit(request, null, overrideConfig).toBlocking().last(); assertEquals(200, response.getStatus().code()); assertEquals(1, listener.executionStartCounter.get()); assertEquals(1, listener.startWithServerCounter.get()); assertEquals(0, listener.exceptionWithServerCounter.get()); assertEquals(0, listener.executionFailedCounter.get()); assertEquals(1, listener.executionSuccessCounter.get()); assertEquals(500, listener.getContext().getClientProperty(CommonClientConfigKey.ConnectTimeout).intValue()); assertTrue(listener.isContextChecked()); assertTrue(listener.isCheckExecutionInfo()); assertSame(response, listener.getResponse()); } @Test public void testAbortedExecution() { IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues().withProperty(CommonClientConfigKey.ConnectTimeout, "100") .withProperty(CommonClientConfigKey.MaxAutoRetries, 1) .withProperty(CommonClientConfigKey.MaxAutoRetriesNextServer, 1); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/person"); Server badServer = new Server("localhost:12345"); Server badServer2 = new Server("localhost:34567"); List<Server> servers = Lists.newArrayList(badServer, badServer2); BaseLoadBalancer lb = LoadBalancerBuilder.<Server>newBuilder() .withRule(new AvailabilityFilteringRule()) .withPing(new DummyPing()) .buildFixedServerListLoadBalancer(servers); IClientConfig overrideConfig = DefaultClientConfigImpl.getEmptyConfig(); TestExecutionListener listener = new TestExecutionListener(request, overrideConfig) { @Override public void onExecutionStart(ExecutionContext context) { throw new AbortExecutionException("exit now"); } }; List<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>> listeners = Lists.<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>>newArrayList(listener); LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(config), listeners); final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> ref = new AtomicReference<Throwable>(); client.submit(request, null, overrideConfig).subscribe(new Action1<HttpClientResponse<ByteBuf>>() { @Override public void call(HttpClientResponse<ByteBuf> byteBufHttpClientResponse) { } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { ref.set(throwable); latch.countDown(); } }); try { latch.await(500, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } assertTrue(ref.get() instanceof AbortExecutionException); } @Test public void testAbortedExecutionOnServer() { IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues().withProperty(CommonClientConfigKey.ConnectTimeout, "100") .withProperty(CommonClientConfigKey.MaxAutoRetries, 1) .withProperty(CommonClientConfigKey.MaxAutoRetriesNextServer, 1); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/person"); Server badServer = new Server("localhost:12345"); Server badServer2 = new Server("localhost:34567"); List<Server> servers = Lists.newArrayList(badServer, badServer2); BaseLoadBalancer lb = LoadBalancerBuilder.<Server>newBuilder() .withRule(new AvailabilityFilteringRule()) .withPing(new DummyPing()) .buildFixedServerListLoadBalancer(servers); IClientConfig overrideConfig = DefaultClientConfigImpl.getEmptyConfig(); TestExecutionListener listener = new TestExecutionListener(request, overrideConfig) { @Override public void onStartWithServer(ExecutionContext context, ExecutionInfo info) { throw new AbortExecutionException("exit now"); } }; List<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>> listeners = Lists.<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>>newArrayList(listener); LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(config), listeners); final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> ref = new AtomicReference<Throwable>(); client.submit(request, null, overrideConfig).subscribe(new Action1<HttpClientResponse<ByteBuf>>() { @Override public void call(HttpClientResponse<ByteBuf> byteBufHttpClientResponse) { } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { ref.set(throwable); latch.countDown(); } }); try { latch.await(500, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } assertTrue(ref.get() instanceof AbortExecutionException); } @Test public void testDisabledListener() throws Exception { IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues("myClient").withProperty(CommonClientConfigKey.ConnectTimeout, "2000") .withProperty(CommonClientConfigKey.MaxAutoRetries, 1) .withProperty(CommonClientConfigKey.MaxAutoRetriesNextServer, 1); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/person"); Server badServer = new Server("localhost:12345"); List<Server> servers = Lists.newArrayList(badServer); BaseLoadBalancer lb = LoadBalancerBuilder.<Server>newBuilder() .withRule(new AvailabilityFilteringRule()) .withPing(new DummyPing()) .buildFixedServerListLoadBalancer(servers); IClientConfig overrideConfig = DefaultClientConfigImpl.getEmptyConfig().set(CommonClientConfigKey.ConnectTimeout, 500); TestExecutionListener<ByteBuf, ByteBuf> listener = new TestExecutionListener<ByteBuf, ByteBuf>(request, overrideConfig); List<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>> listeners = Lists.<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>>newArrayList(listener); LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(config), listeners); ConfigurationManager.getConfigInstance().setProperty("ribbon.listener." + TestExecutionListener.class.getName() + ".disabled", "true"); try { client.submit(request, null, overrideConfig).toBlocking().last(); } catch (Exception e) { assertNotNull(e); } assertEquals(0, listener.executionStartCounter.get()); assertEquals(0, listener.startWithServerCounter.get()); assertEquals(0, listener.exceptionWithServerCounter.get()); assertEquals(0, listener.executionFailedCounter.get()); assertEquals(0, listener.executionSuccessCounter.get()); try { client.submit(request, null, overrideConfig).toBlocking().last(); } catch (Exception e) { assertNotNull(e); } assertEquals(0, listener.executionStartCounter.get()); assertEquals(0, listener.startWithServerCounter.get()); assertEquals(0, listener.exceptionWithServerCounter.get()); assertEquals(0, listener.executionFailedCounter.get()); assertEquals(0, listener.executionSuccessCounter.get()); } }
7,073
0
Create_ds/ribbon/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty
Create_ds/ribbon/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty/http/ServerListRefreshTest.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.ribbon.transport.netty.http; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.mockwebserver.MockResponse; import com.google.mockwebserver.MockWebServer; import com.netflix.ribbon.transport.netty.RibbonTransport; import com.netflix.loadbalancer.BaseLoadBalancer; import com.netflix.loadbalancer.Server; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import org.junit.Test; import java.io.IOException; import java.util.List; import java.util.Set; import static org.junit.Assert.assertEquals; /** * Created by awang on 8/4/14. */ public class ServerListRefreshTest { /** * This test ensures that when server list is refreshed in the load balancer, the set of servers * which equals to (oldList - newList) should be removed from the map of cached RxClient. Any server * that is not part of oldList should stay in the map. * * @throws IOException */ @Test public void testServerListRefresh() throws IOException { String content = "Hello world"; MockWebServer server1 = new MockWebServer(); MockWebServer server2 = new MockWebServer(); MockWebServer server3 = new MockWebServer(); MockResponse mockResponse = new MockResponse().setResponseCode(200).setHeader("Content-type", "text/plain") .setBody(content); server1.enqueue(mockResponse); server2.enqueue(mockResponse); server3.enqueue(mockResponse); server1.play(); server2.play(); server3.play(); try { BaseLoadBalancer lb = new BaseLoadBalancer(); List<Server> initialList = Lists.newArrayList(new Server("localhost", server1.getPort()), new Server("localhost", server2.getPort())); lb.setServersList(initialList); LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(lb); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/"); client.submit(request).toBlocking().last(); client.submit(request).toBlocking().last(); HttpClientRequest<ByteBuf> request2 = HttpClientRequest.createGet("http://localhost:" + server3.getPort()); client.submit(request2).toBlocking().last(); Set<Server> cachedServers = client.getRxClients().keySet(); assertEquals(Sets.newHashSet(new Server("localhost", server1.getPort()), new Server("localhost", server2.getPort()), new Server("localhost", server3.getPort())), cachedServers); List<Server> newList = Lists.newArrayList(new Server("localhost", server1.getPort()), new Server("localhost", 99999)); lb.setServersList(newList); cachedServers = client.getRxClients().keySet(); assertEquals(Sets.newHashSet(new Server("localhost", server1.getPort()), new Server("localhost", server3.getPort())), cachedServers); } finally { server1.shutdown(); server2.shutdown(); server3.shutdown(); } } }
7,074
0
Create_ds/ribbon/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty
Create_ds/ribbon/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty/http/DiscoveryLoadBalancerTest.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.ribbon.transport.netty.http; import com.google.common.collect.Lists; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import com.netflix.ribbon.transport.netty.RibbonTransport; import com.netflix.loadbalancer.LoadBalancerContext; import com.netflix.loadbalancer.Server; import com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList; import com.netflix.ribbon.testutils.MockedDiscoveryServerListTest; import io.netty.buffer.ByteBuf; import org.junit.Test; import org.powermock.core.classloader.annotations.PowerMockIgnore; import java.util.List; import static org.junit.Assert.assertEquals; @PowerMockIgnore("com.google.*") public class DiscoveryLoadBalancerTest extends MockedDiscoveryServerListTest { @Override protected List<Server> getMockServerList() { return Lists.newArrayList(new Server("www.example1.com", 80), new Server("www.example2.com", 80)); } @Override protected String getVipAddress() { return "myvip"; } @Test public void testLoadBalancer() { IClientConfig config = IClientConfig.Builder.newBuilder().withDefaultValues() .withDeploymentContextBasedVipAddresses(getVipAddress()).build() .set(IClientConfigKey.Keys.NIWSServerListClassName, DiscoveryEnabledNIWSServerList.class.getName()); LoadBalancingHttpClient<ByteBuf, ByteBuf> client = RibbonTransport.newHttpClient(config); LoadBalancerContext lbContext = client.getLoadBalancerContext(); List<Server> serverList = lbContext.getLoadBalancer().getAllServers(); assertEquals(getMockServerList(), serverList); } }
7,075
0
Create_ds/ribbon/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty
Create_ds/ribbon/ribbon-transport/src/test/java/com/netflix/ribbon/transport/netty/http/TestExecutionListener.java
package com.netflix.ribbon.transport.netty.http; import com.netflix.loadbalancer.reactive.ExecutionContext; import com.netflix.loadbalancer.reactive.ExecutionInfo; import com.netflix.loadbalancer.reactive.ExecutionListener; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.Server; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; /** * @author Allen Wang */ public class TestExecutionListener<I, O> implements ExecutionListener<HttpClientRequest<I>, HttpClientResponse<O>> { public AtomicInteger executionStartCounter = new AtomicInteger(0); public AtomicInteger startWithServerCounter = new AtomicInteger(0); public AtomicInteger exceptionWithServerCounter = new AtomicInteger(0); public AtomicInteger executionFailedCounter = new AtomicInteger(0); public AtomicInteger executionSuccessCounter = new AtomicInteger(0); private HttpClientRequest<ByteBuf> expectedRequest; private IClientConfig requestConfig; private volatile boolean checkContext = true; private volatile boolean checkExecutionInfo = true; private volatile Throwable finalThrowable; private HttpClientResponse<O> response; private List<Throwable> errors = new CopyOnWriteArrayList<Throwable>(); private AtomicInteger numAttemptsOnServer = new AtomicInteger(); private AtomicInteger numServers = new AtomicInteger(); private volatile Server lastServer; private static final Integer MY_OBJECT = Integer.valueOf(9); private volatile ExecutionContext<HttpClientRequest<I>> context; public TestExecutionListener(HttpClientRequest<ByteBuf> expectedRequest, IClientConfig requestConfig) { this.expectedRequest = expectedRequest; this.requestConfig = requestConfig; } private void checkContext(ExecutionContext<HttpClientRequest<I>> context) { try { assertSame(requestConfig, context.getRequestConfig()); assertSame(expectedRequest, context.getRequest()); assertEquals(MY_OBJECT, context.get("MyObject")); if (this.context == null) { this.context = context; } else { assertSame(this.context, context); } } catch (Throwable e) { e.printStackTrace(); checkContext = false; } } private void checkExecutionInfo(ExecutionInfo info) { try { assertEquals(numAttemptsOnServer.get(), info.getNumberOfPastAttemptsOnServer()); assertEquals(numServers.get(), info.getNumberOfPastServersAttempted()); } catch (Throwable e) { e.printStackTrace(); checkExecutionInfo = false; } } @Override public void onExecutionStart(ExecutionContext<HttpClientRequest<I>> context) { context.put("MyObject", MY_OBJECT); checkContext(context); executionStartCounter.incrementAndGet(); } @Override public void onStartWithServer(ExecutionContext<HttpClientRequest<I>> context, ExecutionInfo info) { checkContext(context); if (lastServer == null) { lastServer = info.getServer(); } else if (!lastServer.equals(info.getServer())) { lastServer = info.getServer(); numAttemptsOnServer.set(0); numServers.incrementAndGet(); } checkExecutionInfo(info); startWithServerCounter.incrementAndGet(); } @Override public void onExceptionWithServer(ExecutionContext<HttpClientRequest<I>> context, Throwable exception, ExecutionInfo info) { checkContext(context); checkExecutionInfo(info); numAttemptsOnServer.incrementAndGet(); errors.add(exception); exceptionWithServerCounter.incrementAndGet(); } @Override public void onExecutionSuccess(ExecutionContext<HttpClientRequest<I>> context, HttpClientResponse<O> response, ExecutionInfo info) { checkContext(context); checkExecutionInfo(info); this.response = response; executionSuccessCounter.incrementAndGet(); } @Override public void onExecutionFailed(ExecutionContext<HttpClientRequest<I>> context, Throwable finalException, ExecutionInfo info) { checkContext(context); checkExecutionInfo(info); executionFailedCounter.incrementAndGet(); finalThrowable = finalException; } public boolean isContextChecked() { return checkContext; } public boolean isCheckExecutionInfo() { return checkExecutionInfo; } public Throwable getFinalThrowable() { return finalThrowable; } public HttpClientResponse<O> getResponse() { return response; } public ExecutionContext<HttpClientRequest<I>> getContext() { return this.context; } @Override public String toString() { return "TestExecutionListener{" + "executionStartCounter=" + executionStartCounter + ", startWithServerCounter=" + startWithServerCounter + ", exceptionWithServerCounter=" + exceptionWithServerCounter + ", executionFailedCounter=" + executionFailedCounter + ", executionSuccessCounter=" + executionSuccessCounter + ", expectedRequest=" + expectedRequest + ", requestConfig=" + requestConfig + ", checkContext=" + checkContext + ", checkExecutionInfo=" + checkExecutionInfo + ", finalThrowable=" + finalThrowable + ", response=" + response + ", errors=" + errors + ", numAttemptsOnServer=" + numAttemptsOnServer + ", numServers=" + numServers + ", lastServer=" + lastServer + ", context=" + context + '}'; } }
7,076
0
Create_ds/ribbon/ribbon-transport/src/test/java/com/netflix/client/netty
Create_ds/ribbon/ribbon-transport/src/test/java/com/netflix/client/netty/udp/HelloUdpServerExternalResource.java
package com.netflix.client.netty.udp; import io.netty.buffer.ByteBuf; import io.netty.channel.socket.DatagramPacket; import io.reactivex.netty.RxNetty; import io.reactivex.netty.channel.ConnectionHandler; import io.reactivex.netty.channel.ObservableConnection; import io.reactivex.netty.protocol.udp.server.UdpServer; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketException; import java.nio.charset.Charset; import java.util.concurrent.TimeUnit; import org.junit.rules.ExternalResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.functions.Func1; public class HelloUdpServerExternalResource extends ExternalResource { private static final Logger LOG = LoggerFactory.getLogger(HelloUdpServerExternalResource.class); static final String WELCOME_MSG = "Welcome to the broadcast world!"; static final byte[] WELCOME_MSG_BYTES = WELCOME_MSG.getBytes(Charset.defaultCharset()); private UdpServer<DatagramPacket, DatagramPacket> server; private int timeout = 0; public HelloUdpServerExternalResource() { } private int choosePort() throws SocketException { DatagramSocket serverSocket = new DatagramSocket(); int port = serverSocket.getLocalPort(); serverSocket.close(); return port; } public void setTimeout(int timeout) { this.timeout = timeout; } public void start() { int port; try { port = choosePort(); } catch (SocketException e) { throw new RuntimeException("Error choosing point", e); } server = RxNetty.createUdpServer(port, new ConnectionHandler<DatagramPacket, DatagramPacket>() { @Override public Observable<Void> handle(final ObservableConnection<DatagramPacket, DatagramPacket> newConnection) { return newConnection.getInput().flatMap(new Func1<DatagramPacket, Observable<Void>>() { @Override public Observable<Void> call(final DatagramPacket received) { return Observable.interval(timeout, TimeUnit.MILLISECONDS).take(1).flatMap(new Func1<Long, Observable<Void>>() { @Override public Observable<Void> call(Long aLong) { InetSocketAddress sender = received.sender(); LOG.info("Received datagram. Sender: " + sender); ByteBuf data = newConnection.getChannel().alloc().buffer(WELCOME_MSG_BYTES.length); data.writeBytes(WELCOME_MSG_BYTES); return newConnection.writeAndFlush(new DatagramPacket(data, sender)); } }); } }); } }); server.start(); LOG.info("UDP hello server started at port: " + port); } /** * Override to tear down your specific external resource. */ protected void after() { if (server != null) { try { server.shutdown(); } catch (InterruptedException e) { LOG.error("Failed to shut down server", e); } } } public int getServerPort() { return server.getServerPort(); } }
7,077
0
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/RibbonTransportFactory.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.ribbon; import com.netflix.client.config.ClientConfigFactory; import com.netflix.client.config.IClientConfig; import com.netflix.ribbon.transport.netty.RibbonTransport; import io.netty.buffer.ByteBuf; import io.netty.channel.socket.DatagramPacket; import io.reactivex.netty.client.RxClient; import io.reactivex.netty.protocol.http.client.HttpClient; import javax.inject.Inject; /** * A dependency injection friendly Ribbon transport client factory that can create clients based on IClientConfig or * a name which is used to construct the necessary IClientConfig. * * Created by awang on 7/18/14. */ public abstract class RibbonTransportFactory { protected final ClientConfigFactory clientConfigFactory; public static class DefaultRibbonTransportFactory extends RibbonTransportFactory { @Inject public DefaultRibbonTransportFactory(ClientConfigFactory clientConfigFactory) { super(clientConfigFactory); } } protected RibbonTransportFactory(ClientConfigFactory clientConfigFactory) { this.clientConfigFactory = clientConfigFactory; } public static final RibbonTransportFactory DEFAULT = new DefaultRibbonTransportFactory(ClientConfigFactory.DEFAULT); public HttpClient<ByteBuf, ByteBuf> newHttpClient(IClientConfig config) { return RibbonTransport.newHttpClient(config); } public RxClient<ByteBuf, ByteBuf> newTcpClient(IClientConfig config) { return RibbonTransport.newTcpClient(config); } public RxClient<DatagramPacket, DatagramPacket> newUdpClient(IClientConfig config) { return RibbonTransport.newUdpClient(config); } public final HttpClient<ByteBuf, ByteBuf> newHttpClient(String name) { IClientConfig config = clientConfigFactory.newConfig(); config.loadProperties(name); return newHttpClient(config); } public final RxClient<ByteBuf, ByteBuf> newTcpClient(String name) { IClientConfig config = clientConfigFactory.newConfig(); config.loadProperties(name); return newTcpClient(config); } public RxClient<DatagramPacket, DatagramPacket> newUdpClient(String name) { IClientConfig config = clientConfigFactory.newConfig(); config.loadProperties(name); return newUdpClient(config); } }
7,078
0
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/LoadBalancingRxClient.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.ribbon.transport.netty; import io.reactivex.netty.channel.ObservableConnection; import io.reactivex.netty.client.ClientMetricsEvent; import io.reactivex.netty.client.RxClient; import io.reactivex.netty.metrics.MetricEventsListener; import io.reactivex.netty.metrics.MetricEventsSubject; import io.reactivex.netty.pipeline.PipelineConfigurator; import java.net.URL; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Subscription; import com.netflix.client.RetryHandler; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import com.netflix.client.ssl.AbstractSslContextFactory; import com.netflix.client.ssl.ClientSslSocketFactoryException; import com.netflix.client.ssl.URLSslContextFactory; import com.netflix.client.util.Resources; import com.netflix.loadbalancer.BaseLoadBalancer; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.LoadBalancerBuilder; import com.netflix.loadbalancer.LoadBalancerContext; import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.ServerListChangeListener; import com.netflix.loadbalancer.reactive.LoadBalancerCommand; import com.netflix.loadbalancer.reactive.ServerOperation; /** * Decorator for RxClient which adds load balancing functionality. This implementation uses * an ILoadBlanacer and caches the mapping from Server to a client implementation * * @author elandau * * @param <I> Client input type * @param <O> Client output type * @param <T> Specific RxClient derived type */ public abstract class LoadBalancingRxClient<I, O, T extends RxClient<I, O>> implements RxClient<I, O> { private static final Logger logger = LoggerFactory.getLogger(LoadBalancingRxClient.class); protected final ConcurrentMap<Server, T> rxClientCache; protected final PipelineConfigurator<O, I> pipelineConfigurator; protected final IClientConfig clientConfig; protected final RetryHandler defaultRetryHandler; protected final AbstractSslContextFactory sslContextFactory; protected final MetricEventsListener<? extends ClientMetricsEvent<?>> listener; protected final MetricEventsSubject<ClientMetricsEvent<?>> eventSubject; protected final LoadBalancerContext lbContext; public LoadBalancingRxClient(IClientConfig config, RetryHandler defaultRetryHandler, PipelineConfigurator<O, I> pipelineConfigurator) { this(LoadBalancerBuilder.newBuilder().withClientConfig(config).buildLoadBalancerFromConfigWithReflection(), config, defaultRetryHandler, pipelineConfigurator ); } public LoadBalancingRxClient(ILoadBalancer lb, IClientConfig config, RetryHandler defaultRetryHandler, PipelineConfigurator<O, I> pipelineConfigurator) { this.rxClientCache = new ConcurrentHashMap<Server, T>(); this.lbContext = new LoadBalancerContext(lb, config, defaultRetryHandler); this.defaultRetryHandler = defaultRetryHandler; this.pipelineConfigurator = pipelineConfigurator; this.clientConfig = config; this.listener = createListener(config.getClientName()); eventSubject = new MetricEventsSubject<ClientMetricsEvent<?>>(); boolean isSecure = getProperty(IClientConfigKey.Keys.IsSecure, null, false); if (isSecure) { final URL trustStoreUrl = getResourceForOptionalProperty(CommonClientConfigKey.TrustStore); final URL keyStoreUrl = getResourceForOptionalProperty(CommonClientConfigKey.KeyStore); boolean isClientAuthRequired = clientConfig.get(IClientConfigKey.Keys.IsClientAuthRequired, false); if ( // if client auth is required, need both a truststore and a keystore to warrant configuring // if client is not is not required, we only need a keystore OR a truststore to warrant configuring (isClientAuthRequired && (trustStoreUrl != null && keyStoreUrl != null)) || (!isClientAuthRequired && (trustStoreUrl != null || keyStoreUrl != null)) ) { try { sslContextFactory = new URLSslContextFactory(trustStoreUrl, clientConfig.get(CommonClientConfigKey.TrustStorePassword), keyStoreUrl, clientConfig.get(CommonClientConfigKey.KeyStorePassword)); } catch (ClientSslSocketFactoryException e) { throw new IllegalArgumentException("Unable to configure custom secure socket factory", e); } } else { sslContextFactory = null; } } else { sslContextFactory = null; } addLoadBalancerListener(); } public IClientConfig getClientConfig() { return clientConfig; } public int getResponseTimeOut() { int maxRetryNextServer = 0; int maxRetrySameServer = 0; if (defaultRetryHandler != null) { maxRetryNextServer = defaultRetryHandler.getMaxRetriesOnNextServer(); maxRetrySameServer = defaultRetryHandler.getMaxRetriesOnSameServer(); } else { maxRetryNextServer = clientConfig.get(IClientConfigKey.Keys.MaxAutoRetriesNextServer, DefaultClientConfigImpl.DEFAULT_MAX_AUTO_RETRIES_NEXT_SERVER); maxRetrySameServer = clientConfig.get(IClientConfigKey.Keys.MaxAutoRetries, DefaultClientConfigImpl.DEFAULT_MAX_AUTO_RETRIES); } int readTimeout = getProperty(IClientConfigKey.Keys.ReadTimeout, null, DefaultClientConfigImpl.DEFAULT_READ_TIMEOUT); int connectTimeout = getProperty(IClientConfigKey.Keys.ConnectTimeout, null, DefaultClientConfigImpl.DEFAULT_CONNECT_TIMEOUT); return (maxRetryNextServer + 1) * (maxRetrySameServer + 1) * (readTimeout + connectTimeout); } public int getMaxConcurrentRequests() { return -1; } /** * Resolve the final property value from, * 1. Request specific configuration * 2. Default configuration * 3. Default value * * @param key * @param requestConfig * @param defaultValue * @return */ protected <S> S getProperty(IClientConfigKey<S> key, @Nullable IClientConfig requestConfig, S defaultValue) { if (requestConfig != null && requestConfig.get(key) != null) { return requestConfig.get(key); } else { return clientConfig.get(key, defaultValue); } } protected URL getResourceForOptionalProperty(final IClientConfigKey<String> configKey) { final String propValue = clientConfig.get(configKey); URL result = null; if (propValue != null) { result = Resources.getResource(propValue); if (result == null) { throw new IllegalArgumentException("No resource found for " + configKey + ": " + propValue); } } return result; } /** * Add a listener that is responsible for removing an HttpClient and shutting down * its connection pool if it is no longer available from load balancer. */ private void addLoadBalancerListener() { if (!(lbContext.getLoadBalancer() instanceof BaseLoadBalancer)) { return; } ((BaseLoadBalancer) lbContext.getLoadBalancer()).addServerListChangeListener(new ServerListChangeListener() { @Override public void serverListChanged(List<Server> oldList, List<Server> newList) { Set<Server> removedServers = new HashSet<Server>(oldList); removedServers.removeAll(newList); for (Server server: rxClientCache.keySet()) { if (removedServers.contains(server)) { // this server is no longer in UP status removeClient(server); } } } }); } /** * Create a client instance for this Server. Note that only the client object is created * here but that the client connection is not created yet. * * @param server * @return */ protected abstract T createRxClient(Server server); /** * Look up the client associated with this Server. * @param server * @return */ protected T getOrCreateRxClient(Server server) { T client = rxClientCache.get(server); if (client != null) { return client; } else { client = createRxClient(server); client.subscribe(listener); client.subscribe(eventSubject); T old = rxClientCache.putIfAbsent(server, client); if (old != null) { return old; } else { return client; } } } /** * Remove the client for this Server * @param server * @return The RxClient implementation or null if not found */ protected T removeClient(Server server) { T client = rxClientCache.remove(server); if (client != null) { client.shutdown(); } return client; } @Override public Observable<ObservableConnection<O, I>> connect() { return LoadBalancerCommand.<ObservableConnection<O, I>>builder() .withLoadBalancerContext(lbContext) .build() .submit(new ServerOperation<ObservableConnection<O, I>>() { @Override public Observable<ObservableConnection<O, I>> call(Server server) { return getOrCreateRxClient(server).connect(); } }); } protected abstract MetricEventsListener<? extends ClientMetricsEvent<?>> createListener(String name); @Override public void shutdown() { for (Server server: rxClientCache.keySet()) { removeClient(server); } } @Override public String name() { return clientConfig.getClientName(); } @Override public Subscription subscribe(MetricEventsListener<? extends ClientMetricsEvent<?>> listener) { return eventSubject.subscribe(listener); } public final LoadBalancerContext getLoadBalancerContext() { return lbContext; } }
7,079
0
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/LoadBalancingRxClientWithPoolOptions.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.ribbon.transport.netty; import io.reactivex.netty.client.CompositePoolLimitDeterminationStrategy; import io.reactivex.netty.client.MaxConnectionsBasedStrategy; import io.reactivex.netty.client.PoolLimitDeterminationStrategy; import io.reactivex.netty.client.RxClient; import io.reactivex.netty.pipeline.PipelineConfigurator; import java.util.concurrent.ScheduledExecutorService; import com.netflix.client.RetryHandler; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import com.netflix.client.config.IClientConfigKey.Keys; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.LoadBalancerBuilder; public abstract class LoadBalancingRxClientWithPoolOptions<I, O, T extends RxClient<I, O>> extends LoadBalancingRxClient<I, O, T>{ protected CompositePoolLimitDeterminationStrategy poolStrategy; protected MaxConnectionsBasedStrategy globalStrategy; protected int idleConnectionEvictionMills; protected ScheduledExecutorService poolCleanerScheduler; protected boolean poolEnabled = true; public LoadBalancingRxClientWithPoolOptions(IClientConfig config, RetryHandler retryHandler, PipelineConfigurator<O, I> pipelineConfigurator, ScheduledExecutorService poolCleanerScheduler) { this(LoadBalancerBuilder.newBuilder().withClientConfig(config).buildDynamicServerListLoadBalancer(), config, retryHandler, pipelineConfigurator, poolCleanerScheduler); } public LoadBalancingRxClientWithPoolOptions(ILoadBalancer lb, IClientConfig config, RetryHandler retryHandler, PipelineConfigurator<O, I> pipelineConfigurator, ScheduledExecutorService poolCleanerScheduler) { super(lb, config, retryHandler, pipelineConfigurator); poolEnabled = config.get(CommonClientConfigKey.EnableConnectionPool, DefaultClientConfigImpl.DEFAULT_ENABLE_CONNECTION_POOL); if (poolEnabled) { this.poolCleanerScheduler = poolCleanerScheduler; int maxTotalConnections = config.get(IClientConfigKey.Keys.MaxTotalConnections, DefaultClientConfigImpl.DEFAULT_MAX_TOTAL_CONNECTIONS); int maxConnections = config.get(Keys.MaxConnectionsPerHost, DefaultClientConfigImpl.DEFAULT_MAX_CONNECTIONS_PER_HOST); MaxConnectionsBasedStrategy perHostStrategy = new DynamicPropertyBasedPoolStrategy(maxConnections, config.getClientName() + "." + config.getNameSpace() + "." + CommonClientConfigKey.MaxConnectionsPerHost); globalStrategy = new DynamicPropertyBasedPoolStrategy(maxTotalConnections, config.getClientName() + "." + config.getNameSpace() + "." + CommonClientConfigKey.MaxTotalConnections); poolStrategy = new CompositePoolLimitDeterminationStrategy(perHostStrategy, globalStrategy); idleConnectionEvictionMills = config.get(Keys.ConnIdleEvictTimeMilliSeconds, DefaultClientConfigImpl.DEFAULT_CONNECTIONIDLE_TIME_IN_MSECS); } } protected final PoolLimitDeterminationStrategy getPoolStrategy() { return globalStrategy; } protected int getConnectionIdleTimeoutMillis() { return idleConnectionEvictionMills; } protected boolean isPoolEnabled() { return poolEnabled; } @Override public int getMaxConcurrentRequests() { if (poolEnabled) { return globalStrategy.getMaxConnections(); } return super.getMaxConcurrentRequests(); } }
7,080
0
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/DynamicPropertyBasedPoolStrategy.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.ribbon.transport.netty; import com.netflix.config.DynamicProperty; import io.reactivex.netty.client.MaxConnectionsBasedStrategy; /** * A {@link MaxConnectionsBasedStrategy} that resize itself based on callbacks from * {@link DynamicProperty} * * @author awang * */ public class DynamicPropertyBasedPoolStrategy extends MaxConnectionsBasedStrategy { private final DynamicProperty poolSizeProperty; public DynamicPropertyBasedPoolStrategy(final int maxConnections, String propertyName) { super(maxConnections); poolSizeProperty = DynamicProperty.getInstance(propertyName); setMaxConnections(poolSizeProperty.getInteger(maxConnections)); poolSizeProperty.addCallback(new Runnable() { @Override public void run() { setMaxConnections(poolSizeProperty.getInteger(maxConnections)); }; }); } protected void setMaxConnections(int max) { int diff = max - getMaxConnections(); incrementMaxConnections(diff); } }
7,081
0
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/RibbonTransport.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.ribbon.transport.netty; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.netflix.client.DefaultLoadBalancerRetryHandler; import com.netflix.loadbalancer.reactive.ExecutionListener; import com.netflix.client.RetryHandler; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfig; import com.netflix.ribbon.transport.netty.http.LoadBalancingHttpClient; import com.netflix.ribbon.transport.netty.http.NettyHttpLoadBalancerErrorHandler; import com.netflix.ribbon.transport.netty.http.SSEClient; import com.netflix.ribbon.transport.netty.tcp.LoadBalancingTcpClient; import com.netflix.ribbon.transport.netty.udp.LoadBalancingUdpClient; import com.netflix.config.DynamicIntProperty; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.utils.ScheduledThreadPoolExectuorWithDynamicSize; import io.netty.buffer.ByteBuf; import io.netty.channel.socket.DatagramPacket; import io.reactivex.netty.client.RxClient; import io.reactivex.netty.pipeline.PipelineConfigurator; import io.reactivex.netty.pipeline.PipelineConfigurators; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import io.reactivex.netty.protocol.text.sse.ServerSentEvent; import java.util.List; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; public final class RibbonTransport { public static final PipelineConfigurator<HttpClientResponse<ServerSentEvent>, HttpClientRequest<ByteBuf>> DEFAULT_SSE_PIPELINE_CONFIGURATOR = PipelineConfigurators.sseClientConfigurator(); public static final PipelineConfigurator<HttpClientResponse<ByteBuf>, HttpClientRequest<ByteBuf>> DEFAULT_HTTP_PIPELINE_CONFIGURATOR = PipelineConfigurators.httpClientConfigurator(); public static final DynamicIntProperty POOL_CLEANER_CORE_SIZE = new DynamicIntProperty("rxNetty.poolCleaner.coreSize", 2); public static final ScheduledExecutorService poolCleanerScheduler; static { ThreadFactory factory = (new ThreadFactoryBuilder()).setDaemon(true) .setNameFormat("RxClient_Connection_Pool_Clean_Up") .build(); poolCleanerScheduler = new ScheduledThreadPoolExectuorWithDynamicSize(POOL_CLEANER_CORE_SIZE, factory); } private RibbonTransport() { } private static RetryHandler getDefaultHttpRetryHandlerWithConfig(IClientConfig config) { return new NettyHttpLoadBalancerErrorHandler(config); } private static RetryHandler getDefaultRetryHandlerWithConfig(IClientConfig config) { return new DefaultLoadBalancerRetryHandler(config); } public static RxClient<ByteBuf, ByteBuf> newTcpClient(ILoadBalancer loadBalancer, IClientConfig config) { return new LoadBalancingTcpClient<ByteBuf, ByteBuf>(loadBalancer, config, getDefaultRetryHandlerWithConfig(config), null, poolCleanerScheduler); } public static <I, O> RxClient<I, O> newTcpClient(ILoadBalancer loadBalancer, PipelineConfigurator<O, I> pipelineConfigurator, IClientConfig config, RetryHandler retryHandler) { return new LoadBalancingTcpClient<I, O>(loadBalancer, config, retryHandler, pipelineConfigurator, poolCleanerScheduler); } public static <I, O> RxClient<I, O> newTcpClient(PipelineConfigurator<O, I> pipelineConfigurator, IClientConfig config) { return new LoadBalancingTcpClient<I, O>(config, getDefaultRetryHandlerWithConfig(config), pipelineConfigurator, poolCleanerScheduler); } public static RxClient<ByteBuf, ByteBuf> newTcpClient(IClientConfig config) { return new LoadBalancingTcpClient<ByteBuf, ByteBuf>(config, getDefaultRetryHandlerWithConfig(config), null, poolCleanerScheduler); } public static RxClient<DatagramPacket, DatagramPacket> newUdpClient(ILoadBalancer loadBalancer, IClientConfig config) { return new LoadBalancingUdpClient<DatagramPacket, DatagramPacket>(loadBalancer, config, getDefaultRetryHandlerWithConfig(config), null); } public static RxClient<DatagramPacket, DatagramPacket> newUdpClient(IClientConfig config) { return new LoadBalancingUdpClient<DatagramPacket, DatagramPacket>(config, getDefaultRetryHandlerWithConfig(config), null); } public static <I, O> RxClient<I, O> newUdpClient(ILoadBalancer loadBalancer, PipelineConfigurator<O, I> pipelineConfigurator, IClientConfig config, RetryHandler retryHandler) { return new LoadBalancingUdpClient<I, O>(loadBalancer, config, retryHandler, pipelineConfigurator); } public static <I, O> RxClient<I, O> newUdpClient(PipelineConfigurator<O, I> pipelineConfigurator, IClientConfig config) { return new LoadBalancingUdpClient<I, O>(config, getDefaultRetryHandlerWithConfig(config), pipelineConfigurator); } public static LoadBalancingHttpClient<ByteBuf, ByteBuf> newHttpClient() { IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues(); return newHttpClient(config); } public static LoadBalancingHttpClient<ByteBuf, ByteBuf> newHttpClient(ILoadBalancer loadBalancer, IClientConfig config) { return LoadBalancingHttpClient.<ByteBuf, ByteBuf>builder() .withLoadBalancer(loadBalancer) .withClientConfig(config) .withRetryHandler(getDefaultHttpRetryHandlerWithConfig(config)) .withPipelineConfigurator(DEFAULT_HTTP_PIPELINE_CONFIGURATOR) .withPoolCleanerScheduler(poolCleanerScheduler) .build(); } public static LoadBalancingHttpClient<ByteBuf, ByteBuf> newHttpClient(ILoadBalancer loadBalancer, IClientConfig config, RetryHandler retryHandler) { return LoadBalancingHttpClient.<ByteBuf, ByteBuf>builder() .withLoadBalancer(loadBalancer) .withClientConfig(config) .withRetryHandler(retryHandler) .withPipelineConfigurator(DEFAULT_HTTP_PIPELINE_CONFIGURATOR) .withPoolCleanerScheduler(poolCleanerScheduler) .build(); } public static LoadBalancingHttpClient<ByteBuf, ByteBuf> newHttpClient(ILoadBalancer loadBalancer, IClientConfig config, RetryHandler retryHandler, List<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>> listeners) { return LoadBalancingHttpClient.<ByteBuf, ByteBuf>builder() .withLoadBalancer(loadBalancer) .withClientConfig(config) .withRetryHandler(retryHandler) .withPipelineConfigurator(DEFAULT_HTTP_PIPELINE_CONFIGURATOR) .withPoolCleanerScheduler(poolCleanerScheduler) .withExecutorListeners(listeners) .build(); } public static LoadBalancingHttpClient<ByteBuf, ByteBuf> newHttpClient(IClientConfig config) { return LoadBalancingHttpClient.<ByteBuf, ByteBuf>builder() .withClientConfig(config) .withRetryHandler(getDefaultHttpRetryHandlerWithConfig(config)) .withPipelineConfigurator(DEFAULT_HTTP_PIPELINE_CONFIGURATOR) .withPoolCleanerScheduler(poolCleanerScheduler) .build(); } public static LoadBalancingHttpClient<ByteBuf, ByteBuf> newHttpClient(ILoadBalancer loadBalancer) { IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues(); return newHttpClient(loadBalancer, config); } public static <I, O> LoadBalancingHttpClient<I, O> newHttpClient(PipelineConfigurator<HttpClientResponse<O>, HttpClientRequest<I>> pipelineConfigurator, ILoadBalancer loadBalancer, IClientConfig config) { return LoadBalancingHttpClient.<I, O>builder() .withLoadBalancer(loadBalancer) .withClientConfig(config) .withRetryHandler(getDefaultHttpRetryHandlerWithConfig(config)) .withPipelineConfigurator(pipelineConfigurator) .withPoolCleanerScheduler(poolCleanerScheduler) .build(); } public static <I, O> LoadBalancingHttpClient<I, O> newHttpClient(PipelineConfigurator<HttpClientResponse<O>, HttpClientRequest<I>> pipelineConfigurator, IClientConfig config) { return LoadBalancingHttpClient.<I, O>builder() .withClientConfig(config) .withRetryHandler(getDefaultHttpRetryHandlerWithConfig(config)) .withPipelineConfigurator(pipelineConfigurator) .withPoolCleanerScheduler(poolCleanerScheduler) .build(); } public static <I, O> LoadBalancingHttpClient<I, O> newHttpClient(PipelineConfigurator<HttpClientResponse<O>, HttpClientRequest<I>> pipelineConfigurator, IClientConfig config, RetryHandler retryHandler) { return LoadBalancingHttpClient.<I, O>builder() .withClientConfig(config) .withRetryHandler(retryHandler) .withPipelineConfigurator(pipelineConfigurator) .withPoolCleanerScheduler(poolCleanerScheduler) .build(); } public static <I, O> LoadBalancingHttpClient<I, O> newHttpClient(PipelineConfigurator<HttpClientResponse<O>, HttpClientRequest<I>> pipelineConfigurator, ILoadBalancer loadBalancer, IClientConfig config, RetryHandler retryHandler, List<ExecutionListener<HttpClientRequest<I>, HttpClientResponse<O>>> listeners) { return LoadBalancingHttpClient.<I, O>builder() .withLoadBalancer(loadBalancer) .withClientConfig(config) .withRetryHandler(retryHandler) .withPipelineConfigurator(pipelineConfigurator) .withPoolCleanerScheduler(poolCleanerScheduler) .withExecutorListeners(listeners) .build(); } public static LoadBalancingHttpClient<ByteBuf, ServerSentEvent> newSSEClient(ILoadBalancer loadBalancer, IClientConfig config) { return SSEClient.<ByteBuf>sseClientBuilder() .withLoadBalancer(loadBalancer) .withClientConfig(config) .withRetryHandler(getDefaultHttpRetryHandlerWithConfig(config)) .withPipelineConfigurator(DEFAULT_SSE_PIPELINE_CONFIGURATOR) .build(); } public static LoadBalancingHttpClient<ByteBuf, ServerSentEvent> newSSEClient(IClientConfig config) { return SSEClient.<ByteBuf>sseClientBuilder() .withClientConfig(config) .withRetryHandler(getDefaultHttpRetryHandlerWithConfig(config)) .withPipelineConfigurator(DEFAULT_SSE_PIPELINE_CONFIGURATOR) .build(); } public static <I> LoadBalancingHttpClient<I, ServerSentEvent> newSSEClient(PipelineConfigurator<HttpClientResponse<ServerSentEvent>, HttpClientRequest<I>> pipelineConfigurator, ILoadBalancer loadBalancer, IClientConfig config) { return SSEClient.<I>sseClientBuilder() .withLoadBalancer(loadBalancer) .withClientConfig(config) .withRetryHandler(getDefaultHttpRetryHandlerWithConfig(config)) .withPipelineConfigurator(pipelineConfigurator) .build(); } public static <I> LoadBalancingHttpClient<I, ServerSentEvent> newSSEClient(PipelineConfigurator<HttpClientResponse<ServerSentEvent>, HttpClientRequest<I>> pipelineConfigurator, IClientConfig config) { return SSEClient.<I>sseClientBuilder() .withClientConfig(config) .withRetryHandler(getDefaultHttpRetryHandlerWithConfig(config)) .withPipelineConfigurator(pipelineConfigurator) .build(); } public static LoadBalancingHttpClient<ByteBuf, ServerSentEvent> newSSEClient() { IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues(); return newSSEClient(config); } }
7,082
0
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/udp/LoadBalancingUdpClient.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.ribbon.transport.netty.udp; import com.netflix.client.RetryHandler; import com.netflix.client.config.IClientConfig; import com.netflix.ribbon.transport.netty.LoadBalancingRxClient; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.Server; import io.reactivex.netty.RxNetty; import io.reactivex.netty.client.ClientMetricsEvent; import io.reactivex.netty.client.RxClient; import io.reactivex.netty.metrics.MetricEventsListener; import io.reactivex.netty.pipeline.PipelineConfigurator; import io.reactivex.netty.protocol.udp.client.UdpClientBuilder; import io.reactivex.netty.servo.udp.UdpClientListener; public class LoadBalancingUdpClient<I, O> extends LoadBalancingRxClient<I, O, RxClient<I,O>> implements RxClient<I, O> { public LoadBalancingUdpClient(IClientConfig config, RetryHandler retryHandler, PipelineConfigurator<O, I> pipelineConfigurator) { super(config, retryHandler, pipelineConfigurator); } public LoadBalancingUdpClient(ILoadBalancer lb, IClientConfig config, RetryHandler retryHandler, PipelineConfigurator<O, I> pipelineConfigurator) { super(lb, config, retryHandler, pipelineConfigurator); } @Override protected RxClient<I, O> createRxClient(Server server) { UdpClientBuilder<I, O> builder = RxNetty.newUdpClientBuilder(server.getHost(), server.getPort()); if (pipelineConfigurator != null) { builder.pipelineConfigurator(pipelineConfigurator); } return builder.build(); } @Override protected MetricEventsListener<? extends ClientMetricsEvent<?>> createListener( String name) { return UdpClientListener.newUdpListener(name); } }
7,083
0
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/tcp/LoadBalancingTcpClient.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.ribbon.transport.netty.tcp; import java.util.concurrent.ScheduledExecutorService; import io.netty.channel.ChannelOption; import io.reactivex.netty.RxNetty; import io.reactivex.netty.client.ClientBuilder; import io.reactivex.netty.client.ClientMetricsEvent; import io.reactivex.netty.client.RxClient; import io.reactivex.netty.metrics.MetricEventsListener; import io.reactivex.netty.pipeline.PipelineConfigurator; import io.reactivex.netty.servo.tcp.TcpClientListener; import com.netflix.client.RetryHandler; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import com.netflix.ribbon.transport.netty.LoadBalancingRxClientWithPoolOptions; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.Server; public class LoadBalancingTcpClient<I, O> extends LoadBalancingRxClientWithPoolOptions<I, O, RxClient<I,O>> implements RxClient<I, O> { public LoadBalancingTcpClient(ILoadBalancer lb, IClientConfig config, RetryHandler retryHandler, PipelineConfigurator<O, I> pipelineConfigurator, ScheduledExecutorService poolCleanerScheduler) { super(lb, config, retryHandler, pipelineConfigurator, poolCleanerScheduler); } public LoadBalancingTcpClient(IClientConfig config, RetryHandler retryHandler, PipelineConfigurator<O, I> pipelineConfigurator, ScheduledExecutorService poolCleanerScheduler) { super(config, retryHandler, pipelineConfigurator, poolCleanerScheduler); } @Override protected RxClient<I, O> createRxClient(Server server) { ClientBuilder<I, O> builder = RxNetty.newTcpClientBuilder(server.getHost(), server.getPort()); if (pipelineConfigurator != null) { builder.pipelineConfigurator(pipelineConfigurator); } Integer connectTimeout = getProperty(IClientConfigKey.Keys.ConnectTimeout, null, DefaultClientConfigImpl.DEFAULT_CONNECT_TIMEOUT); builder.channelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout); if (isPoolEnabled()) { builder.withConnectionPoolLimitStrategy(poolStrategy) .withIdleConnectionsTimeoutMillis(idleConnectionEvictionMills) .withPoolIdleCleanupScheduler(poolCleanerScheduler); } else { builder.withNoConnectionPooling(); } RxClient<I, O> client = builder.build(); return client; } @Override protected MetricEventsListener<? extends ClientMetricsEvent<?>> createListener( String name) { return TcpClientListener.newListener(name); } }
7,084
0
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/http/DefaultResponseToErrorPolicy.java
package com.netflix.ribbon.transport.netty.http; import io.netty.handler.codec.http.HttpResponseStatus; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import java.util.concurrent.TimeUnit; import rx.Observable; import rx.functions.Func1; import rx.functions.Func2; import com.netflix.client.ClientException; public class DefaultResponseToErrorPolicy<O> implements Func2<HttpClientResponse<O>, Integer, Observable<HttpClientResponse<O>>> { @Override public Observable<HttpClientResponse<O>> call(HttpClientResponse<O> t1, Integer backoff) { if (t1.getStatus().equals(HttpResponseStatus.INTERNAL_SERVER_ERROR)) { return Observable.error(new ClientException(ClientException.ErrorType.GENERAL)); } if (t1.getStatus().equals(HttpResponseStatus.SERVICE_UNAVAILABLE) || t1.getStatus().equals(HttpResponseStatus.BAD_GATEWAY) || t1.getStatus().equals(HttpResponseStatus.GATEWAY_TIMEOUT)) { if (backoff > 0) { return Observable.timer(backoff, TimeUnit.MILLISECONDS) .concatMap(new Func1<Long, Observable<HttpClientResponse<O>>>() { @Override public Observable<HttpClientResponse<O>> call(Long t1) { return Observable.error(new ClientException(ClientException.ErrorType.SERVER_THROTTLED)); } }); } else { return Observable.error(new ClientException(ClientException.ErrorType.SERVER_THROTTLED)); } } return Observable.just(t1); } }
7,085
0
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/http/LoadBalancingHttpClient.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.ribbon.transport.netty.http; import io.netty.buffer.ByteBufAllocator; import io.netty.channel.ChannelOption; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpMethod; import io.reactivex.netty.client.ClientMetricsEvent; import io.reactivex.netty.client.CompositePoolLimitDeterminationStrategy; import io.reactivex.netty.client.RxClient; import io.reactivex.netty.contexts.RxContexts; import io.reactivex.netty.contexts.http.HttpRequestIdProvider; import io.reactivex.netty.metrics.MetricEventsListener; import io.reactivex.netty.pipeline.PipelineConfigurator; import io.reactivex.netty.pipeline.ssl.DefaultFactories; import io.reactivex.netty.pipeline.ssl.SSLEngineFactory; import io.reactivex.netty.protocol.http.client.HttpClient; import io.reactivex.netty.protocol.http.client.HttpClientBuilder; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import io.reactivex.netty.servo.http.HttpClientListener; import java.net.URI; import java.net.URISyntaxException; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.net.ssl.SSLEngine; import rx.Observable; import rx.functions.Func1; import rx.functions.Func2; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.netflix.client.RequestSpecificRetryHandler; import com.netflix.client.RetryHandler; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import com.netflix.client.ssl.ClientSslSocketFactoryException; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.LoadBalancerBuilder; import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.ServerStats; import com.netflix.loadbalancer.reactive.ExecutionContext; import com.netflix.loadbalancer.reactive.ExecutionListener; import com.netflix.loadbalancer.reactive.LoadBalancerCommand; import com.netflix.loadbalancer.reactive.ServerOperation; import com.netflix.ribbon.transport.netty.LoadBalancingRxClientWithPoolOptions; /** * A Netty HttpClient that can connect to different servers. Internally it caches the RxNetty's HttpClient, with each created with * a connection pool governed by {@link CompositePoolLimitDeterminationStrategy} that has a global limit and per server limit. * * @author awang */ public class LoadBalancingHttpClient<I, O> extends LoadBalancingRxClientWithPoolOptions<HttpClientRequest<I>, HttpClientResponse<O>, HttpClient<I, O>> implements HttpClient<I, O> { private static final HttpClientConfig DEFAULT_RX_CONFIG = HttpClientConfig.Builder.newDefaultConfig(); private final String requestIdHeaderName; private final HttpRequestIdProvider requestIdProvider; private final List<ExecutionListener<HttpClientRequest<I>, HttpClientResponse<O>>> listeners; private final LoadBalancerCommand<HttpClientResponse<O>> defaultCommandBuilder; private final Func2<HttpClientResponse<O>, Integer, Observable<HttpClientResponse<O>>> responseToErrorPolicy; private final Func1<Integer, Integer> backoffStrategy; public static class Builder<I, O> { ILoadBalancer lb; IClientConfig config; RetryHandler retryHandler; PipelineConfigurator<HttpClientResponse<O>, HttpClientRequest<I>> pipelineConfigurator; ScheduledExecutorService poolCleanerScheduler; List<ExecutionListener<HttpClientRequest<I>, HttpClientResponse<O>>> listeners; Func2<HttpClientResponse<O>, Integer, Observable<HttpClientResponse<O>>> responseToErrorPolicy; Func1<Integer, Integer> backoffStrategy; Func1<Builder<I, O>, LoadBalancingHttpClient<I, O>> build; protected Builder(Func1<Builder<I, O>, LoadBalancingHttpClient<I, O>> build) { this.build = build; } public Builder<I, O> withLoadBalancer(ILoadBalancer lb) { this.lb = lb; return this; } public Builder<I, O> withClientConfig(IClientConfig config) { this.config = config; return this; } public Builder<I, O> withRetryHandler(RetryHandler retryHandler) { this.retryHandler = retryHandler; return this; } public Builder<I, O> withPipelineConfigurator(PipelineConfigurator<HttpClientResponse<O>, HttpClientRequest<I>> pipelineConfigurator) { this.pipelineConfigurator = pipelineConfigurator; return this; } public Builder<I, O> withPoolCleanerScheduler(ScheduledExecutorService poolCleanerScheduler) { this.poolCleanerScheduler = poolCleanerScheduler; return this; } public Builder<I, O> withExecutorListeners(List<ExecutionListener<HttpClientRequest<I>, HttpClientResponse<O>>> listeners) { this.listeners = listeners; return this; } /** * Policy for converting a response to an error if the status code indicates it as such. This will only * be called for responses with status code 4xx or 5xx * * Parameters to the function are * * HttpClientResponse - The actual response * * Integer - Backoff to apply if this is a retryable error. The backoff amount is in milliseconds * and is based on the configured BackoffStrategy. It is the responsibility of this function * to implement the actual backoff mechanism. This can be done as Observable.error(e).delay(backoff, TimeUnit.MILLISECONDS) * The return Observable will either contain the HttpClientResponse if is it not an error or an * Observable.error() with the translated exception. * * @param responseToErrorPolicy */ public Builder<I, O> withResponseToErrorPolicy(Func2<HttpClientResponse<O>, Integer, Observable<HttpClientResponse<O>>> responseToErrorPolicy) { this.responseToErrorPolicy = responseToErrorPolicy; return this; } /** * Strategy for calculating the backoff based on the number of reties. Input is the number * of retries and output is the backoff amount in milliseconds. * The default implementation is non random exponential backoff with time interval configurable * via the property BackoffInterval (default 1000 msec) * * @param backoffStrategy */ public Builder<I, O> withBackoffStrategy(Func1<Integer, Integer> backoffStrategy) { this.backoffStrategy = backoffStrategy; return this; } public LoadBalancingHttpClient<I, O> build() { if (retryHandler == null) { retryHandler = new NettyHttpLoadBalancerErrorHandler(); } if (config == null) { config = DefaultClientConfigImpl.getClientConfigWithDefaultValues(); } if (lb == null) { lb = LoadBalancerBuilder.newBuilder().withClientConfig(config).buildLoadBalancerFromConfigWithReflection(); } if (listeners == null) { listeners = Collections.<ExecutionListener<HttpClientRequest<I>, HttpClientResponse<O>>>emptyList(); } if (backoffStrategy == null) { backoffStrategy = new Func1<Integer, Integer>() { @Override public Integer call(Integer backoffCount) { int interval = config.getOrDefault(IClientConfigKey.Keys.BackoffInterval); if (backoffCount < 0) { backoffCount = 0; } else if (backoffCount > 10) { // Reasonable upper bound backoffCount = 10; } return (int)Math.pow(2, backoffCount) * interval; } }; } if (responseToErrorPolicy == null) { responseToErrorPolicy = new DefaultResponseToErrorPolicy<O>(); } return build.call(this); } } public static <I, O> Builder<I, O> builder() { return new Builder<I, O>(new Func1<Builder<I, O>, LoadBalancingHttpClient<I, O>>() { @Override public LoadBalancingHttpClient<I, O> call(Builder<I, O> builder) { return new LoadBalancingHttpClient<I, O>(builder); } }); } protected LoadBalancingHttpClient(Builder<I, O> builder) { super(builder.lb, builder.config, new RequestSpecificRetryHandler(true, true, builder.retryHandler, null), builder.pipelineConfigurator, builder.poolCleanerScheduler); requestIdHeaderName = getProperty(IClientConfigKey.Keys.RequestIdHeaderName, null, null); requestIdProvider = (requestIdHeaderName != null) ? new HttpRequestIdProvider(requestIdHeaderName, RxContexts.DEFAULT_CORRELATOR) : null; this.listeners = new CopyOnWriteArrayList<ExecutionListener<HttpClientRequest<I>, HttpClientResponse<O>>>(builder.listeners); defaultCommandBuilder = LoadBalancerCommand.<HttpClientResponse<O>>builder() .withLoadBalancerContext(lbContext) .withListeners(this.listeners) .withClientConfig(builder.config) .withRetryHandler(builder.retryHandler) .build(); this.responseToErrorPolicy = builder.responseToErrorPolicy; this.backoffStrategy = builder.backoffStrategy; } private RetryHandler getRequestRetryHandler(HttpClientRequest<?> request, IClientConfig requestConfig) { return new RequestSpecificRetryHandler( true, request.getMethod().equals(HttpMethod.GET), // Default only allows retrys for GET defaultRetryHandler, requestConfig); } protected static void setHostHeader(HttpClientRequest<?> request, String host) { request.getHeaders().set(HttpHeaders.Names.HOST, host); } /** * Submit a request to server chosen by the load balancer to execute. An error will be emitted from the returned {@link Observable} if * there is no server available from load balancer. */ @Override public Observable<HttpClientResponse<O>> submit(HttpClientRequest<I> request) { return submit(request, null, null); } /** * Submit a request to server chosen by the load balancer to execute. An error will be emitted from the returned {@link Observable} if * there is no server available from load balancer. * * @param config An {@link ClientConfig} to override the default configuration for the client. Can be null. * @return */ @Override public Observable<HttpClientResponse<O>> submit(final HttpClientRequest<I> request, final ClientConfig config) { return submit(null, request, null, null, config); } /** * Submit a request to run on a specific server * * @param server * @param request * @param requestConfig * @return */ public Observable<HttpClientResponse<O>> submit(Server server, final HttpClientRequest<I> request, final IClientConfig requestConfig) { return submit(server, request, null, requestConfig, getRxClientConfig(requestConfig)); } /** * Submit a request to server chosen by the load balancer to execute. An error will be emitted from the returned {@link Observable} if * there is no server available from load balancer. * * @param errorHandler A handler to determine the load balancer retry logic. If null, the default one will be used. * @param requestConfig An {@link IClientConfig} to override the default configuration for the client. Can be null. * @return */ public Observable<HttpClientResponse<O>> submit(final HttpClientRequest<I> request, final RetryHandler errorHandler, final IClientConfig requestConfig) { return submit(null, request, errorHandler, requestConfig, null); } public Observable<HttpClientResponse<O>> submit(Server server, final HttpClientRequest<I> request) { return submit(server, request, null, null, getRxClientConfig(null)); } /** * Convert an HttpClientRequest to a ServerOperation * * @param request * @param rxClientConfig * @return */ protected ServerOperation<HttpClientResponse<O>> requestToOperation(final HttpClientRequest<I> request, final ClientConfig rxClientConfig) { Preconditions.checkNotNull(request); return new ServerOperation<HttpClientResponse<O>>() { final AtomicInteger count = new AtomicInteger(0); @Override public Observable<HttpClientResponse<O>> call(Server server) { HttpClient<I,O> rxClient = getOrCreateRxClient(server); setHostHeader(request, server.getHost()); Observable<HttpClientResponse<O>> o; if (rxClientConfig != null) { o = rxClient.submit(request, rxClientConfig); } else { o = rxClient.submit(request); } return o.concatMap(new Func1<HttpClientResponse<O>, Observable<HttpClientResponse<O>>>() { @Override public Observable<HttpClientResponse<O>> call(HttpClientResponse<O> t1) { if (t1.getStatus().code()/100 == 4 || t1.getStatus().code()/100 == 5) return responseToErrorPolicy.call(t1, backoffStrategy.call(count.getAndIncrement())); else return Observable.just(t1); } }); } }; } /** * Construct an RxClient.ClientConfig from an IClientConfig * * @param requestConfig * @return */ private RxClient.ClientConfig getRxClientConfig(IClientConfig requestConfig) { if (requestConfig == null) { return DEFAULT_RX_CONFIG; } int requestReadTimeout = getProperty(IClientConfigKey.Keys.ReadTimeout, requestConfig, DefaultClientConfigImpl.DEFAULT_READ_TIMEOUT); Boolean followRedirect = getProperty(IClientConfigKey.Keys.FollowRedirects, requestConfig, null); HttpClientConfig.Builder builder = new HttpClientConfig.Builder().readTimeout(requestReadTimeout, TimeUnit.MILLISECONDS); if (followRedirect != null) { builder.setFollowRedirect(followRedirect); } return builder.build(); } /** * @return ClientConfig that is merged from IClientConfig and ClientConfig in the method arguments */ private RxClient.ClientConfig getRxClientConfig(IClientConfig ribbonClientConfig, ClientConfig rxClientConfig) { if (ribbonClientConfig == null) { return rxClientConfig; } else if (rxClientConfig == null) { return getRxClientConfig(ribbonClientConfig); } int readTimeoutFormRibbon = ribbonClientConfig.get(CommonClientConfigKey.ReadTimeout, -1); if (rxClientConfig instanceof HttpClientConfig) { HttpClientConfig httpConfig = (HttpClientConfig) rxClientConfig; HttpClientConfig.Builder builder = HttpClientConfig.Builder.from(httpConfig); if (readTimeoutFormRibbon >= 0) { builder.readTimeout(readTimeoutFormRibbon, TimeUnit.MILLISECONDS); } return builder.build(); } else { RxClient.ClientConfig.Builder builder = new RxClient.ClientConfig.Builder(rxClientConfig); if (readTimeoutFormRibbon >= 0) { builder.readTimeout(readTimeoutFormRibbon, TimeUnit.MILLISECONDS); } return builder.build(); } } private IClientConfig getRibbonClientConfig(ClientConfig rxClientConfig) { if (rxClientConfig != null && rxClientConfig.isReadTimeoutSet()) { return IClientConfig.Builder.newBuilder().withReadTimeout((int) rxClientConfig.getReadTimeoutInMillis()).build(); } return null; } /** * Subject an operation to run in the load balancer * * @param request * @param errorHandler * @param requestConfig * @param rxClientConfig * @return */ private Observable<HttpClientResponse<O>> submit(final Server server, final HttpClientRequest<I> request, final RetryHandler errorHandler, final IClientConfig requestConfig, final ClientConfig rxClientConfig) { RetryHandler retryHandler = errorHandler; if (retryHandler == null) { retryHandler = getRequestRetryHandler(request, requestConfig); } final IClientConfig config = requestConfig == null ? DefaultClientConfigImpl.getEmptyConfig() : requestConfig; final ExecutionContext<HttpClientRequest<I>> context = new ExecutionContext<HttpClientRequest<I>>(request, config, this.getClientConfig(), retryHandler); Observable<HttpClientResponse<O>> result = submitToServerInURI(request, config, rxClientConfig, retryHandler, context); if (result == null) { LoadBalancerCommand<HttpClientResponse<O>> command; if (retryHandler != defaultRetryHandler) { // need to create new builder instead of the default one command = LoadBalancerCommand.<HttpClientResponse<O>>builder() .withExecutionContext(context) .withLoadBalancerContext(lbContext) .withListeners(listeners) .withClientConfig(this.getClientConfig()) .withRetryHandler(retryHandler) .withServer(server) .build(); } else { command = defaultCommandBuilder; } result = command.submit(requestToOperation(request, getRxClientConfig(config, rxClientConfig))); } return result; } @VisibleForTesting ServerStats getServerStats(Server server) { return lbContext.getServerStats(server); } /** * Submits the request to the server indicated in the URI * @param request * @param requestConfig * @param config * @param errorHandler * @param context * @return */ private Observable<HttpClientResponse<O>> submitToServerInURI( HttpClientRequest<I> request, IClientConfig requestConfig, ClientConfig config, RetryHandler errorHandler, ExecutionContext<HttpClientRequest<I>> context) { // First, determine server from the URI URI uri; try { uri = new URI(request.getUri()); } catch (URISyntaxException e) { return Observable.error(e); } String host = uri.getHost(); if (host == null) { return null; } int port = uri.getPort(); if (port < 0) { if (clientConfig.get(IClientConfigKey.Keys.IsSecure, false)) { port = 443; } else { port = 80; } } return LoadBalancerCommand.<HttpClientResponse<O>>builder() .withRetryHandler(errorHandler) .withLoadBalancerContext(lbContext) .withListeners(listeners) .withExecutionContext(context) .withServer(new Server(host, port)) .build() .submit(this.requestToOperation(request, getRxClientConfig(requestConfig, config))); } @Override protected HttpClient<I, O> createRxClient(Server server) { HttpClientBuilder<I, O> clientBuilder; if (requestIdProvider != null) { clientBuilder = RxContexts.<I, O>newHttpClientBuilder(server.getHost(), server.getPort(), requestIdProvider, RxContexts.DEFAULT_CORRELATOR, pipelineConfigurator); } else { clientBuilder = RxContexts.<I, O>newHttpClientBuilder(server.getHost(), server.getPort(), RxContexts.DEFAULT_CORRELATOR, pipelineConfigurator); } Integer connectTimeout = getProperty(IClientConfigKey.Keys.ConnectTimeout, null, DefaultClientConfigImpl.DEFAULT_CONNECT_TIMEOUT); Integer readTimeout = getProperty(IClientConfigKey.Keys.ReadTimeout, null, DefaultClientConfigImpl.DEFAULT_READ_TIMEOUT); Boolean followRedirect = getProperty(IClientConfigKey.Keys.FollowRedirects, null, null); HttpClientConfig.Builder builder = new HttpClientConfig.Builder().readTimeout(readTimeout, TimeUnit.MILLISECONDS); if (followRedirect != null) { builder.setFollowRedirect(followRedirect); } clientBuilder .channelOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout) .config(builder.build()); if (isPoolEnabled()) { clientBuilder .withConnectionPoolLimitStrategy(poolStrategy) .withIdleConnectionsTimeoutMillis(idleConnectionEvictionMills) .withPoolIdleCleanupScheduler(poolCleanerScheduler); } else { clientBuilder .withNoConnectionPooling(); } if (sslContextFactory != null) { try { SSLEngineFactory myFactory = new DefaultFactories.SSLContextBasedFactory(sslContextFactory.getSSLContext()) { @Override public SSLEngine createSSLEngine(ByteBufAllocator allocator) { SSLEngine myEngine = super.createSSLEngine(allocator); myEngine.setUseClientMode(true); return myEngine; } }; clientBuilder.withSslEngineFactory(myFactory); } catch (ClientSslSocketFactoryException e) { throw new RuntimeException(e); } } return clientBuilder.build(); } @VisibleForTesting HttpClientListener getListener() { return (HttpClientListener) listener; } @VisibleForTesting Map<Server, HttpClient<I, O>> getRxClients() { return rxClientCache; } @Override protected MetricEventsListener<? extends ClientMetricsEvent<?>> createListener(String name) { return HttpClientListener.newHttpListener(name); } }
7,086
0
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/http/SSEClient.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.ribbon.transport.netty.http; import io.netty.channel.ChannelOption; import io.reactivex.netty.client.RxClient; import io.reactivex.netty.protocol.http.client.HttpClient; import io.reactivex.netty.protocol.http.client.HttpClientBuilder; import io.reactivex.netty.protocol.text.sse.ServerSentEvent; import rx.functions.Func1; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfigKey; import com.netflix.loadbalancer.Server; public class SSEClient<I> extends LoadBalancingHttpClient<I, ServerSentEvent> { public static <I> Builder<I, ServerSentEvent> sseClientBuilder() { return new Builder<I, ServerSentEvent>(new Func1<Builder<I, ServerSentEvent>, LoadBalancingHttpClient<I, ServerSentEvent>>() { @Override public LoadBalancingHttpClient<I, ServerSentEvent> call(Builder<I, ServerSentEvent> t1) { return new SSEClient<I>(t1); } }); } private SSEClient(LoadBalancingHttpClient.Builder<I, ServerSentEvent> t1) { super(t1); } @Override protected HttpClient<I, ServerSentEvent> getOrCreateRxClient(Server server) { HttpClientBuilder<I, ServerSentEvent> clientBuilder = new HttpClientBuilder<I, ServerSentEvent>(server.getHost(), server.getPort()).pipelineConfigurator(pipelineConfigurator); int requestConnectTimeout = getProperty(IClientConfigKey.Keys.ConnectTimeout, null, DefaultClientConfigImpl.DEFAULT_CONNECT_TIMEOUT); RxClient.ClientConfig rxClientConfig = new HttpClientConfig.Builder().build(); HttpClient<I, ServerSentEvent> client = clientBuilder.channelOption( ChannelOption.CONNECT_TIMEOUT_MILLIS, requestConnectTimeout).config(rxClientConfig).build(); return client; } @Override public void shutdown() { } }
7,087
0
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty
Create_ds/ribbon/ribbon-transport/src/main/java/com/netflix/ribbon/transport/netty/http/NettyHttpLoadBalancerErrorHandler.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.ribbon.transport.netty.http; import java.net.ConnectException; import java.net.SocketException; import java.net.SocketTimeoutException; import java.util.List; import com.google.common.collect.Lists; import com.netflix.client.ClientException; import com.netflix.client.DefaultLoadBalancerRetryHandler; import com.netflix.client.config.IClientConfig; import com.netflix.client.http.UnexpectedHttpResponseException; public class NettyHttpLoadBalancerErrorHandler extends DefaultLoadBalancerRetryHandler { @SuppressWarnings("unchecked") private List<Class<? extends Throwable>> retriable = Lists.<Class<? extends Throwable>>newArrayList(ConnectException.class, SocketTimeoutException.class, io.netty.handler.timeout.ReadTimeoutException.class, io.netty.channel.ConnectTimeoutException.class, io.reactivex.netty.client.PoolExhaustedException.class); @SuppressWarnings("unchecked") private List<Class<? extends Throwable>> circuitRelated = Lists.<Class<? extends Throwable>>newArrayList(SocketException.class, SocketTimeoutException.class, io.netty.handler.timeout.ReadTimeoutException.class, io.netty.channel.ConnectTimeoutException.class, io.reactivex.netty.client.PoolExhaustedException.class); public NettyHttpLoadBalancerErrorHandler() { super(); } public NettyHttpLoadBalancerErrorHandler(IClientConfig clientConfig) { super(clientConfig); } public NettyHttpLoadBalancerErrorHandler(int retrySameServer, int retryNextServer, boolean retryEnabled) { super(retrySameServer, retryNextServer, retryEnabled); } /** * @return true if the Throwable has one of the following exception type as a cause: * {@link SocketException}, {@link SocketTimeoutException} */ @Override public boolean isCircuitTrippingException(Throwable e) { if (e instanceof UnexpectedHttpResponseException) { return ((UnexpectedHttpResponseException) e).getStatusCode() == 503; } else if (e instanceof ClientException) { return ((ClientException) e).getErrorType() == ClientException.ErrorType.SERVER_THROTTLED; } return super.isCircuitTrippingException(e); } @Override public boolean isRetriableException(Throwable e, boolean sameServer) { if (e instanceof ClientException) { ClientException ce = (ClientException) e; if (ce.getErrorType() == ClientException.ErrorType.SERVER_THROTTLED) { return !sameServer && retryEnabled; } } return super.isRetriableException(e, sameServer); } @Override protected List<Class<? extends Throwable>> getRetriableExceptions() { return retriable; } @Override protected List<Class<? extends Throwable>> getCircuitRelatedExceptions() { return circuitRelated; } }
7,088
0
Create_ds/ribbon/ribbon-guice/src/test/java/com/netflix/ribbon/examples
Create_ds/ribbon/ribbon-guice/src/test/java/com/netflix/ribbon/examples/rx/RxMovieProxyExampleTest.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.ribbon.examples.rx; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Scopes; import com.netflix.client.config.ClientConfigFactory; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfig; import com.netflix.ribbon.transport.netty.http.LoadBalancingHttpClient; import com.netflix.config.ConfigurationManager; import com.netflix.ribbon.DefaultResourceFactory; import com.netflix.ribbon.RibbonResourceFactory; import com.netflix.ribbon.RibbonTransportFactory; import com.netflix.ribbon.RibbonTransportFactory.DefaultRibbonTransportFactory; import com.netflix.ribbon.examples.rx.proxy.MovieService; import com.netflix.ribbon.examples.rx.proxy.RxMovieProxyExample; import com.netflix.ribbon.guice.RibbonModule; import com.netflix.ribbon.guice.RibbonResourceProvider; import com.netflix.ribbon.proxy.processor.AnnotationProcessorsProvider; import com.netflix.ribbon.proxy.processor.AnnotationProcessorsProvider.DefaultAnnotationProcessorsProvider; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.HttpClient; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class RxMovieProxyExampleTest extends RxMovieClientTestBase { static class MyClientConfigFactory implements ClientConfigFactory { @Override public IClientConfig newConfig() { return new DefaultClientConfigImpl() { @Override public String getNameSpace() { return "MyConfig"; } }; } } @Test public void shouldBind() { ConfigurationManager.getConfigInstance().setProperty(MovieService.class.getSimpleName() + ".ribbon.listOfServers", "localhost:" + port); Injector injector = Guice.createInjector( new RibbonModule(), new AbstractModule() { @Override protected void configure() { bind(MovieService.class).toProvider(new RibbonResourceProvider<MovieService>(MovieService.class)).asEagerSingleton(); } } ); RxMovieProxyExample example = injector.getInstance(RxMovieProxyExample.class); assertTrue(example.runExample()); } @Test public void shouldBindCustomClientConfigFactory() { ConfigurationManager.getConfigInstance().setProperty(MovieService.class.getSimpleName() + ".MyConfig.listOfServers", "localhost:" + port); Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind(RibbonResourceFactory.class).to(DefaultResourceFactory.class).in(Scopes.SINGLETON); bind(RibbonTransportFactory.class).to(DefaultRibbonTransportFactory.class).in(Scopes.SINGLETON); bind(AnnotationProcessorsProvider.class).to(DefaultAnnotationProcessorsProvider.class).in(Scopes.SINGLETON); bind(ClientConfigFactory.class).to(MyClientConfigFactory.class).in(Scopes.SINGLETON); } }, new AbstractModule() { @Override protected void configure() { bind(MovieService.class).toProvider(new RibbonResourceProvider<MovieService>(MovieService.class)).asEagerSingleton(); } } ); RxMovieProxyExample example = injector.getInstance(RxMovieProxyExample.class); assertTrue(example.runExample()); } @Test public void testTransportFactoryWithInjection() { Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind(ClientConfigFactory.class).to(MyClientConfigFactory.class).in(Scopes.SINGLETON); bind(RibbonTransportFactory.class).to(DefaultRibbonTransportFactory.class).in(Scopes.SINGLETON); } } ); RibbonTransportFactory transportFactory = injector.getInstance(RibbonTransportFactory.class); HttpClient<ByteBuf, ByteBuf> client = transportFactory.newHttpClient("myClient"); IClientConfig config = ((LoadBalancingHttpClient) client).getClientConfig(); assertEquals("MyConfig", config.getNameSpace()); } }
7,089
0
Create_ds/ribbon/ribbon-guice/src/test/java/com/netflix/ribbon/examples
Create_ds/ribbon/ribbon-guice/src/test/java/com/netflix/ribbon/examples/rx/RxMovieClientTestBase.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.ribbon.examples.rx; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.server.HttpServer; import org.junit.After; import org.junit.Before; /** * @author Tomasz Bak */ public class RxMovieClientTestBase { protected int port = 0; private RxMovieServer movieServer; private HttpServer<ByteBuf, ByteBuf> httpServer; @Before public void setUp() throws Exception { movieServer = new RxMovieServer(port); httpServer = movieServer.createServer().start(); port = httpServer.getServerPort(); } @After public void tearDown() throws Exception { httpServer.shutdown(); } }
7,090
0
Create_ds/ribbon/ribbon-guice/src/test/java/com/netflix/ribbon/examples
Create_ds/ribbon/ribbon-guice/src/test/java/com/netflix/ribbon/examples/rx/RibbonModuleTest.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.ribbon.examples.rx; import com.google.inject.Guice; import com.google.inject.Injector; import com.netflix.ribbon.ClientOptions; import com.netflix.ribbon.RibbonResourceFactory; import com.netflix.ribbon.examples.rx.common.Movie; import com.netflix.ribbon.examples.rx.common.RecommendationServiceFallbackHandler; import com.netflix.ribbon.examples.rx.common.RecommendationServiceResponseValidator; import com.netflix.ribbon.examples.rx.common.RxMovieTransformer; import com.netflix.ribbon.guice.RibbonModule; import com.netflix.ribbon.http.HttpRequestTemplate; import com.netflix.ribbon.http.HttpResourceGroup; import io.netty.buffer.ByteBuf; import io.reactivex.netty.channel.StringTransformer; import org.junit.Test; import rx.Observable; import javax.inject.Inject; import javax.inject.Singleton; public class RibbonModuleTest { private static final int PORT = 7001; @Singleton public static class MyService extends AbstractRxMovieClient { private final HttpResourceGroup httpResourceGroup; private final HttpRequestTemplate<ByteBuf> registerMovieTemplate; private final HttpRequestTemplate<ByteBuf> updateRecommendationTemplate; private final HttpRequestTemplate<ByteBuf> recommendationsByUserIdTemplate; private final HttpRequestTemplate<ByteBuf> recommendationsByTemplate; @Inject public MyService(RibbonResourceFactory factory) { httpResourceGroup = factory.createHttpResourceGroup("movieServiceClient", ClientOptions.create() .withMaxAutoRetriesNextServer(3) .withConfigurationBasedServerList("localhost:" + PORT)); registerMovieTemplate = httpResourceGroup.newTemplateBuilder("registerMovie", ByteBuf.class) .withMethod("POST") .withUriTemplate("/movies") .withHeader("X-Platform-Version", "xyz") .withHeader("X-Auth-Token", "abc") .withResponseValidator(new RecommendationServiceResponseValidator()).build(); updateRecommendationTemplate = httpResourceGroup.newTemplateBuilder("updateRecommendation", ByteBuf.class) .withMethod("POST") .withUriTemplate("/users/{userId}/recommendations") .withHeader("X-Platform-Version", "xyz") .withHeader("X-Auth-Token", "abc") .withResponseValidator(new RecommendationServiceResponseValidator()).build(); recommendationsByUserIdTemplate = httpResourceGroup.newTemplateBuilder("recommendationsByUserId", ByteBuf.class) .withMethod("GET") .withUriTemplate("/users/{userId}/recommendations") .withHeader("X-Platform-Version", "xyz") .withHeader("X-Auth-Token", "abc") .withFallbackProvider(new RecommendationServiceFallbackHandler()) .withResponseValidator(new RecommendationServiceResponseValidator()).build(); recommendationsByTemplate = httpResourceGroup.newTemplateBuilder("recommendationsBy", ByteBuf.class) .withMethod("GET") .withUriTemplate("/recommendations?category={category}&ageGroup={ageGroup}") .withHeader("X-Platform-Version", "xyz") .withHeader("X-Auth-Token", "abc") .withFallbackProvider(new RecommendationServiceFallbackHandler()) .withResponseValidator(new RecommendationServiceResponseValidator()).build(); } @SuppressWarnings("unchecked") @Override protected Observable<ByteBuf>[] triggerMoviesRegistration() { return new Observable[]{ registerMovieTemplate.requestBuilder() .withRawContentSource(Observable.just(Movie.ORANGE_IS_THE_NEW_BLACK), new RxMovieTransformer()) .build().toObservable(), registerMovieTemplate.requestBuilder() .withRawContentSource(Observable.just(Movie.BREAKING_BAD), new RxMovieTransformer()) .build().toObservable(), registerMovieTemplate.requestBuilder() .withRawContentSource(Observable.just(Movie.HOUSE_OF_CARDS), new RxMovieTransformer()) .build().toObservable() }; } @SuppressWarnings("unchecked") @Override protected Observable<ByteBuf>[] triggerRecommendationsUpdate() { return new Observable[]{ updateRecommendationTemplate.requestBuilder() .withRawContentSource(Observable.just(Movie.ORANGE_IS_THE_NEW_BLACK.getId()), new StringTransformer()) .withRequestProperty("userId", TEST_USER) .build().toObservable(), updateRecommendationTemplate.requestBuilder() .withRawContentSource(Observable.just(Movie.BREAKING_BAD.getId()), new StringTransformer()) .withRequestProperty("userId", TEST_USER) .build().toObservable() }; } @SuppressWarnings("unchecked") @Override protected Observable<ByteBuf>[] triggerRecommendationsSearch() { return new Observable[]{ recommendationsByUserIdTemplate.requestBuilder() .withRequestProperty("userId", TEST_USER) .build().toObservable(), recommendationsByTemplate.requestBuilder() .withRequestProperty("category", "Drama") .withRequestProperty("ageGroup", "Adults") .build().toObservable() }; } } @Test public void shouldBind() { Injector injector = Guice.createInjector( new RibbonModule() ); MyService service = injector.getInstance(MyService.class); service.runExample(); } }
7,091
0
Create_ds/ribbon/ribbon-guice/src/test/java/com/netflix/ribbon/examples/rx
Create_ds/ribbon/ribbon-guice/src/test/java/com/netflix/ribbon/examples/rx/proxy/RxMovieProxyExample.java
package com.netflix.ribbon.examples.rx.proxy; import io.netty.buffer.ByteBuf; import javax.inject.Inject; import rx.Observable; import com.google.inject.Singleton; import com.netflix.ribbon.examples.rx.AbstractRxMovieClient; import com.netflix.ribbon.examples.rx.common.Movie; import com.netflix.ribbon.examples.rx.proxy.MovieService; import com.netflix.ribbon.proxy.ProxyLifeCycle; @Singleton public class RxMovieProxyExample extends AbstractRxMovieClient { private final MovieService movieService; @Inject public RxMovieProxyExample(MovieService movieService) { this.movieService = movieService; } @SuppressWarnings("unchecked") @Override protected Observable<ByteBuf>[] triggerMoviesRegistration() { return new Observable[]{ movieService.registerMovie(Movie.ORANGE_IS_THE_NEW_BLACK).toObservable(), movieService.registerMovie(Movie.BREAKING_BAD).toObservable(), movieService.registerMovie(Movie.HOUSE_OF_CARDS).toObservable() }; } @SuppressWarnings("unchecked") @Override protected Observable<ByteBuf>[] triggerRecommendationsUpdate() { return new Observable[]{ movieService.updateRecommendations(TEST_USER, Movie.ORANGE_IS_THE_NEW_BLACK.getId()).toObservable(), movieService.updateRecommendations(TEST_USER, Movie.BREAKING_BAD.getId()).toObservable() }; } @SuppressWarnings("unchecked") @Override protected Observable<ByteBuf>[] triggerRecommendationsSearch() { return new Observable[]{ movieService.recommendationsByUserId(TEST_USER).toObservable(), movieService.recommendationsBy("Drama", "Adults").toObservable() }; } @Override public void shutdown() { super.shutdown(); ((ProxyLifeCycle) movieService).shutdown(); } }
7,092
0
Create_ds/ribbon/ribbon-guice/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon-guice/src/main/java/com/netflix/ribbon/guice/RibbonResourceProvider.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.ribbon.guice; import com.google.inject.Inject; import com.google.inject.spi.BindingTargetVisitor; import com.google.inject.spi.ProviderInstanceBinding; import com.google.inject.spi.ProviderWithExtensionVisitor; import com.google.inject.spi.Toolable; import com.netflix.ribbon.RibbonResourceFactory; /** * Guice Provider extension to create a ribbon resource from an injectable * RibbonResourceFactory. * * @author elandau * * @param <T> Type of the client API interface class */ public class RibbonResourceProvider<T> implements ProviderWithExtensionVisitor<T> { private RibbonResourceFactory factory; private final Class<T> contract; public RibbonResourceProvider(Class<T> contract) { this.contract = contract; } @Override public T get() { // TODO: Get name from annotations (not only class name of contract) return factory.from(contract); } /** * This is needed for 'initialize(injector)' below to be called so the provider * can get the injector after it is instantiated. */ @Override public <B, V> V acceptExtensionVisitor( BindingTargetVisitor<B, V> visitor, ProviderInstanceBinding<? extends B> binding) { return visitor.visit(binding); } @Inject @Toolable protected void initialize(RibbonResourceFactory factory) { this.factory = factory; } }
7,093
0
Create_ds/ribbon/ribbon-guice/src/main/java/com/netflix/ribbon
Create_ds/ribbon/ribbon-guice/src/main/java/com/netflix/ribbon/guice/RibbonModule.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.ribbon.guice; import com.google.inject.AbstractModule; import com.google.inject.Scopes; import com.netflix.client.config.ClientConfigFactory; import com.netflix.ribbon.DefaultResourceFactory; import com.netflix.ribbon.RibbonResourceFactory; import com.netflix.ribbon.RibbonTransportFactory; import com.netflix.ribbon.RibbonTransportFactory.DefaultRibbonTransportFactory; import com.netflix.ribbon.proxy.processor.AnnotationProcessorsProvider; import com.netflix.ribbon.proxy.processor.AnnotationProcessorsProvider.DefaultAnnotationProcessorsProvider; /** * Default bindings for Ribbon * * @author elandau * */ public class RibbonModule extends AbstractModule { @Override protected void configure() { bind(ClientConfigFactory.class).toInstance(ClientConfigFactory.DEFAULT); bind(RibbonTransportFactory.class).to(DefaultRibbonTransportFactory.class).in(Scopes.SINGLETON); bind(AnnotationProcessorsProvider.class).to(DefaultAnnotationProcessorsProvider.class).in(Scopes.SINGLETON); bind(RibbonResourceFactory.class).to(DefaultResourceFactory.class).in(Scopes.SINGLETON); } }
7,094
0
Create_ds/ribbon/ribbon-eureka/src/test/java/com/netflix/niws
Create_ds/ribbon/ribbon-eureka/src/test/java/com/netflix/niws/loadbalancer/DefaultNIWSServerListFilterTest.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.niws.loadbalancer; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import com.netflix.config.ConfigurationBasedDeploymentContext; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import com.netflix.appinfo.AmazonInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.Builder; import com.netflix.client.ClientFactory; import com.netflix.config.ConfigurationManager; import com.netflix.config.DeploymentContext.ContextKey; import com.netflix.loadbalancer.AvailabilityFilteringRule; import com.netflix.loadbalancer.DynamicServerListLoadBalancer; import com.netflix.loadbalancer.LoadBalancerStats; import com.netflix.loadbalancer.ZoneAffinityServerListFilter; public class DefaultNIWSServerListFilterTest { @BeforeClass public static void init() { ConfigurationManager.getConfigInstance().setProperty(ContextKey.zone.getKey(), "us-eAst-1C"); } private DiscoveryEnabledServer createServer(String host, String zone) { return createServer(host, 7001, zone); } private DiscoveryEnabledServer createServer(String host, int port, String zone) { AmazonInfo amazonInfo = AmazonInfo.Builder.newBuilder().addMetadata(AmazonInfo.MetaDataKey.availabilityZone, zone).build(); Builder builder = InstanceInfo.Builder.newBuilder(); InstanceInfo info = builder.setAppName("l10nservicegeneral") .setDataCenterInfo(amazonInfo) .setHostName(host) .setPort(port) .build(); DiscoveryEnabledServer server = new DiscoveryEnabledServer(info, false, false); server.setZone(zone); return server; } private DiscoveryEnabledServer createServer(int hostId, String zoneSuffix) { return createServer(zoneSuffix + "-" + "server" + hostId, "Us-east-1" + zoneSuffix); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testZoneAffinityEnabled() throws Exception { ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest1.ribbon.DeploymentContextBasedVipAddresses", "l10nservicegeneral.cloud.netflix.net:7001"); ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest1.ribbon.NFLoadBalancerClassName", DynamicServerListLoadBalancer.class.getName()); ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest1.ribbon.NIWSServerListClassName", DiscoveryEnabledNIWSServerList.class.getName()); ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest1.ribbon.EnableZoneAffinity", "true"); DynamicServerListLoadBalancer lb = (DynamicServerListLoadBalancer) ClientFactory.getNamedLoadBalancer("DefaultNIWSServerListFilterTest1"); assertTrue(lb.getRule() instanceof AvailabilityFilteringRule); ZoneAffinityServerListFilter filter = (ZoneAffinityServerListFilter) lb.getFilter(); LoadBalancerStats loadBalancerStats = lb.getLoadBalancerStats(); List<DiscoveryEnabledServer> servers = new ArrayList<DiscoveryEnabledServer>(); servers.add(createServer(1, "a")); servers.add(createServer(2, "a")); servers.add(createServer(3, "a")); servers.add(createServer(4, "a")); servers.add(createServer(1, "b")); servers.add(createServer(2, "b")); servers.add(createServer(3, "b")); servers.add(createServer(1, "c")); servers.add(createServer(2, "c")); servers.add(createServer(3, "c")); servers.add(createServer(4, "c")); servers.add(createServer(5, "c")); List<DiscoveryEnabledServer> filtered = filter.getFilteredListOfServers(servers); List<DiscoveryEnabledServer> expected = new ArrayList<DiscoveryEnabledServer>(); expected.add(createServer(1, "c")); expected.add(createServer(2, "c")); expected.add(createServer(3, "c")); expected.add(createServer(4, "c")); expected.add(createServer(5, "c")); assertEquals(expected, filtered); lb.setServersList(filtered); for (int i = 1; i <= 4; i++) { loadBalancerStats.incrementActiveRequestsCount(createServer(i, "c")); } filtered = filter.getFilteredListOfServers(servers); assertEquals(servers, filtered); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testZoneExclusivity() throws Exception { ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest2.ribbon.DeploymentContextBasedVipAddresses", "l10nservicegeneral.cloud.netflix.net:7001"); ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest2.ribbon.NFLoadBalancerClassName", DynamicServerListLoadBalancer.class.getName()); ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest2.ribbon.EnableZoneExclusivity", "true"); ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest2.ribbon.NIWSServerListClassName", DiscoveryEnabledNIWSServerList.class.getName()); DynamicServerListLoadBalancer lb = (DynamicServerListLoadBalancer) ClientFactory.getNamedLoadBalancer("DefaultNIWSServerListFilterTest2"); ZoneAffinityServerListFilter filter = (ZoneAffinityServerListFilter) lb.getFilter(); LoadBalancerStats loadBalancerStats = lb.getLoadBalancerStats(); List<DiscoveryEnabledServer> servers = new ArrayList<DiscoveryEnabledServer>(); servers.add(createServer(1, "a")); servers.add(createServer(2, "a")); servers.add(createServer(3, "a")); servers.add(createServer(4, "a")); servers.add(createServer(1, "b")); servers.add(createServer(2, "b")); servers.add(createServer(3, "b")); servers.add(createServer(1, "c")); servers.add(createServer(2, "c")); servers.add(createServer(3, "c")); servers.add(createServer(4, "c")); servers.add(createServer(5, "c")); List<DiscoveryEnabledServer> filtered = filter.getFilteredListOfServers(servers); List<DiscoveryEnabledServer> expected = new ArrayList<DiscoveryEnabledServer>(); expected.add(createServer(1, "c")); expected.add(createServer(2, "c")); expected.add(createServer(3, "c")); expected.add(createServer(4, "c")); expected.add(createServer(5, "c")); assertEquals(expected, filtered); lb.setServersList(filtered); for (int i = 1; i <= 4; i++) { loadBalancerStats.incrementActiveRequestsCount(createServer(i, "c")); } filtered = filter.getFilteredListOfServers(servers); assertEquals(expected, filtered); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testZoneAffinityOverride() throws Exception { ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest3.ribbon.DeploymentContextBasedVipAddresses", "l10nservicegeneral.cloud.netflix.net:7001"); ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest3.ribbon.NFLoadBalancerClassName", DynamicServerListLoadBalancer.class.getName()); ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest3.ribbon.EnableZoneAffinity", "true"); ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest3.ribbon.NIWSServerListClassName", DiscoveryEnabledNIWSServerList.class.getName()); ConfigurationManager.getConfigInstance().setProperty("DefaultNIWSServerListFilterTest3.ribbon.zoneAffinity.minAvailableServers", "3"); DynamicServerListLoadBalancer lb = (DynamicServerListLoadBalancer) ClientFactory.getNamedLoadBalancer("DefaultNIWSServerListFilterTest3"); ZoneAffinityServerListFilter filter = (ZoneAffinityServerListFilter) lb.getFilter(); LoadBalancerStats loadBalancerStats = lb.getLoadBalancerStats(); List<DiscoveryEnabledServer> servers = new ArrayList<DiscoveryEnabledServer>(); servers.add(createServer(1, "a")); servers.add(createServer(2, "a")); servers.add(createServer(3, "a")); servers.add(createServer(4, "a")); servers.add(createServer(1, "b")); servers.add(createServer(2, "b")); servers.add(createServer(3, "b")); servers.add(createServer(1, "c")); servers.add(createServer(2, "c")); List<DiscoveryEnabledServer> filtered = filter.getFilteredListOfServers(servers); List<DiscoveryEnabledServer> expected = new ArrayList<DiscoveryEnabledServer>(); /* expected.add(createServer(1, "c")); expected.add(createServer(2, "c")); expected.add(createServer(3, "c")); expected.add(createServer(4, "c")); expected.add(createServer(5, "c")); */ // less than 3 servers in zone c, will not honor zone affinity assertEquals(servers, filtered); lb.setServersList(filtered); servers.add(createServer(3, "c")); filtered = filter.getFilteredListOfServers(servers); expected.add(createServer(1, "c")); expected.add(createServer(2, "c")); expected.add(createServer(3, "c")); filtered = filter.getFilteredListOfServers(servers); // now we have enough servers in C assertEquals(expected, filtered); // make one server black out for (int i = 1; i <= 3; i++) { loadBalancerStats.incrementSuccessiveConnectionFailureCount(createServer(1, "c")); } filtered = filter.getFilteredListOfServers(servers); assertEquals(servers, filtered); // new server added in zone c, zone c should now have enough servers servers.add(createServer(4, "c")); filtered = filter.getFilteredListOfServers(servers); expected.add(createServer(4, "c")); assertEquals(expected, filtered); } }
7,095
0
Create_ds/ribbon/ribbon-eureka/src/test/java/com/netflix/niws
Create_ds/ribbon/ribbon-eureka/src/test/java/com/netflix/niws/loadbalancer/DiscoveryEnabledLoadBalancerSupportsPortOverrideTest.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.niws.loadbalancer; import com.netflix.appinfo.InstanceInfo; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.config.ConfigurationManager; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.DiscoveryManager; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.util.List; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.createMock; import static org.powermock.api.easymock.PowerMock.replay; import static org.powermock.api.easymock.PowerMock.verify; /** * Verify behavior of the override flag ForceClientPortConfiguration("ForceClientPortConfiguration") * * WARNING: This feature should be treated as temporary workaround to support * more than 2 ports per server until relevant load balancer paradigms * (i.e., Eureka Server/Client) can accommodate more than 2 ports in its metadata. * * Currently only works with the DiscoveryEnabledNIWSServerList since this is where the current limitation is applicable * * See also: https://github.com/Netflix/eureka/issues/71 * * I'll add that testing this is painful due to the DiscoveryManager.getInstance()... singletons man... * * Created by jzarfoss on 1/7/14. */ @RunWith(PowerMockRunner.class) @PrepareForTest( {DiscoveryManager.class, DiscoveryClient.class} ) @PowerMockIgnore("javax.management.*") @SuppressWarnings("PMD.AvoidUsingHardCodedIP") public class DiscoveryEnabledLoadBalancerSupportsPortOverrideTest { @Before public void setupMock(){ List<InstanceInfo> dummyII = LoadBalancerTestUtils.getDummyInstanceInfo("dummy", "http://www.host.com", "1.1.1.1", 8001); List<InstanceInfo> secureDummyII = LoadBalancerTestUtils.getDummyInstanceInfo("secureDummy", "http://www.host.com", "1.1.1.1", 8002); PowerMock.mockStatic(DiscoveryManager.class); PowerMock.mockStatic(DiscoveryClient.class); DiscoveryClient mockedDiscoveryClient = LoadBalancerTestUtils.mockDiscoveryClient(); DiscoveryManager mockedDiscoveryManager = createMock(DiscoveryManager.class); expect(DiscoveryManager.getInstance()).andReturn(mockedDiscoveryManager).anyTimes(); expect(mockedDiscoveryManager.getDiscoveryClient()).andReturn(mockedDiscoveryClient).anyTimes(); expect(mockedDiscoveryClient.getInstancesByVipAddress("dummy", false, "region")).andReturn(dummyII).anyTimes(); expect(mockedDiscoveryClient.getInstancesByVipAddress("secureDummy", true, "region")).andReturn(secureDummyII).anyTimes(); replay(DiscoveryManager.class); replay(DiscoveryClient.class); replay(mockedDiscoveryManager); replay(mockedDiscoveryClient); } @After public void afterMock(){ verify(DiscoveryManager.class); verify(DiscoveryClient.class); } @Test public void testDefaultHonorsVipPortDefinition() throws Exception{ ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipPortDefinition.ribbon.DeploymentContextBasedVipAddresses", "dummy"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipPortDefinition.ribbon.IsSecure", "false"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipPortDefinition.ribbon.Port", "6999"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipPortDefinition.ribbon.TargetRegion", "region"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipPortDefinition.ribbon.NIWSServerListClassName", DiscoveryEnabledNIWSServerList.class.getName()); DiscoveryEnabledNIWSServerList deList = new DiscoveryEnabledNIWSServerList(); DefaultClientConfigImpl clientConfig = DefaultClientConfigImpl.class.newInstance(); clientConfig.loadProperties("DiscoveryEnabled.testDefaultHonorsVipPortDefinition"); deList.initWithNiwsConfig(clientConfig); List<DiscoveryEnabledServer> serverList = deList.getInitialListOfServers(); Assert.assertEquals(1, serverList.size()); Assert.assertEquals(8001, serverList.get(0).getPort()); // vip indicated Assert.assertEquals(8001, serverList.get(0).getInstanceInfo().getPort()); // vip indicated Assert.assertEquals(7002, serverList.get(0).getInstanceInfo().getSecurePort()); // 7002 is the secure default } @Test public void testDefaultHonorsVipSecurePortDefinition() throws Exception{ ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipSecurePortDefinition.ribbon.DeploymentContextBasedVipAddresses", "secureDummy"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipSecurePortDefinition.ribbon.IsSecure", "true"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipSecurePortDefinition.ribbon.SecurePort", "6002"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipSecurePortDefinition.ribbon.TargetRegion", "region"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testDefaultHonorsVipSecurePortDefinition.ribbon.NIWSServerListClassName", DiscoveryEnabledNIWSServerList.class.getName()); DiscoveryEnabledNIWSServerList deList = new DiscoveryEnabledNIWSServerList(); DefaultClientConfigImpl clientConfig = DefaultClientConfigImpl.class.newInstance(); clientConfig.loadProperties("DiscoveryEnabled.testDefaultHonorsVipSecurePortDefinition"); deList.initWithNiwsConfig(clientConfig); List<DiscoveryEnabledServer> serverList = deList.getInitialListOfServers(); Assert.assertEquals(1, serverList.size()); Assert.assertEquals(8002, serverList.get(0).getPort()); // vip indicated Assert.assertEquals(8002, serverList.get(0).getInstanceInfo().getPort()); // vip indicated Assert.assertEquals(7002, serverList.get(0).getInstanceInfo().getSecurePort()); // 7002 is the secure default } @Test public void testVipPortCanBeOverriden() throws Exception{ ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testVipPortCanBeOverriden.ribbon.DeploymentContextBasedVipAddresses", "dummy"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testVipPortCanBeOverriden.ribbon.IsSecure", "false"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testVipPortCanBeOverriden.ribbon.Port", "6001"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testVipPortCanBeOverriden.ribbon.TargetRegion", "region"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testVipPortCanBeOverriden.ribbon.NIWSServerListClassName", DiscoveryEnabledNIWSServerList.class.getName()); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testVipPortCanBeOverriden.ribbon.ForceClientPortConfiguration", "true"); DiscoveryEnabledNIWSServerList deList = new DiscoveryEnabledNIWSServerList(); DefaultClientConfigImpl clientConfig = DefaultClientConfigImpl.class.newInstance(); clientConfig.loadProperties("DiscoveryEnabled.testVipPortCanBeOverriden"); deList.initWithNiwsConfig(clientConfig); List<DiscoveryEnabledServer> serverList = deList.getInitialListOfServers(); Assert.assertEquals(1, serverList.size()); Assert.assertEquals(6001, serverList.get(0).getPort()); // client property indicated Assert.assertEquals(6001, serverList.get(0).getInstanceInfo().getPort()); // client property indicated Assert.assertEquals(7002, serverList.get(0).getInstanceInfo().getSecurePort()); // 7002 is the secure default } @Test public void testSecureVipPortCanBeOverriden() throws Exception{ ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testSecureVipPortCanBeOverriden.ribbon.DeploymentContextBasedVipAddresses", "secureDummy"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testSecureVipPortCanBeOverriden.ribbon.IsSecure", "true"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testSecureVipPortCanBeOverriden.ribbon.SecurePort", "6002"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testSecureVipPortCanBeOverriden.ribbon.TargetRegion", "region"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testSecureVipPortCanBeOverriden.ribbon.NIWSServerListClassName", DiscoveryEnabledNIWSServerList.class.getName()); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testSecureVipPortCanBeOverriden.ribbon.ForceClientPortConfiguration", "true"); DiscoveryEnabledNIWSServerList deList = new DiscoveryEnabledNIWSServerList(); DefaultClientConfigImpl clientConfig = DefaultClientConfigImpl.class.newInstance(); clientConfig.loadProperties("DiscoveryEnabled.testSecureVipPortCanBeOverriden"); deList.initWithNiwsConfig(clientConfig); List<DiscoveryEnabledServer> serverList = deList.getInitialListOfServers(); Assert.assertEquals(1, serverList.size()); Assert.assertEquals(8002, serverList.get(0).getPort()); // vip indicated Assert.assertEquals(8002, serverList.get(0).getInstanceInfo().getPort()); // vip indicated Assert.assertEquals(6002, serverList.get(0).getInstanceInfo().getSecurePort()); // client property indicated } /** * Tests case where two different clients want to use the same instance, one with overriden ports and one without * * @throws Exception for anything unexpected */ @Test public void testTwoInstancesDontStepOnEachOther() throws Exception{ // setup override client ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther1.ribbon.DeploymentContextBasedVipAddresses", "dummy"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther1.ribbon.IsSecure", "false"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther1.ribbon.Port", "6001"); // override from 8001 ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther1.ribbon.TargetRegion", "region"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther1.ribbon.NIWSServerListClassName", DiscoveryEnabledNIWSServerList.class.getName()); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther1.ribbon.ForceClientPortConfiguration", "true"); // setup non override client ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther2.ribbon.DeploymentContextBasedVipAddresses", "dummy"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther2.ribbon.IsSecure", "false"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther2.ribbon.Port", "6001"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther2.ribbon.TargetRegion", "region"); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther2.ribbon.NIWSServerListClassName", DiscoveryEnabledNIWSServerList.class.getName()); ConfigurationManager.getConfigInstance().setProperty("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther2.ribbon.ForceClientPortConfiguration", "false"); // check override client DiscoveryEnabledNIWSServerList deList1 = new DiscoveryEnabledNIWSServerList(); DefaultClientConfigImpl clientConfig1 = DefaultClientConfigImpl.class.newInstance(); clientConfig1.loadProperties("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther1"); deList1.initWithNiwsConfig(clientConfig1); List<DiscoveryEnabledServer> serverList1 = deList1.getInitialListOfServers(); Assert.assertEquals(1, serverList1.size()); Assert.assertEquals(6001, serverList1.get(0).getPort()); // client property overridden Assert.assertEquals(6001, serverList1.get(0).getInstanceInfo().getPort()); // client property overridden Assert.assertEquals(7002, serverList1.get(0).getInstanceInfo().getSecurePort()); // 7002 is the secure default // check non-override client DiscoveryEnabledNIWSServerList deList2 = new DiscoveryEnabledNIWSServerList(); DefaultClientConfigImpl clientConfig2 = DefaultClientConfigImpl.class.newInstance(); clientConfig2.loadProperties("DiscoveryEnabled.testTwoInstancesDontStepOnEachOther2"); deList2.initWithNiwsConfig(clientConfig2); List<DiscoveryEnabledServer> serverList2 = deList2.getInitialListOfServers(); Assert.assertEquals(1, serverList2.size()); Assert.assertEquals(8001, serverList2.get(0).getPort()); // client property indicated in ii Assert.assertEquals(8001, serverList2.get(0).getInstanceInfo().getPort()); // client property indicated in ii Assert.assertEquals(7002, serverList2.get(0).getInstanceInfo().getSecurePort()); // 7002 is the secure default } }
7,096
0
Create_ds/ribbon/ribbon-eureka/src/test/java/com/netflix/niws
Create_ds/ribbon/ribbon-eureka/src/test/java/com/netflix/niws/loadbalancer/EurekaNotificationServerListUpdaterTest.java
package com.netflix.niws.loadbalancer; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.netflix.discovery.CacheRefreshedEvent; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaEventListener; import com.netflix.loadbalancer.ServerListUpdater; import org.easymock.Capture; import org.easymock.EasyMock; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import javax.inject.Provider; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * @author David Liu */ public class EurekaNotificationServerListUpdaterTest { private EurekaClient eurekaClientMock; private EurekaClient eurekaClientMock2; private ThreadPoolExecutor testExecutor; @Before public void setUp() { eurekaClientMock = setUpEurekaClientMock(); eurekaClientMock2 = setUpEurekaClientMock(); // use a test executor so that the tests do not share executors testExecutor = new ThreadPoolExecutor( 2, 2 * 5, 0, TimeUnit.NANOSECONDS, new ArrayBlockingQueue<Runnable>(1000), new ThreadFactoryBuilder() .setNameFormat("EurekaNotificationServerListUpdater-%d") .setDaemon(true) .build() ); } @Test public void testUpdating() throws Exception { EurekaNotificationServerListUpdater serverListUpdater = new EurekaNotificationServerListUpdater( new Provider<EurekaClient>() { @Override public EurekaClient get() { return eurekaClientMock; } }, testExecutor ); try { Capture<EurekaEventListener> eventListenerCapture = new Capture<EurekaEventListener>(); eurekaClientMock.registerEventListener(EasyMock.capture(eventListenerCapture)); EasyMock.replay(eurekaClientMock); final AtomicBoolean firstTime = new AtomicBoolean(false); final CountDownLatch firstLatch = new CountDownLatch(1); final CountDownLatch secondLatch = new CountDownLatch(1); serverListUpdater.start(new ServerListUpdater.UpdateAction() { @Override public void doUpdate() { if (firstTime.compareAndSet(false, true)) { firstLatch.countDown(); } else { secondLatch.countDown(); } } }); eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent()); Assert.assertTrue(firstLatch.await(2, TimeUnit.SECONDS)); // wait a bit for the updateQueued flag to be reset for (int i = 1; i < 10; i++) { if (serverListUpdater.updateQueued.get()) { Thread.sleep(i * 100); } else { break; } } eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent()); Assert.assertTrue(secondLatch.await(2, TimeUnit.SECONDS)); } finally { serverListUpdater.stop(); EasyMock.verify(eurekaClientMock); } } @Test public void testStopWithCommonExecutor() throws Exception { EurekaNotificationServerListUpdater serverListUpdater1 = new EurekaNotificationServerListUpdater( new Provider<EurekaClient>() { @Override public EurekaClient get() { return eurekaClientMock; } }, testExecutor ); EurekaNotificationServerListUpdater serverListUpdater2 = new EurekaNotificationServerListUpdater( new Provider<EurekaClient>() { @Override public EurekaClient get() { return eurekaClientMock2; } }, testExecutor ); Capture<EurekaEventListener> eventListenerCapture = new Capture<EurekaEventListener>(); eurekaClientMock.registerEventListener(EasyMock.capture(eventListenerCapture)); Capture<EurekaEventListener> eventListenerCapture2 = new Capture<EurekaEventListener>(); eurekaClientMock2.registerEventListener(EasyMock.capture(eventListenerCapture2)); EasyMock.replay(eurekaClientMock); EasyMock.replay(eurekaClientMock2); final CountDownLatch updateCountLatch = new CountDownLatch(2); serverListUpdater1.start(new ServerListUpdater.UpdateAction() { @Override public void doUpdate() { updateCountLatch.countDown(); } }); serverListUpdater2.start(new ServerListUpdater.UpdateAction() { @Override public void doUpdate() { updateCountLatch.countDown(); } }); eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent()); eventListenerCapture2.getValue().onEvent(new CacheRefreshedEvent()); Assert.assertTrue(updateCountLatch.await(2, TimeUnit.SECONDS)); // latch is for both serverListUpdater1.stop(); serverListUpdater2.stop(); EasyMock.verify(eurekaClientMock); EasyMock.verify(eurekaClientMock2); } @Test public void testTaskAlreadyQueued() throws Exception { EurekaNotificationServerListUpdater serverListUpdater = new EurekaNotificationServerListUpdater( new Provider<EurekaClient>() { @Override public EurekaClient get() { return eurekaClientMock; } }, testExecutor ); try { Capture<EurekaEventListener> eventListenerCapture = new Capture<EurekaEventListener>(); eurekaClientMock.registerEventListener(EasyMock.capture(eventListenerCapture)); EasyMock.replay(eurekaClientMock); final CountDownLatch countDownLatch = new CountDownLatch(1); serverListUpdater.start(new ServerListUpdater.UpdateAction() { @Override public void doUpdate() { if (countDownLatch.getCount() == 0) { Assert.fail("should only countdown once"); } countDownLatch.countDown(); } }); eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent()); eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent()); Assert.assertTrue(countDownLatch.await(2, TimeUnit.SECONDS)); Thread.sleep(100); // sleep a bit more Assert.assertFalse(serverListUpdater.updateQueued.get()); } finally { serverListUpdater.stop(); EasyMock.verify(eurekaClientMock); } } @Test public void testSubmitExceptionClearQueued() { ThreadPoolExecutor executorMock = EasyMock.createMock(ThreadPoolExecutor.class); EasyMock.expect(executorMock.submit(EasyMock.isA(Runnable.class))) .andThrow(new RejectedExecutionException("test exception")); EasyMock.expect(executorMock.isShutdown()).andReturn(Boolean.FALSE); EurekaNotificationServerListUpdater serverListUpdater = new EurekaNotificationServerListUpdater( new Provider<EurekaClient>() { @Override public EurekaClient get() { return eurekaClientMock; } }, executorMock ); try { Capture<EurekaEventListener> eventListenerCapture = new Capture<EurekaEventListener>(); eurekaClientMock.registerEventListener(EasyMock.capture(eventListenerCapture)); EasyMock.replay(eurekaClientMock); EasyMock.replay(executorMock); serverListUpdater.start(new ServerListUpdater.UpdateAction() { @Override public void doUpdate() { Assert.fail("should not reach here"); } }); eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent()); Assert.assertFalse(serverListUpdater.updateQueued.get()); } finally { serverListUpdater.stop(); EasyMock.verify(executorMock); EasyMock.verify(eurekaClientMock); } } @Test public void testEurekaClientUnregister() { ThreadPoolExecutor executorMock = EasyMock.createMock(ThreadPoolExecutor.class); EasyMock.expect(executorMock.isShutdown()).andReturn(Boolean.TRUE); EurekaNotificationServerListUpdater serverListUpdater = new EurekaNotificationServerListUpdater( new Provider<EurekaClient>() { @Override public EurekaClient get() { return eurekaClientMock; } }, executorMock ); try { Capture<EurekaEventListener> registeredListener = new Capture<EurekaEventListener>(); eurekaClientMock.registerEventListener(EasyMock.capture(registeredListener)); EasyMock.replay(eurekaClientMock); EasyMock.replay(executorMock); serverListUpdater.start(new ServerListUpdater.UpdateAction() { @Override public void doUpdate() { Assert.fail("should not reach here"); } }); registeredListener.getValue().onEvent(new CacheRefreshedEvent()); } finally { EasyMock.verify(executorMock); EasyMock.verify(eurekaClientMock); } } @Test(expected = IllegalStateException.class) public void testFailIfDiscoveryIsNotAvailable() { EurekaNotificationServerListUpdater serverListUpdater = new EurekaNotificationServerListUpdater( new Provider<EurekaClient>() { @Override public EurekaClient get() { return null; } }, testExecutor ); serverListUpdater.start(new ServerListUpdater.UpdateAction() { @Override public void doUpdate() { Assert.fail("Should not reach here"); } }); } private EurekaClient setUpEurekaClientMock() { final EurekaClient eurekaClientMock = EasyMock.createMock(EurekaClient.class); EasyMock .expect(eurekaClientMock.unregisterEventListener(EasyMock.isA(EurekaEventListener.class))) .andReturn(true).times(1); return eurekaClientMock; } }
7,097
0
Create_ds/ribbon/ribbon-eureka/src/test/java/com/netflix/niws
Create_ds/ribbon/ribbon-eureka/src/test/java/com/netflix/niws/loadbalancer/LoadBalancerTestUtils.java
package com.netflix.niws.loadbalancer; import com.netflix.appinfo.DataCenterInfo; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.MyDataCenterInfo; import com.netflix.discovery.DefaultEurekaClientConfig; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.DiscoveryManager; import java.util.ArrayList; import java.util.List; import static org.easymock.EasyMock.expect; import static org.powermock.api.easymock.PowerMock.createMock; public class LoadBalancerTestUtils { static List<InstanceInfo> getDummyInstanceInfo(String appName, String host, String ipAddr, int port){ List<InstanceInfo> list = new ArrayList<InstanceInfo>(); InstanceInfo info = InstanceInfo.Builder.newBuilder().setAppName(appName) .setHostName(host) .setIPAddr(ipAddr) .setPort(port) .setDataCenterInfo(new MyDataCenterInfo(DataCenterInfo.Name.MyOwn)) .build(); list.add(info); return list; } static DiscoveryClient mockDiscoveryClient() { DiscoveryClient mockedDiscoveryClient = createMock(DiscoveryClient.class); expect(mockedDiscoveryClient.getEurekaClientConfig()).andReturn(new DefaultEurekaClientConfig()).anyTimes(); return mockedDiscoveryClient; } }
7,098
0
Create_ds/ribbon/ribbon-eureka/src/test/java/com/netflix/niws
Create_ds/ribbon/ribbon-eureka/src/test/java/com/netflix/niws/loadbalancer/LBBuilderTest.java
package com.netflix.niws.loadbalancer; import com.google.common.collect.Lists; import com.netflix.appinfo.InstanceInfo; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey.Keys; import com.netflix.config.ConfigurationManager; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.DiscoveryManager; import com.netflix.loadbalancer.AvailabilityFilteringRule; import com.netflix.loadbalancer.BaseLoadBalancer; import com.netflix.loadbalancer.DummyPing; import com.netflix.loadbalancer.DynamicServerListLoadBalancer; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.IRule; import com.netflix.loadbalancer.LoadBalancerBuilder; import com.netflix.loadbalancer.PollingServerListUpdater; import com.netflix.loadbalancer.RoundRobinRule; import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.ServerList; import com.netflix.loadbalancer.ServerListFilter; import com.netflix.loadbalancer.ServerListUpdater; import com.netflix.loadbalancer.ZoneAffinityServerListFilter; import com.netflix.loadbalancer.ZoneAwareLoadBalancer; import org.apache.commons.configuration.Configuration; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.util.List; import static org.easymock.EasyMock.expect; import static org.junit.Assert.*; import static org.powermock.api.easymock.PowerMock.createMock; import static org.powermock.api.easymock.PowerMock.replay; @RunWith(PowerMockRunner.class) @PrepareForTest( {DiscoveryManager.class, DiscoveryClient.class} ) @PowerMockIgnore({"javax.management.*", "com.sun.jersey.*", "com.sun.*", "org.apache.*", "weblogic.*", "com.netflix.config.*", "com.sun.jndi.dns.*", "javax.naming.*", "com.netflix.logging.*", "javax.ws.*", "com.google.*"}) public class LBBuilderTest { static Server expected = new Server("www.example.com", 8001); static class NiwsClientConfig extends DefaultClientConfigImpl { public NiwsClientConfig() { super(); } @Override public String getNameSpace() { return "niws.client"; } } @Before public void setupMock(){ List<InstanceInfo> instances = LoadBalancerTestUtils.getDummyInstanceInfo("dummy", expected.getHost(), "127.0.0.1", expected.getPort()); PowerMock.mockStatic(DiscoveryManager.class); PowerMock.mockStatic(DiscoveryClient.class); DiscoveryClient mockedDiscoveryClient = LoadBalancerTestUtils.mockDiscoveryClient(); DiscoveryManager mockedDiscoveryManager = createMock(DiscoveryManager.class); expect(DiscoveryManager.getInstance()).andReturn(mockedDiscoveryManager).anyTimes(); expect(mockedDiscoveryManager.getDiscoveryClient()).andReturn(mockedDiscoveryClient).anyTimes(); expect(mockedDiscoveryClient.getInstancesByVipAddress("dummy:7001", false, null)).andReturn(instances).anyTimes(); replay(DiscoveryManager.class); replay(DiscoveryClient.class); replay(mockedDiscoveryManager); replay(mockedDiscoveryClient); } @Test public void testBuildWithDiscoveryEnabledNIWSServerList() { IRule rule = new AvailabilityFilteringRule(); ServerList<DiscoveryEnabledServer> list = new DiscoveryEnabledNIWSServerList("dummy:7001"); ServerListFilter<DiscoveryEnabledServer> filter = new ZoneAffinityServerListFilter<>(); ZoneAwareLoadBalancer<DiscoveryEnabledServer> lb = LoadBalancerBuilder.<DiscoveryEnabledServer>newBuilder() .withDynamicServerList(list) .withRule(rule) .withServerListFilter(filter) .buildDynamicServerListLoadBalancer(); assertNotNull(lb); assertEquals(Lists.newArrayList(expected), lb.getAllServers()); assertSame(filter, lb.getFilter()); assertSame(list, lb.getServerListImpl()); Server server = lb.chooseServer(); // make sure load balancer does not recreate the server instance assertTrue(server instanceof DiscoveryEnabledServer); } @Test public void testBuildWithDiscoveryEnabledNIWSServerListAndUpdater() { IRule rule = new AvailabilityFilteringRule(); ServerList<DiscoveryEnabledServer> list = new DiscoveryEnabledNIWSServerList("dummy:7001"); ServerListFilter<DiscoveryEnabledServer> filter = new ZoneAffinityServerListFilter<>(); ServerListUpdater updater = new PollingServerListUpdater(); ZoneAwareLoadBalancer<DiscoveryEnabledServer> lb = LoadBalancerBuilder.<DiscoveryEnabledServer>newBuilder() .withDynamicServerList(list) .withRule(rule) .withServerListFilter(filter) .withServerListUpdater(updater) .buildDynamicServerListLoadBalancerWithUpdater(); assertNotNull(lb); assertEquals(Lists.newArrayList(expected), lb.getAllServers()); assertSame(filter, lb.getFilter()); assertSame(list, lb.getServerListImpl()); assertSame(updater, lb.getServerListUpdater()); Server server = lb.chooseServer(); // make sure load balancer does not recreate the server instance assertTrue(server instanceof DiscoveryEnabledServer); } @Test public void testBuildWithArchaiusProperties() { Configuration config = ConfigurationManager.getConfigInstance(); config.setProperty("client1.niws.client." + Keys.DeploymentContextBasedVipAddresses, "dummy:7001"); config.setProperty("client1.niws.client." + Keys.InitializeNFLoadBalancer, "true"); config.setProperty("client1.niws.client." + Keys.NFLoadBalancerClassName, DynamicServerListLoadBalancer.class.getName()); config.setProperty("client1.niws.client." + Keys.NFLoadBalancerRuleClassName, RoundRobinRule.class.getName()); config.setProperty("client1.niws.client." + Keys.NIWSServerListClassName, DiscoveryEnabledNIWSServerList.class.getName()); config.setProperty("client1.niws.client." + Keys.NIWSServerListFilterClassName, ZoneAffinityServerListFilter.class.getName()); config.setProperty("client1.niws.client." + Keys.ServerListUpdaterClassName, PollingServerListUpdater.class.getName()); IClientConfig clientConfig = IClientConfig.Builder.newBuilder(NiwsClientConfig.class, "client1").build(); ILoadBalancer lb = LoadBalancerBuilder.newBuilder().withClientConfig(clientConfig).buildLoadBalancerFromConfigWithReflection(); assertNotNull(lb); assertEquals(DynamicServerListLoadBalancer.class.getName(), lb.getClass().getName()); DynamicServerListLoadBalancer<Server> dynamicLB = (DynamicServerListLoadBalancer<Server>) lb; assertTrue(dynamicLB.getServerListUpdater() instanceof PollingServerListUpdater); assertTrue(dynamicLB.getFilter() instanceof ZoneAffinityServerListFilter); assertTrue(dynamicLB.getRule() instanceof RoundRobinRule); assertTrue(dynamicLB.getPing() instanceof DummyPing); assertEquals(Lists.newArrayList(expected), lb.getAllServers()); } @Test public void testBuildStaticServerListLoadBalancer() { List<Server> list = Lists.newArrayList(expected, expected); IRule rule = new AvailabilityFilteringRule(); IClientConfig clientConfig = IClientConfig.Builder.newBuilder() .withDefaultValues() .withMaxAutoRetriesNextServer(3).build(); assertEquals(3, clientConfig.get(Keys.MaxAutoRetriesNextServer).intValue()); BaseLoadBalancer lb = LoadBalancerBuilder.newBuilder() .withRule(rule) .buildFixedServerListLoadBalancer(list); assertEquals(list, lb.getAllServers()); assertSame(rule, lb.getRule()); } }
7,099