Search in sources :

Example 1 with ConsistentHashRing

use of com.linkedin.d2.balancer.util.hashing.ConsistentHashRing in project rest.li by linkedin.

the class TestScatterGather method getKeyToHostMapper.

private static ConsistentHashKeyMapper getKeyToHostMapper(int n, int partitionNum) throws URISyntaxException {
    Map<URI, Integer> endpoints = new HashMap<URI, Integer>();
    for (int ii = 0; ii < n; ++ii) {
        endpoints.put(new URI("test" + String.valueOf(ii)), 100);
    }
    final int partitionSize = endpoints.size() / partitionNum;
    List<Map<URI, Integer>> mapList = new ArrayList<Map<URI, Integer>>();
    int count = 0;
    for (final URI uri : endpoints.keySet()) {
        final int index = count / partitionSize;
        if (index == mapList.size()) {
            mapList.add(new HashMap<URI, Integer>());
        }
        Map<URI, Integer> map = mapList.get(index);
        map.put(uri, endpoints.get(uri));
        count++;
    }
    List<Ring<URI>> rings = new ArrayList<Ring<URI>>();
    for (final Map<URI, Integer> map : mapList) {
        final ConsistentHashRing<URI> ring = new ConsistentHashRing<URI>(map);
        rings.add(ring);
    }
    return new ConsistentHashKeyMapper(new StaticRingProvider(rings), new TestPartitionInfoProvider());
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) StaticRingProvider(com.linkedin.d2.balancer.util.hashing.StaticRingProvider) URI(java.net.URI) ConsistentHashRing(com.linkedin.d2.balancer.util.hashing.ConsistentHashRing) ConsistentHashRing(com.linkedin.d2.balancer.util.hashing.ConsistentHashRing) Ring(com.linkedin.d2.balancer.util.hashing.Ring) ConsistentHashKeyMapper(com.linkedin.d2.balancer.util.hashing.ConsistentHashKeyMapper) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) DataMap(com.linkedin.data.DataMap)

Example 2 with ConsistentHashRing

use of com.linkedin.d2.balancer.util.hashing.ConsistentHashRing in project rest.li by linkedin.

the class PointBasedConsistentHashRingFactory method createRing.

@Override
public Ring<T> createRing(Map<T, Integer> points) {
    List<Point<T>> newRingPoints = new ArrayList<>();
    clearPoints(points.size());
    for (Map.Entry<T, Integer> entry : points.entrySet()) {
        T t = entry.getKey();
        int numDesiredPoints = entry.getValue();
        List<Point<T>> tPoints = getPointList(t, numDesiredPoints);
        // Only copy the number of desired points
        newRingPoints.addAll(tPoints.subList(0, numDesiredPoints));
    }
    _log.debug("Creating new hash ring with the following points {}", newRingPoints);
    return new ConsistentHashRing<>(newRingPoints);
}
Also used : ConsistentHashRing(com.linkedin.d2.balancer.util.hashing.ConsistentHashRing) ArrayList(java.util.ArrayList) Point(com.linkedin.d2.balancer.util.hashing.ConsistentHashRing.Point) HashMap(java.util.HashMap) Map(java.util.Map) Point(com.linkedin.d2.balancer.util.hashing.ConsistentHashRing.Point)

Example 3 with ConsistentHashRing

use of com.linkedin.d2.balancer.util.hashing.ConsistentHashRing in project rest.li by linkedin.

the class ConsistentHashRingTest method testManyItemsEqualWeight.

