Search in sources :

Example 21 with BiFunction

use of java.util.function.BiFunction in project gatk by broadinstitute.

the class CoverageModelEMWorkspace method getCopyRatioSegmentsSpark.

/**
     * Fetch copy ratio segments from compute blocks (Spark implementation)
     *
     * @return a list of {@link CopyRatioHMMResults}
     */
private List<List<HiddenStateSegmentRecord<STATE, Target>>> getCopyRatioSegmentsSpark() {
    /* local final member variables for lambda capture */
    final List<Target> processedTargetList = new ArrayList<>();
    processedTargetList.addAll(this.processedTargetList);
    final List<SexGenotypeData> processedSampleSexGenotypeData = new ArrayList<>();
    processedSampleSexGenotypeData.addAll(this.processedSampleSexGenotypeData);
    final List<String> processedSampleNameList = new ArrayList<>();
    processedSampleNameList.addAll(this.processedSampleNameList);
    final INDArray sampleReadDepths = Transforms.exp(sampleMeanLogReadDepths, true);
    final CopyRatioExpectationsCalculator<CoverageModelCopyRatioEmissionData, STATE> copyRatioExpectationsCalculator = this.copyRatioExpectationsCalculator;
    final BiFunction<SexGenotypeData, Target, STATE> referenceStateFactory = this.referenceStateFactory;
    return fetchCopyRatioEmissionDataSpark().mapPartitionsToPair(it -> {
        final List<Tuple2<Integer, CopyRatioHMMResults<CoverageModelCopyRatioEmissionData, STATE>>> newPartitionData = new ArrayList<>();
        while (it.hasNext()) {
            final Tuple2<Integer, List<CoverageModelCopyRatioEmissionData>> prevDatum = it.next();
            final int sampleIndex = prevDatum._1;
            final CopyRatioCallingMetadata copyRatioCallingMetadata = CopyRatioCallingMetadata.builder().sampleName(processedSampleNameList.get(sampleIndex)).sampleSexGenotypeData(processedSampleSexGenotypeData.get(sampleIndex)).sampleCoverageDepth(sampleReadDepths.getDouble(sampleIndex)).emissionCalculationStrategy(EmissionCalculationStrategy.HYBRID_POISSON_GAUSSIAN).build();
            newPartitionData.add(new Tuple2<>(sampleIndex, copyRatioExpectationsCalculator.getCopyRatioHMMResults(copyRatioCallingMetadata, processedTargetList, prevDatum._2)));
        }
        return newPartitionData.iterator();
    }, true).mapPartitionsToPair(it -> {
        final List<Tuple2<Integer, List<HiddenStateSegmentRecord<STATE, Target>>>> newPartitionData = new ArrayList<>();
        while (it.hasNext()) {
            final Tuple2<Integer, CopyRatioHMMResults<CoverageModelCopyRatioEmissionData, STATE>> prevDatum = it.next();
            final int sampleIndex = prevDatum._1;
            final CopyRatioHMMResults<CoverageModelCopyRatioEmissionData, STATE> result = prevDatum._2;
            final HMMSegmentProcessor<CoverageModelCopyRatioEmissionData, STATE, Target> processor = new HMMSegmentProcessor<>(Collections.singletonList(result.getMetaData().getSampleName()), Collections.singletonList(result.getMetaData().getSampleSexGenotypeData()), referenceStateFactory, Collections.singletonList(new HashedListTargetCollection<>(processedTargetList)), Collections.singletonList(result.getForwardBackwardResult()), Collections.singletonList(result.getViterbiResult()));
            newPartitionData.add(new Tuple2<>(sampleIndex, processor.getSegmentsAsList()));
        }
        return newPartitionData.iterator();
    }).collect().stream().sorted(Comparator.comparingInt(t -> t._1)).map(t -> t._2).collect(Collectors.toList());
}
Also used : ScalarProducer(org.broadinstitute.hellbender.utils.hmm.interfaces.ScalarProducer) Function2(org.apache.spark.api.java.function.Function2) HMMSegmentProcessor(org.broadinstitute.hellbender.utils.hmm.segmentation.HMMSegmentProcessor) GermlinePloidyAnnotatedTargetCollection(org.broadinstitute.hellbender.tools.exome.sexgenotyper.GermlinePloidyAnnotatedTargetCollection) HiddenStateSegmentRecordWriter(org.broadinstitute.hellbender.utils.hmm.segmentation.HiddenStateSegmentRecordWriter) BiFunction(java.util.function.BiFunction) GATKException(org.broadinstitute.hellbender.exceptions.GATKException) SexGenotypeData(org.broadinstitute.hellbender.tools.exome.sexgenotyper.SexGenotypeData) ParamUtils(org.broadinstitute.hellbender.utils.param.ParamUtils) CallStringProducer(org.broadinstitute.hellbender.utils.hmm.interfaces.CallStringProducer) StorageLevel(org.apache.spark.storage.StorageLevel) SynchronizedUnivariateSolver(org.broadinstitute.hellbender.tools.coveragemodel.math.SynchronizedUnivariateSolver) CopyRatioExpectationsCalculator(org.broadinstitute.hellbender.tools.coveragemodel.interfaces.CopyRatioExpectationsCalculator) UnivariateSolverSpecifications(org.broadinstitute.hellbender.tools.coveragemodel.math.UnivariateSolverSpecifications) IndexRange(org.broadinstitute.hellbender.utils.IndexRange) Broadcast(org.apache.spark.broadcast.Broadcast) ExitStatus(org.broadinstitute.hellbender.tools.coveragemodel.linalg.IterativeLinearSolverNDArray.ExitStatus) SexGenotypeDataCollection(org.broadinstitute.hellbender.tools.exome.sexgenotyper.SexGenotypeDataCollection) HashPartitioner(org.apache.spark.HashPartitioner) Predicate(java.util.function.Predicate) GeneralLinearOperator(org.broadinstitute.hellbender.tools.coveragemodel.linalg.GeneralLinearOperator) Nd4j(org.nd4j.linalg.factory.Nd4j) INDArrayIndex(org.nd4j.linalg.indexing.INDArrayIndex) FastMath(org.apache.commons.math3.util.FastMath) org.broadinstitute.hellbender.tools.exome(org.broadinstitute.hellbender.tools.exome) Tuple2(scala.Tuple2) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) AbstractUnivariateSolver(org.apache.commons.math3.analysis.solvers.AbstractUnivariateSolver) FourierLinearOperatorNDArray(org.broadinstitute.hellbender.tools.coveragemodel.linalg.FourierLinearOperatorNDArray) Logger(org.apache.logging.log4j.Logger) Stream(java.util.stream.Stream) UserException(org.broadinstitute.hellbender.exceptions.UserException) UnivariateFunction(org.apache.commons.math3.analysis.UnivariateFunction) TooManyEvaluationsException(org.apache.commons.math3.exception.TooManyEvaluationsException) Utils(org.broadinstitute.hellbender.utils.Utils) Function(org.apache.spark.api.java.function.Function) DataBuffer(org.nd4j.linalg.api.buffer.DataBuffer) IntStream(java.util.stream.IntStream) java.util(java.util) NDArrayIndex(org.nd4j.linalg.indexing.NDArrayIndex) JavaSparkContext(org.apache.spark.api.java.JavaSparkContext) AlleleMetadataProducer(org.broadinstitute.hellbender.utils.hmm.interfaces.AlleleMetadataProducer) EmissionCalculationStrategy(org.broadinstitute.hellbender.tools.coveragemodel.CoverageModelCopyRatioEmissionProbabilityCalculator.EmissionCalculationStrategy) RobustBrentSolver(org.broadinstitute.hellbender.tools.coveragemodel.math.RobustBrentSolver) IntervalUtils(org.broadinstitute.hellbender.utils.IntervalUtils) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) HiddenStateSegmentRecord(org.broadinstitute.hellbender.utils.hmm.segmentation.HiddenStateSegmentRecord) ImmutableTriple(org.apache.commons.lang3.tuple.ImmutableTriple) IterativeLinearSolverNDArray(org.broadinstitute.hellbender.tools.coveragemodel.linalg.IterativeLinearSolverNDArray) GATKProtectedMathUtils(org.broadinstitute.hellbender.utils.GATKProtectedMathUtils) Nd4jIOUtils(org.broadinstitute.hellbender.tools.coveragemodel.nd4jutils.Nd4jIOUtils) IOException(java.io.IOException) JavaPairRDD(org.apache.spark.api.java.JavaPairRDD) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) File(java.io.File) INDArray(org.nd4j.linalg.api.ndarray.INDArray) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Transforms(org.nd4j.linalg.ops.transforms.Transforms) LogManager(org.apache.logging.log4j.LogManager) NoBracketingException(org.apache.commons.math3.exception.NoBracketingException) INDArray(org.nd4j.linalg.api.ndarray.INDArray) Tuple2(scala.Tuple2) SexGenotypeData(org.broadinstitute.hellbender.tools.exome.sexgenotyper.SexGenotypeData) HMMSegmentProcessor(org.broadinstitute.hellbender.utils.hmm.segmentation.HMMSegmentProcessor)