@Test(groups = { "small", "back-end" })
public void testManyItemsEqualWeight() {
    Map<String, Integer> many = new HashMap<String, Integer>();
    Map<String, AtomicInteger> counts = new HashMap<String, AtomicInteger>();
    for (int i = 0; i < 100; ++i) {
        many.put("test" + i, 10);
        counts.put("test" + i, new AtomicInteger());
    }
    DegraderRingFactory<String> ringFactory = new DegraderRingFactory<>(new DegraderLoadBalancerStrategyConfig(1L));
    ConsistentHashRing<String> test = (ConsistentHashRing<String>) ringFactory.createRing(many);
    assertNotNull(test.get(0));
    // verify that each test item has 10 points on the ring
    List<ConsistentHashRing.Point<String>> points = test.getPoints();
    for (int i = 0; i < points.size(); ++i) {
        counts.get(points.get(i).getT()).incrementAndGet();
    }
    for (Entry<String, AtomicInteger> count : counts.entrySet()) {
        assertEquals(count.getValue().get(), 10);
    }
    double highLowDiff = test.getHighLowDiffOfAreaRing();
    assertTrue(highLowDiff < 1.54, "Hash Ring area diff is greater than it should be, saw diff of: " + highLowDiff);
}
Also used : HashMap(java.util.HashMap) DegraderLoadBalancerStrategyConfig(com.linkedin.d2.balancer.strategies.degrader.DegraderLoadBalancerStrategyConfig) DegraderRingFactory(com.linkedin.d2.balancer.strategies.degrader.DegraderRingFactory) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.testng.annotations.Test)

Example 4 with ConsistentHashRing

use of com.linkedin.d2.balancer.util.hashing.ConsistentHashRing in project rest.li by linkedin.

the class SimpleLoadBalancerTest method testLoadBalancerWithPartitionsSmoke.