Example 22 with BiFunction

use of java.util.function.BiFunction in project webpieces by deanhiller.

the class FieldMeta method createFunction.

private BiFunction<Object, Object, Void> createFunction(Class<? extends Object> beanClass, Field field) {
    String key = field.getName();
    String cap = key.substring(0, 1).toUpperCase() + key.substring(1);
    String methodName = "set" + cap;
    //What is slower....throwing exceptions or looping over methods to not through exception?....
    try {
        Method method = beanClass.getMethod(methodName, field.getType());
        return (bean, val) -> invokeMethod(method, bean, val);
    } catch (NoSuchMethodException e) {
        log.warn("performance penalty since method=" + methodName + " does not exist on class=" + beanClass.getName() + " using field instead to set data");
        return (bean, val) -> setField(field, bean, val);
    } catch (SecurityException e) {
        throw new RuntimeException(e);
    }
}
Also used : Logger(org.webpieces.util.logging.Logger) Type(java.lang.reflect.Type) BiFunction(java.util.function.BiFunction) LoggerFactory(org.webpieces.util.logging.LoggerFactory) Field(java.lang.reflect.Field) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) Method(java.lang.reflect.Method)

Example 23 with BiFunction

use of java.util.function.BiFunction in project elasticsearch by elastic.

the class UnicastZenPingTests method testSimplePings.