// load balancer working with partitioned cluster
@Test(groups = { "small", "back-end" })
public void testLoadBalancerWithPartitionsSmoke() throws URISyntaxException, ServiceUnavailableException, InterruptedException, ExecutionException {
    for (int tryAgain = 0; tryAgain < 12; ++tryAgain) {
        Map<String, LoadBalancerStrategyFactory<? extends LoadBalancerStrategy>> loadBalancerStrategyFactories = new HashMap<String, LoadBalancerStrategyFactory<? extends LoadBalancerStrategy>>();
        Map<String, TransportClientFactory> clientFactories = new HashMap<String, TransportClientFactory>();
        List<String> prioritizedSchemes = new ArrayList<String>();
        MockStore<ServiceProperties> serviceRegistry = new MockStore<ServiceProperties>();
        MockStore<ClusterProperties> clusterRegistry = new MockStore<ClusterProperties>();
        MockStore<UriProperties> uriRegistry = new MockStore<UriProperties>();
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        loadBalancerStrategyFactories.put("degrader", new DegraderLoadBalancerStrategyFactoryV3());
        clientFactories.put("http", new DoNothingClientFactory());
        SimpleLoadBalancerState state = new SimpleLoadBalancerState(executorService, uriRegistry, clusterRegistry, serviceRegistry, clientFactories, loadBalancerStrategyFactories);
        SimpleLoadBalancer loadBalancer = new SimpleLoadBalancer(state, 5, TimeUnit.SECONDS);
        FutureCallback<None> balancerCallback = new FutureCallback<None>();
        loadBalancer.start(balancerCallback);
        balancerCallback.get();
        URI uri1 = URI.create("http://test.qa1.com:1234");
        URI uri2 = URI.create("http://test.qa2.com:2345");
        URI uri3 = URI.create("http://test.qa3.com:6789");
        Map<URI, Double> uris = new HashMap<URI, Double>();
        uris.put(uri1, 1d);
        uris.put(uri2, 1d);
        uris.put(uri3, 1d);
        Map<URI, Map<Integer, PartitionData>> partitionDesc = new HashMap<URI, Map<Integer, PartitionData>>();
        Map<Integer, PartitionData> server1 = new HashMap<Integer, PartitionData>();
        server1.put(0, new PartitionData(1d));
        server1.put(1, new PartitionData(1d));
        Map<Integer, PartitionData> server2 = new HashMap<Integer, PartitionData>();
        server2.put(0, new PartitionData(1d));
        Map<Integer, PartitionData> server3 = new HashMap<Integer, PartitionData>();
        server3.put(1, new PartitionData(1d));
        partitionDesc.put(uri1, server1);
        partitionDesc.put(uri2, server2);
        partitionDesc.put(uri3, server3);
        prioritizedSchemes.add("http");
        int partitionMethod = tryAgain % 4;
        switch(partitionMethod) {
            case 0:
                clusterRegistry.put("cluster-1", new ClusterProperties("cluster-1", null, new HashMap<String, String>(), new HashSet<URI>(), new RangeBasedPartitionProperties("id=(\\d+)", 0, 50, 2)));
                break;
            case 1:
                clusterRegistry.put("cluster-1", new ClusterProperties("cluster-1", null, new HashMap<String, String>(), new HashSet<URI>(), new HashBasedPartitionProperties("id=(\\d+)", 2, HashBasedPartitionProperties.HashAlgorithm.valueOf("MODULO"))));
                break;
            case 2:
                clusterRegistry.put("cluster-1", new ClusterProperties("cluster-1", null, new HashMap<String, String>(), new HashSet<URI>(), new HashBasedPartitionProperties("id=(\\d+)", 2, HashBasedPartitionProperties.HashAlgorithm.valueOf("MD5"))));
                break;
            case 3:
                // test getRings with gap. here, no server serves partition 2
                clusterRegistry.put("cluster-1", new ClusterProperties("cluster-1", null, new HashMap<String, String>(), new HashSet<URI>(), new RangeBasedPartitionProperties("id=(\\d+)", 0, 50, 4)));
                server3.put(3, new PartitionData(1d));
                partitionDesc.put(uri3, server3);
                break;
            default:
                break;
        }
        serviceRegistry.put("foo", new ServiceProperties("foo", "cluster-1", "/foo", Arrays.asList("degrader"), Collections.<String, Object>emptyMap(), null, null, prioritizedSchemes, null));
        uriRegistry.put("cluster-1", new UriProperties("cluster-1", partitionDesc));
        if (partitionMethod == 3) {
            Map<Integer, Ring<URI>> ringMap = loadBalancer.getRings(URI.create("d2://foo"));
            assertEquals(ringMap.size(), 4);
            // the ring for partition 2 should be empty
            assertEquals(ringMap.get(2).toString(), new ConsistentHashRing<URI>(Collections.emptyList()).toString());
            continue;
        }
        URI expectedUri1 = URI.create("http://test.qa1.com:1234/foo");
        URI expectedUri2 = URI.create("http://test.qa2.com:2345/foo");
        URI expectedUri3 = URI.create("http://test.qa3.com:6789/foo");
        Set<URI> expectedUris = new HashSet<URI>();
        expectedUris.add(expectedUri1);
        expectedUris.add(expectedUri2);
        expectedUris.add(expectedUri3);
        for (int i = 0; i < 1000; ++i) {
            int ii = i % 100;
            RewriteClient client = (RewriteClient) loadBalancer.getClient(new URIRequest("d2://foo/id=" + ii), new RequestContext());
            String clientUri = client.getUri().toString();
            HashFunction<String[]> hashFunction = null;
            String[] str = new String[1];
            // test KeyMapper target host hint: request is always to target host regardless of what's in d2 URI and whether it's hash-based or range-based partitions
            RequestContext requestContextWithHint = new RequestContext();
            KeyMapper.TargetHostHints.setRequestContextTargetHost(requestContextWithHint, uri1);
            RewriteClient hintedClient1 = (RewriteClient) loadBalancer.getClient(new URIRequest("d2://foo/id=" + ii), requestContextWithHint);
            String hintedUri1 = hintedClient1.getUri().toString();
            Assert.assertEquals(hintedUri1, uri1.toString() + "/foo");
            RewriteClient hintedClient2 = (RewriteClient) loadBalancer.getClient(new URIRequest("d2://foo/action=purge-all"), requestContextWithHint);
            String hintedUri2 = hintedClient2.getUri().toString();
            Assert.assertEquals(hintedUri2, uri1.toString() + "/foo");
            if (partitionMethod == 2) {
                hashFunction = new MD5Hash();
            }
            for (URI uri : expectedUris) {
                if (clientUri.contains(uri.toString())) {
                    // check if only key belonging to partition 0 gets uri2
                    if (uri.equals(uri2)) {
                        if (partitionMethod == 0) {
                            assertTrue(ii < 50);
                        } else if (partitionMethod == 1) {
                            assertTrue(ii % 2 == 0);
                        } else {
                            str[0] = ii + "";
                            assertTrue(hashFunction.hash(str) % 2 == 0);
                        }
                    }
                    // check if only key belonging to partition 1 gets uri3
                    if (uri.equals(uri3)) {
                        if (partitionMethod == 0) {
                            assertTrue(ii >= 50);
                        } else if (partitionMethod == 1) {
                            assertTrue(ii % 2 == 1);
                        } else {
                            str[0] = ii + "";
                            assertTrue(hashFunction.hash(str) % 2 == 1);
                        }
                    }
                }
            }
        }
        // two rings for two partitions
        Map<Integer, Ring<URI>> ringMap = loadBalancer.getRings(URI.create("d2://foo"));
        assertEquals(ringMap.size(), 2);
        if (partitionMethod != 2) {
            Set<String> keys = new HashSet<String>();
            for (int j = 0; j < 50; j++) {
                if (partitionMethod == 0) {
                    keys.add(j + "");
                } else {
                    keys.add(j * 2 + "");
                }
            }
            // if it is range based partition, all keys from 0 ~ 49 belong to partition 0 according to the range definition
            // if it is modulo based partition, all even keys belong to partition 0 because the partition count is 2
            // only from partition 0
            MapKeyResult<Ring<URI>, String> mapKeyResult = loadBalancer.getRings(URI.create("d2://foo"), keys);
            Map<Ring<URI>, Collection<String>> keyToPartition = mapKeyResult.getMapResult();
            assertEquals(keyToPartition.size(), 1);
            for (Ring<URI> ring : keyToPartition.keySet()) {
                assertEquals(ring, ringMap.get(0));
            }
            // now also from partition 1
            keys.add("51");
            mapKeyResult = loadBalancer.getRings(URI.create("d2://foo"), keys);
            assertEquals(mapKeyResult.getMapResult().size(), 2);
            assertEquals(mapKeyResult.getUnmappedKeys().size(), 0);
            // now only from partition 1
            keys.clear();
            keys.add("99");
            mapKeyResult = loadBalancer.getRings(URI.create("d2://foo"), keys);
            keyToPartition = mapKeyResult.getMapResult();
            assertEquals(keyToPartition.size(), 1);
            assertEquals(mapKeyResult.getUnmappedKeys().size(), 0);
            for (Ring<URI> ring : keyToPartition.keySet()) {
                assertEquals(ring, ringMap.get(1));
            }
            keys.add("100");
            mapKeyResult = loadBalancer.getRings(URI.create("d2://foo"), keys);
            if (partitionMethod == 0) {
                // key out of range
                Collection<MapKeyResult.UnmappedKey<String>> unmappedKeys = mapKeyResult.getUnmappedKeys();
                assertEquals(unmappedKeys.size(), 1);
            }
            try {
                loadBalancer.getClient(new URIRequest("d2://foo/id=100"), new RequestContext());
                if (partitionMethod == 0) {
                    // key out of range
                    fail("Should throw ServiceUnavailableException caused by PartitionAccessException");
                }
            } catch (ServiceUnavailableException e) {
            }
        }
        final CountDownLatch latch = new CountDownLatch(1);
        PropertyEventShutdownCallback callback = new PropertyEventShutdownCallback() {

            @Override
            public void done() {
                latch.countDown();
            }
        };
        state.shutdown(callback);
        if (!latch.await(60, TimeUnit.SECONDS)) {
            fail("unable to shutdown state");
        }
        executorService.shutdownNow();
        assertTrue(executorService.isShutdown(), "ExecutorService should have shut down!");
    }
}
Also used : HashMap(java.util.HashMap) DegraderLoadBalancerStrategyFactoryV3(com.linkedin.d2.balancer.strategies.degrader.DegraderLoadBalancerStrategyFactoryV3) ArrayList(java.util.ArrayList) PartitionData(com.linkedin.d2.balancer.properties.PartitionData) UriProperties(com.linkedin.d2.balancer.properties.UriProperties) RangeBasedPartitionProperties(com.linkedin.d2.balancer.properties.RangeBasedPartitionProperties) RequestContext(com.linkedin.r2.message.RequestContext) FutureCallback(com.linkedin.common.callback.FutureCallback) HashSet(java.util.HashSet) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) RandomLoadBalancerStrategyFactory(com.linkedin.d2.balancer.strategies.random.RandomLoadBalancerStrategyFactory) LoadBalancerStrategyFactory(com.linkedin.d2.balancer.strategies.LoadBalancerStrategyFactory) HashBasedPartitionProperties(com.linkedin.d2.balancer.properties.HashBasedPartitionProperties) URIRequest(com.linkedin.d2.balancer.util.URIRequest) RewriteClient(com.linkedin.d2.balancer.clients.RewriteClient) Collection(java.util.Collection) Map(java.util.Map) HashMap(java.util.HashMap) PropertyEventShutdownCallback(com.linkedin.d2.discovery.event.PropertyEventThread.PropertyEventShutdownCallback) MockStore(com.linkedin.d2.discovery.stores.mock.MockStore) ServiceUnavailableException(com.linkedin.d2.balancer.ServiceUnavailableException) URI(java.net.URI) ConsistentHashRing(com.linkedin.d2.balancer.util.hashing.ConsistentHashRing) TransportClientFactory(com.linkedin.r2.transport.common.TransportClientFactory) LoadBalancerStrategy(com.linkedin.d2.balancer.strategies.LoadBalancerStrategy) CountDownLatch(java.util.concurrent.CountDownLatch) ServiceProperties(com.linkedin.d2.balancer.properties.ServiceProperties) ConsistentHashRing(com.linkedin.d2.balancer.util.hashing.ConsistentHashRing) Ring(com.linkedin.d2.balancer.util.hashing.Ring) ClusterProperties(com.linkedin.d2.balancer.properties.ClusterProperties) MD5Hash(com.linkedin.d2.balancer.util.hashing.MD5Hash) None(com.linkedin.common.util.None) Test(org.testng.annotations.Test)