public void testSimplePings() throws IOException, InterruptedException, ExecutionException {
    // use ephemeral ports
    final Settings settings = Settings.builder().put("cluster.name", "test").put(TransportSettings.PORT.getKey(), 0).build();
    final Settings settingsMismatch = Settings.builder().put(settings).put("cluster.name", "mismatch").put(TransportSettings.PORT.getKey(), 0).build();
    NetworkService networkService = new NetworkService(settings, Collections.emptyList());
    final BiFunction<Settings, Version, Transport> supplier = (s, v) -> new MockTcpTransport(s, threadPool, BigArrays.NON_RECYCLING_INSTANCE, new NoneCircuitBreakerService(), new NamedWriteableRegistry(Collections.emptyList()), networkService, v) {

        @Override
        public void connectToNode(DiscoveryNode node, ConnectionProfile connectionProfile, CheckedBiConsumer<Connection, ConnectionProfile, IOException> connectionValidator) throws ConnectTransportException {
            throw new AssertionError("zen pings should never connect to node (got [" + node + "])");
        }
    };
    NetworkHandle handleA = startServices(settings, threadPool, "UZP_A", Version.CURRENT, supplier);
    closeables.push(handleA.transportService);
    NetworkHandle handleB = startServices(settings, threadPool, "UZP_B", Version.CURRENT, supplier);
    closeables.push(handleB.transportService);
    NetworkHandle handleC = startServices(settingsMismatch, threadPool, "UZP_C", Version.CURRENT, supplier);
    closeables.push(handleC.transportService);
    final Version versionD;
    if (randomBoolean()) {
        versionD = VersionUtils.randomVersionBetween(random(), Version.CURRENT.minimumCompatibilityVersion(), Version.CURRENT);
    } else {
        versionD = Version.CURRENT;
    }
    logger.info("UZP_D version set to [{}]", versionD);
    NetworkHandle handleD = startServices(settingsMismatch, threadPool, "UZP_D", versionD, supplier);
    closeables.push(handleD.transportService);
    final ClusterState state = ClusterState.builder(new ClusterName("test")).version(randomNonNegativeLong()).build();
    final ClusterState stateMismatch = ClusterState.builder(new ClusterName("mismatch")).version(randomNonNegativeLong()).build();
    Settings hostsSettings = Settings.builder().putArray("discovery.zen.ping.unicast.hosts", NetworkAddress.format(new InetSocketAddress(handleA.address.address().getAddress(), handleA.address.address().getPort())), NetworkAddress.format(new InetSocketAddress(handleB.address.address().getAddress(), handleB.address.address().getPort())), NetworkAddress.format(new InetSocketAddress(handleC.address.address().getAddress(), handleC.address.address().getPort())), NetworkAddress.format(new InetSocketAddress(handleD.address.address().getAddress(), handleD.address.address().getPort()))).put("cluster.name", "test").build();
    Settings hostsSettingsMismatch = Settings.builder().put(hostsSettings).put(settingsMismatch).build();
    TestUnicastZenPing zenPingA = new TestUnicastZenPing(hostsSettings, threadPool, handleA, EMPTY_HOSTS_PROVIDER);
    zenPingA.start(new PingContextProvider() {

        @Override
        public DiscoveryNodes nodes() {
            return DiscoveryNodes.builder().add(handleA.node).localNodeId("UZP_A").build();
        }

        @Override
        public ClusterState clusterState() {
            return ClusterState.builder(state).blocks(ClusterBlocks.builder().addGlobalBlock(STATE_NOT_RECOVERED_BLOCK)).build();
        }
    });
    closeables.push(zenPingA);
    TestUnicastZenPing zenPingB = new TestUnicastZenPing(hostsSettings, threadPool, handleB, EMPTY_HOSTS_PROVIDER);
    zenPingB.start(new PingContextProvider() {

        @Override
        public DiscoveryNodes nodes() {
            return DiscoveryNodes.builder().add(handleB.node).localNodeId("UZP_B").build();
        }

        @Override
        public ClusterState clusterState() {
            return state;
        }
    });
    closeables.push(zenPingB);
    TestUnicastZenPing zenPingC = new TestUnicastZenPing(hostsSettingsMismatch, threadPool, handleC, EMPTY_HOSTS_PROVIDER) {

        @Override
        protected Version getVersion() {
            return versionD;
        }
    };
    zenPingC.start(new PingContextProvider() {

        @Override
        public DiscoveryNodes nodes() {
            return DiscoveryNodes.builder().add(handleC.node).localNodeId("UZP_C").build();
        }

        @Override
        public ClusterState clusterState() {
            return stateMismatch;
        }
    });
    closeables.push(zenPingC);
    TestUnicastZenPing zenPingD = new TestUnicastZenPing(hostsSettingsMismatch, threadPool, handleD, EMPTY_HOSTS_PROVIDER);
    zenPingD.start(new PingContextProvider() {

        @Override
        public DiscoveryNodes nodes() {
            return DiscoveryNodes.builder().add(handleD.node).localNodeId("UZP_D").build();
        }

        @Override
        public ClusterState clusterState() {
            return stateMismatch;
        }
    });
    closeables.push(zenPingD);
    logger.info("ping from UZP_A");
    Collection<ZenPing.PingResponse> pingResponses = zenPingA.pingAndWait().toList();
    assertThat(pingResponses.size(), equalTo(1));
    ZenPing.PingResponse ping = pingResponses.iterator().next();
    assertThat(ping.node().getId(), equalTo("UZP_B"));
    assertThat(ping.getClusterStateVersion(), equalTo(state.version()));
    assertPingCount(handleA, handleB, 3);
    // mismatch, shouldn't ping
    assertPingCount(handleA, handleC, 0);
    // mismatch, shouldn't ping
    assertPingCount(handleA, handleD, 0);
    // ping again, this time from B,
    logger.info("ping from UZP_B");
    pingResponses = zenPingB.pingAndWait().toList();
    assertThat(pingResponses.size(), equalTo(1));
    ping = pingResponses.iterator().next();
    assertThat(ping.node().getId(), equalTo("UZP_A"));
    assertThat(ping.getClusterStateVersion(), equalTo(ElectMasterService.MasterCandidate.UNRECOVERED_CLUSTER_VERSION));
    assertPingCount(handleB, handleA, 3);
    // mismatch, shouldn't ping
    assertPingCount(handleB, handleC, 0);
    // mismatch, shouldn't ping
    assertPingCount(handleB, handleD, 0);
    logger.info("ping from UZP_C");
    pingResponses = zenPingC.pingAndWait().toList();
    assertThat(pingResponses.size(), equalTo(1));
    assertPingCount(handleC, handleA, 0);
    assertPingCount(handleC, handleB, 0);
    assertPingCount(handleC, handleD, 3);
    logger.info("ping from UZP_D");
    pingResponses = zenPingD.pingAndWait().toList();
    assertThat(pingResponses.size(), equalTo(1));
    assertPingCount(handleD, handleA, 0);
    assertPingCount(handleD, handleB, 0);
    assertPingCount(handleD, handleC, 3);
}
Also used : Arrays(java.util.Arrays) BigArrays(org.elasticsearch.common.util.BigArrays) ConcurrentCollections(org.elasticsearch.common.util.concurrent.ConcurrentCollections) BiFunction(java.util.function.BiFunction) ClusterBlocks(org.elasticsearch.cluster.block.ClusterBlocks) InetAddress(java.net.InetAddress) STATE_NOT_RECOVERED_BLOCK(org.elasticsearch.gateway.GatewayService.STATE_NOT_RECOVERED_BLOCK) ClusterState(org.elasticsearch.cluster.ClusterState) ConnectTransportException(org.elasticsearch.transport.ConnectTransportException) Settings(org.elasticsearch.common.settings.Settings) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) Matchers.eq(org.mockito.Matchers.eq) After(org.junit.After) Map(java.util.Map) ThreadPool(org.elasticsearch.threadpool.ThreadPool) ClusterName(org.elasticsearch.cluster.ClusterName) Role(org.elasticsearch.cluster.node.DiscoveryNode.Role) ThreadFactory(java.util.concurrent.ThreadFactory) EnumSet(java.util.EnumSet) Transport(org.elasticsearch.transport.Transport) Collection(java.util.Collection) MockTcpTransport(org.elasticsearch.transport.MockTcpTransport) Set(java.util.Set) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) CountDownLatch(java.util.concurrent.CountDownLatch) AbstractRunnable(org.elasticsearch.common.util.concurrent.AbstractRunnable) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Version(org.elasticsearch.Version) TransportAddress(org.elasticsearch.common.transport.TransportAddress) TransportConnectionListener(org.elasticsearch.transport.TransportConnectionListener) TransportSettings(org.elasticsearch.transport.TransportSettings) Matchers.equalTo(org.hamcrest.Matchers.equalTo) TransportResponseHandler(org.elasticsearch.transport.TransportResponseHandler) TransportRequestOptions(org.elasticsearch.transport.TransportRequestOptions) TransportException(org.elasticsearch.transport.TransportException) NetworkAddress(org.elasticsearch.common.network.NetworkAddress) Mockito.mock(org.mockito.Mockito.mock) IntStream(java.util.stream.IntStream) Matchers(org.mockito.Matchers) HashMap(java.util.HashMap) BoundTransportAddress(org.elasticsearch.common.transport.BoundTransportAddress) AtomicReference(java.util.concurrent.atomic.AtomicReference) CheckedBiConsumer(org.elasticsearch.common.CheckedBiConsumer) Stack(java.util.Stack) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) HashSet(java.util.HashSet) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) NetworkService(org.elasticsearch.common.network.NetworkService) NoneCircuitBreakerService(org.elasticsearch.indices.breaker.NoneCircuitBreakerService) NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) TimeValue(org.elasticsearch.common.unit.TimeValue) Matchers.hasSize(org.hamcrest.Matchers.hasSize) ESTestCase(org.elasticsearch.test.ESTestCase) MockTransportService(org.elasticsearch.test.transport.MockTransportService) TransportService(org.elasticsearch.transport.TransportService) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) ConnectionProfile(org.elasticsearch.transport.ConnectionProfile) Collections.emptyMap(java.util.Collections.emptyMap) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) Matchers.empty(org.hamcrest.Matchers.empty) EsExecutors(org.elasticsearch.common.util.concurrent.EsExecutors) Collections.emptySet(java.util.Collections.emptySet) IOUtils(org.apache.lucene.util.IOUtils) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) VersionUtils(org.elasticsearch.test.VersionUtils) Mockito.verify(org.mockito.Mockito.verify) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Closeable(java.io.Closeable) Collections(java.util.Collections) NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) CheckedBiConsumer(org.elasticsearch.common.CheckedBiConsumer) InetSocketAddress(java.net.InetSocketAddress) MockTcpTransport(org.elasticsearch.transport.MockTcpTransport) Version(org.elasticsearch.Version) ClusterName(org.elasticsearch.cluster.ClusterName) Settings(org.elasticsearch.common.settings.Settings) TransportSettings(org.elasticsearch.transport.TransportSettings) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) ClusterState(org.elasticsearch.cluster.ClusterState) ConnectionProfile(org.elasticsearch.transport.ConnectionProfile) NetworkService(org.elasticsearch.common.network.NetworkService) Transport(org.elasticsearch.transport.Transport) MockTcpTransport(org.elasticsearch.transport.MockTcpTransport) NoneCircuitBreakerService(org.elasticsearch.indices.breaker.NoneCircuitBreakerService)

Example 24 with BiFunction

use of java.util.function.BiFunction in project elasticsearch by elastic.

the class UnicastZenPingTests method startServices.

private NetworkHandle startServices(final Settings settings, final ThreadPool threadPool, final String nodeId, final Version version, final BiFunction<Settings, Version, Transport> supplier, final Set<Role> nodeRoles) {
    final Settings nodeSettings = Settings.builder().put(settings).put("node.name", nodeId).put(TransportService.TRACE_LOG_INCLUDE_SETTING.getKey(), "internal:discovery/zen/unicast").build();
    final Transport transport = supplier.apply(nodeSettings, version);
    final MockTransportService transportService = new MockTransportService(nodeSettings, transport, threadPool, TransportService.NOOP_TRANSPORT_INTERCEPTOR, boundAddress -> new DiscoveryNode(nodeId, nodeId, boundAddress.publishAddress(), emptyMap(), nodeRoles, version), null);
    transportService.start();
    transportService.acceptIncomingRequests();
    final ConcurrentMap<TransportAddress, AtomicInteger> counters = ConcurrentCollections.newConcurrentMap();
    transportService.addTracer(new MockTransportService.Tracer() {

        @Override
        public void requestSent(DiscoveryNode node, long requestId, String action, TransportRequestOptions options) {
            counters.computeIfAbsent(node.getAddress(), k -> new AtomicInteger());
            counters.get(node.getAddress()).incrementAndGet();
        }
    });
    return new NetworkHandle(transport.boundAddress().publishAddress(), transportService, transportService.getLocalNode(), counters);
}
Also used : Arrays(java.util.Arrays) BigArrays(org.elasticsearch.common.util.BigArrays) ConcurrentCollections(org.elasticsearch.common.util.concurrent.ConcurrentCollections) BiFunction(java.util.function.BiFunction) ClusterBlocks(org.elasticsearch.cluster.block.ClusterBlocks) InetAddress(java.net.InetAddress) STATE_NOT_RECOVERED_BLOCK(org.elasticsearch.gateway.GatewayService.STATE_NOT_RECOVERED_BLOCK) ClusterState(org.elasticsearch.cluster.ClusterState) ConnectTransportException(org.elasticsearch.transport.ConnectTransportException) Settings(org.elasticsearch.common.settings.Settings) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) Matchers.eq(org.mockito.Matchers.eq) After(org.junit.After) Map(java.util.Map) ThreadPool(org.elasticsearch.threadpool.ThreadPool) ClusterName(org.elasticsearch.cluster.ClusterName) Role(org.elasticsearch.cluster.node.DiscoveryNode.Role) ThreadFactory(java.util.concurrent.ThreadFactory) EnumSet(java.util.EnumSet) Transport(org.elasticsearch.transport.Transport) Collection(java.util.Collection) MockTcpTransport(org.elasticsearch.transport.MockTcpTransport) Set(java.util.Set) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) CountDownLatch(java.util.concurrent.CountDownLatch) AbstractRunnable(org.elasticsearch.common.util.concurrent.AbstractRunnable) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Version(org.elasticsearch.Version) TransportAddress(org.elasticsearch.common.transport.TransportAddress) TransportConnectionListener(org.elasticsearch.transport.TransportConnectionListener) TransportSettings(org.elasticsearch.transport.TransportSettings) Matchers.equalTo(org.hamcrest.Matchers.equalTo) TransportResponseHandler(org.elasticsearch.transport.TransportResponseHandler) TransportRequestOptions(org.elasticsearch.transport.TransportRequestOptions) TransportException(org.elasticsearch.transport.TransportException) NetworkAddress(org.elasticsearch.common.network.NetworkAddress) Mockito.mock(org.mockito.Mockito.mock) IntStream(java.util.stream.IntStream) Matchers(org.mockito.Matchers) HashMap(java.util.HashMap) BoundTransportAddress(org.elasticsearch.common.transport.BoundTransportAddress) AtomicReference(java.util.concurrent.atomic.AtomicReference) CheckedBiConsumer(org.elasticsearch.common.CheckedBiConsumer) Stack(java.util.Stack) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) HashSet(java.util.HashSet) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) NetworkService(org.elasticsearch.common.network.NetworkService) NoneCircuitBreakerService(org.elasticsearch.indices.breaker.NoneCircuitBreakerService) NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) TimeValue(org.elasticsearch.common.unit.TimeValue) Matchers.hasSize(org.hamcrest.Matchers.hasSize) ESTestCase(org.elasticsearch.test.ESTestCase) MockTransportService(org.elasticsearch.test.transport.MockTransportService) TransportService(org.elasticsearch.transport.TransportService) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) ConnectionProfile(org.elasticsearch.transport.ConnectionProfile) Collections.emptyMap(java.util.Collections.emptyMap) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) Matchers.empty(org.hamcrest.Matchers.empty) EsExecutors(org.elasticsearch.common.util.concurrent.EsExecutors) Collections.emptySet(java.util.Collections.emptySet) IOUtils(org.apache.lucene.util.IOUtils) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) VersionUtils(org.elasticsearch.test.VersionUtils) Mockito.verify(org.mockito.Mockito.verify) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Closeable(java.io.Closeable) Collections(java.util.Collections) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) MockTransportService(org.elasticsearch.test.transport.MockTransportService) TransportAddress(org.elasticsearch.common.transport.TransportAddress) BoundTransportAddress(org.elasticsearch.common.transport.BoundTransportAddress) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TransportRequestOptions(org.elasticsearch.transport.TransportRequestOptions) Transport(org.elasticsearch.transport.Transport) MockTcpTransport(org.elasticsearch.transport.MockTcpTransport) Settings(org.elasticsearch.common.settings.Settings) TransportSettings(org.elasticsearch.transport.TransportSettings)