Aggregations

HashMap (java.util.HashMap)4 ConsistentHashRing (com.linkedin.d2.balancer.util.hashing.ConsistentHashRing)3 ArrayList (java.util.ArrayList)3 Map (java.util.Map)3 Ring (com.linkedin.d2.balancer.util.hashing.Ring)2 URI (java.net.URI)2 Test (org.testng.annotations.Test)2 FutureCallback (com.linkedin.common.callback.FutureCallback)1 None (com.linkedin.common.util.None)1 ServiceUnavailableException (com.linkedin.d2.balancer.ServiceUnavailableException)1 RewriteClient (com.linkedin.d2.balancer.clients.RewriteClient)1 ClusterProperties (com.linkedin.d2.balancer.properties.ClusterProperties)1 HashBasedPartitionProperties (com.linkedin.d2.balancer.properties.HashBasedPartitionProperties)1 PartitionData (com.linkedin.d2.balancer.properties.PartitionData)1 RangeBasedPartitionProperties (com.linkedin.d2.balancer.properties.RangeBasedPartitionProperties)1 ServiceProperties (com.linkedin.d2.balancer.properties.ServiceProperties)1 UriProperties (com.linkedin.d2.balancer.properties.UriProperties)1 LoadBalancerStrategy (com.linkedin.d2.balancer.strategies.LoadBalancerStrategy)1 LoadBalancerStrategyFactory (com.linkedin.d2.balancer.strategies.LoadBalancerStrategyFactory)1 DegraderLoadBalancerStrategyConfig (com.linkedin.d2.balancer.strategies.degrader.DegraderLoadBalancerStrategyConfig)1