Example 25 with BiFunction

use of java.util.function.BiFunction in project elasticsearch by elastic.

the class UnicastZenPingTests method testUnknownHostNotCached.

public void testUnknownHostNotCached() throws ExecutionException, InterruptedException {
    // use ephemeral ports
    final Settings settings = Settings.builder().put("cluster.name", "test").put(TransportSettings.PORT.getKey(), 0).build();
    final NetworkService networkService = new NetworkService(settings, Collections.emptyList());
    final Map<String, TransportAddress[]> addresses = new HashMap<>();
    final BiFunction<Settings, Version, Transport> supplier = (s, v) -> new MockTcpTransport(s, threadPool, BigArrays.NON_RECYCLING_INSTANCE, new NoneCircuitBreakerService(), new NamedWriteableRegistry(Collections.emptyList()), networkService, v) {

        @Override
        public TransportAddress[] addressesFromString(String address, int perAddressLimit) throws UnknownHostException {
            final TransportAddress[] transportAddresses = addresses.get(address);
            if (transportAddresses == null) {
                throw new UnknownHostException(address);
            } else {
                return transportAddresses;
            }
        }
    };
    final NetworkHandle handleA = startServices(settings, threadPool, "UZP_A", Version.CURRENT, supplier);
    closeables.push(handleA.transportService);
    final NetworkHandle handleB = startServices(settings, threadPool, "UZP_B", Version.CURRENT, supplier);
    closeables.push(handleB.transportService);
    final NetworkHandle handleC = startServices(settings, threadPool, "UZP_C", Version.CURRENT, supplier);
    closeables.push(handleC.transportService);
    addresses.put("UZP_A", new TransportAddress[] { new TransportAddress(new InetSocketAddress(handleA.address.address().getAddress(), handleA.address.address().getPort())) });
    addresses.put("UZP_C", new TransportAddress[] { new TransportAddress(new InetSocketAddress(handleC.address.address().getAddress(), handleC.address.address().getPort())) });
    final Settings hostsSettings = Settings.builder().putArray("discovery.zen.ping.unicast.hosts", "UZP_A", "UZP_B", "UZP_C").put("cluster.name", "test").build();
    final ClusterState state = ClusterState.builder(new ClusterName("test")).version(randomNonNegativeLong()).build();
    final TestUnicastZenPing zenPingA = new TestUnicastZenPing(hostsSettings, threadPool, handleA, EMPTY_HOSTS_PROVIDER);
    zenPingA.start(new PingContextProvider() {

        @Override
        public DiscoveryNodes nodes() {
            return DiscoveryNodes.builder().add(handleA.node).localNodeId("UZP_A").build();
        }

        @Override
        public ClusterState clusterState() {
            return ClusterState.builder(state).blocks(ClusterBlocks.builder().addGlobalBlock(STATE_NOT_RECOVERED_BLOCK)).build();
        }
    });
    closeables.push(zenPingA);
    TestUnicastZenPing zenPingB = new TestUnicastZenPing(hostsSettings, threadPool, handleB, EMPTY_HOSTS_PROVIDER);
    zenPingB.start(new PingContextProvider() {

        @Override
        public DiscoveryNodes nodes() {
            return DiscoveryNodes.builder().add(handleB.node).localNodeId("UZP_B").build();
        }

        @Override
        public ClusterState clusterState() {
            return state;
        }
    });
    closeables.push(zenPingB);
    TestUnicastZenPing zenPingC = new TestUnicastZenPing(hostsSettings, threadPool, handleC, EMPTY_HOSTS_PROVIDER);
    zenPingC.start(new PingContextProvider() {

        @Override
        public DiscoveryNodes nodes() {
            return DiscoveryNodes.builder().add(handleC.node).localNodeId("UZP_C").build();
        }

        @Override
        public ClusterState clusterState() {
            return state;
        }
    });
    closeables.push(zenPingC);
    // the presence of an unresolvable host should not prevent resolvable hosts from being pinged
    {
        final Collection<ZenPing.PingResponse> pingResponses = zenPingA.pingAndWait().toList();
        assertThat(pingResponses.size(), equalTo(1));
        ZenPing.PingResponse ping = pingResponses.iterator().next();
        assertThat(ping.node().getId(), equalTo("UZP_C"));
        assertThat(ping.getClusterStateVersion(), equalTo(state.version()));
        assertPingCount(handleA, handleB, 0);
        assertPingCount(handleA, handleC, 3);
        assertNull(handleA.counters.get(handleB.address));
    }
    final HashMap<TransportAddress, Integer> moreThan = new HashMap<>();
    // we should see at least one ping to UZP_B, and one more ping than we have already seen to UZP_C
    moreThan.put(handleB.address, 0);
    moreThan.put(handleC.address, handleA.counters.get(handleC.address).intValue());
    // now allow UZP_B to be resolvable
    addresses.put("UZP_B", new TransportAddress[] { new TransportAddress(new InetSocketAddress(handleB.address.address().getAddress(), handleB.address.address().getPort())) });
    // now we should see pings to UZP_B; this establishes that host resolutions are not cached
    {
        handleA.counters.clear();
        final Collection<ZenPing.PingResponse> secondPingResponses = zenPingA.pingAndWait().toList();
        assertThat(secondPingResponses.size(), equalTo(2));
        final Set<String> ids = new HashSet<>(secondPingResponses.stream().map(p -> p.node().getId()).collect(Collectors.toList()));
        assertThat(ids, equalTo(new HashSet<>(Arrays.asList("UZP_B", "UZP_C"))));
        assertPingCount(handleA, handleB, 3);
        assertPingCount(handleA, handleC, 3);
    }
}
Also used : Arrays(java.util.Arrays) BigArrays(org.elasticsearch.common.util.BigArrays) ConcurrentCollections(org.elasticsearch.common.util.concurrent.ConcurrentCollections) BiFunction(java.util.function.BiFunction) ClusterBlocks(org.elasticsearch.cluster.block.ClusterBlocks) InetAddress(java.net.InetAddress) STATE_NOT_RECOVERED_BLOCK(org.elasticsearch.gateway.GatewayService.STATE_NOT_RECOVERED_BLOCK) ClusterState(org.elasticsearch.cluster.ClusterState) ConnectTransportException(org.elasticsearch.transport.ConnectTransportException) Settings(org.elasticsearch.common.settings.Settings) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) Matchers.eq(org.mockito.Matchers.eq) After(org.junit.After) Map(java.util.Map) ThreadPool(org.elasticsearch.threadpool.ThreadPool) ClusterName(org.elasticsearch.cluster.ClusterName) Role(org.elasticsearch.cluster.node.DiscoveryNode.Role) ThreadFactory(java.util.concurrent.ThreadFactory) EnumSet(java.util.EnumSet) Transport(org.elasticsearch.transport.Transport) Collection(java.util.Collection) MockTcpTransport(org.elasticsearch.transport.MockTcpTransport) Set(java.util.Set) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) CountDownLatch(java.util.concurrent.CountDownLatch) AbstractRunnable(org.elasticsearch.common.util.concurrent.AbstractRunnable) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Version(org.elasticsearch.Version) TransportAddress(org.elasticsearch.common.transport.TransportAddress) TransportConnectionListener(org.elasticsearch.transport.TransportConnectionListener) TransportSettings(org.elasticsearch.transport.TransportSettings) Matchers.equalTo(org.hamcrest.Matchers.equalTo) TransportResponseHandler(org.elasticsearch.transport.TransportResponseHandler) TransportRequestOptions(org.elasticsearch.transport.TransportRequestOptions) TransportException(org.elasticsearch.transport.TransportException) NetworkAddress(org.elasticsearch.common.network.NetworkAddress) Mockito.mock(org.mockito.Mockito.mock) IntStream(java.util.stream.IntStream) Matchers(org.mockito.Matchers) HashMap(java.util.HashMap) BoundTransportAddress(org.elasticsearch.common.transport.BoundTransportAddress) AtomicReference(java.util.concurrent.atomic.AtomicReference) CheckedBiConsumer(org.elasticsearch.common.CheckedBiConsumer) Stack(java.util.Stack) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) HashSet(java.util.HashSet) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) NetworkService(org.elasticsearch.common.network.NetworkService) NoneCircuitBreakerService(org.elasticsearch.indices.breaker.NoneCircuitBreakerService) NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) TimeValue(org.elasticsearch.common.unit.TimeValue) Matchers.hasSize(org.hamcrest.Matchers.hasSize) ESTestCase(org.elasticsearch.test.ESTestCase) MockTransportService(org.elasticsearch.test.transport.MockTransportService) TransportService(org.elasticsearch.transport.TransportService) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) ConnectionProfile(org.elasticsearch.transport.ConnectionProfile) Collections.emptyMap(java.util.Collections.emptyMap) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) Matchers.empty(org.hamcrest.Matchers.empty) EsExecutors(org.elasticsearch.common.util.concurrent.EsExecutors) Collections.emptySet(java.util.Collections.emptySet) IOUtils(org.apache.lucene.util.IOUtils) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) VersionUtils(org.elasticsearch.test.VersionUtils) Mockito.verify(org.mockito.Mockito.verify) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Closeable(java.io.Closeable) Collections(java.util.Collections) NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) EnumSet(java.util.EnumSet) Set(java.util.Set) HashSet(java.util.HashSet) Collections.emptySet(java.util.Collections.emptySet) HashMap(java.util.HashMap) TransportAddress(org.elasticsearch.common.transport.TransportAddress) BoundTransportAddress(org.elasticsearch.common.transport.BoundTransportAddress) InetSocketAddress(java.net.InetSocketAddress) MockTcpTransport(org.elasticsearch.transport.MockTcpTransport) Version(org.elasticsearch.Version) ClusterName(org.elasticsearch.cluster.ClusterName) Settings(org.elasticsearch.common.settings.Settings) TransportSettings(org.elasticsearch.transport.TransportSettings) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) ClusterState(org.elasticsearch.cluster.ClusterState) UnknownHostException(java.net.UnknownHostException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) NetworkService(org.elasticsearch.common.network.NetworkService) Collection(java.util.Collection) Transport(org.elasticsearch.transport.Transport) MockTcpTransport(org.elasticsearch.transport.MockTcpTransport) NoneCircuitBreakerService(org.elasticsearch.indices.breaker.NoneCircuitBreakerService)

Aggregations

BiFunction (java.util.function.BiFunction)43 HashMap (java.util.HashMap)22 List (java.util.List)22 Map (java.util.Map)22 ArrayList (java.util.ArrayList)18 Test (org.junit.Test)17 Collectors (java.util.stream.Collectors)15 Collections (java.util.Collections)14 Set (java.util.Set)13 Function (java.util.function.Function)13 Arrays (java.util.Arrays)12 Mockito.mock (org.mockito.Mockito.mock)12 IOException (java.io.IOException)11 Collection (java.util.Collection)11 IntStream (java.util.stream.IntStream)11 Before (org.junit.Before)11 Logger (org.apache.logging.log4j.Logger)8 Config (org.apache.samza.config.Config)8 JobConfig (org.apache.samza.config.JobConfig)8 ApplicationRunner (org.apache.samza.runtime.ApplicationRunner)8