Search in sources :

Example 81 with Stream

use of java.util.stream.Stream in project che by eclipse.

the class OpenShiftConnector method createContainerInfo.

/**
     * Collects the relevant information from a Service, an ImageInfo, and a Pod into
     * a docker ContainerInfo JSON object. The returned object is what would be returned
     * by executing {@code docker inspect <container>}, with fields filled as available.
     * @param svc
     * @param imageInfo
     * @param pod
     * @param containerId
     * @return
     */
private ContainerInfo createContainerInfo(Service svc, ImageInfo imageInfo, Pod pod, String containerId) {
    // In Che on OpenShift, we only have one container per pod.
    Container container = pod.getSpec().getContainers().get(0);
    ContainerConfig imageContainerConfig = imageInfo.getContainerConfig();
    // HostConfig
    HostConfig hostConfig = new HostConfig();
    hostConfig.setBinds(new String[0]);
    hostConfig.setMemory(imageInfo.getConfig().getMemory());
    // Env vars
    List<String> imageEnv = Arrays.asList(imageContainerConfig.getEnv());
    List<String> containerEnv = container.getEnv().stream().map(e -> String.format("%s=%s", e.getName(), e.getValue())).collect(Collectors.toList());
    String[] env = Stream.concat(imageEnv.stream(), containerEnv.stream()).toArray(String[]::new);
    // Exposed Ports
    Map<String, List<PortBinding>> ports = getCheServicePorts(svc);
    Map<String, Map<String, String>> exposedPorts = new HashMap<>();
    for (String key : ports.keySet()) {
        exposedPorts.put(key, Collections.emptyMap());
    }
    // Labels
    Map<String, String> annotations = KubernetesLabelConverter.namesToLabels(svc.getMetadata().getAnnotations());
    Map<String, String> containerLabels = imageInfo.getConfig().getLabels();
    Map<String, String> labels = Stream.concat(annotations.entrySet().stream(), containerLabels.entrySet().stream()).filter(e -> e.getKey().startsWith(KubernetesLabelConverter.getCheServerLabelPrefix())).collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
    // ContainerConfig
    ContainerConfig config = imageContainerConfig;
    config.setHostname(svc.getMetadata().getName());
    config.setEnv(env);
    config.setExposedPorts(exposedPorts);
    config.setLabels(labels);
    config.setImage(container.getImage());
    // NetworkSettings
    NetworkSettings networkSettings = new NetworkSettings();
    networkSettings.setIpAddress(svc.getSpec().getClusterIP());
    networkSettings.setGateway(svc.getSpec().getClusterIP());
    networkSettings.setPorts(ports);
    // Make final ContainerInfo
    ContainerInfo info = new ContainerInfo();
    info.setId(containerId);
    info.setConfig(config);
    info.setNetworkSettings(networkSettings);
    info.setHostConfig(hostConfig);
    info.setImage(imageInfo.getConfig().getImage());
    return info;
}
Also used : VolumeMount(io.fabric8.kubernetes.api.model.VolumeMount) Arrays(java.util.Arrays) RemoveContainerParams(org.eclipse.che.plugin.docker.client.params.RemoveContainerParams) HostConfig(org.eclipse.che.plugin.docker.client.json.HostConfig) Deployment(io.fabric8.kubernetes.api.model.extensions.Deployment) LoggerFactory(org.slf4j.LoggerFactory) MessageProcessor(org.eclipse.che.plugin.docker.client.MessageProcessor) IpamConfig(org.eclipse.che.plugin.docker.client.json.network.IpamConfig) KubernetesContainer(org.eclipse.che.plugin.openshift.client.kubernetes.KubernetesContainer) ServicePort(io.fabric8.kubernetes.api.model.ServicePort) ContainerListEntry(org.eclipse.che.plugin.docker.client.json.ContainerListEntry) DefaultOpenShiftClient(io.fabric8.openshift.client.DefaultOpenShiftClient) VolumeMountBuilder(io.fabric8.kubernetes.api.model.VolumeMountBuilder) DockerRegistryAuthResolver(org.eclipse.che.plugin.docker.client.DockerRegistryAuthResolver) Filters(org.eclipse.che.plugin.docker.client.json.Filters) Map(java.util.Map) NetworkSettings(org.eclipse.che.plugin.docker.client.json.NetworkSettings) ContainerBuilder(io.fabric8.kubernetes.api.model.ContainerBuilder) DockerConnectionFactory(org.eclipse.che.plugin.docker.client.connection.DockerConnectionFactory) ImageStreamTag(io.fabric8.openshift.api.model.ImageStreamTag) ImageInfo(org.eclipse.che.plugin.docker.client.json.ImageInfo) InspectImageParams(org.eclipse.che.plugin.docker.client.params.InspectImageParams) Set(java.util.Set) OpenShiftException(org.eclipse.che.plugin.openshift.client.exception.OpenShiftException) VolumeBuilder(io.fabric8.kubernetes.api.model.VolumeBuilder) Collectors(java.util.stream.Collectors) GetNetworksParams(org.eclipse.che.plugin.docker.client.params.network.GetNetworksParams) KubernetesService(org.eclipse.che.plugin.openshift.client.kubernetes.KubernetesService) ConnectContainerToNetworkParams(org.eclipse.che.plugin.docker.client.params.network.ConnectContainerToNetworkParams) List(java.util.List) Network(org.eclipse.che.plugin.docker.client.json.network.Network) Stream(java.util.stream.Stream) CommitParams(org.eclipse.che.plugin.docker.client.params.CommitParams) ContainerConfig(org.eclipse.che.plugin.docker.client.json.ContainerConfig) GetEventsParams(org.eclipse.che.plugin.docker.client.params.GetEventsParams) DeploymentBuilder(io.fabric8.kubernetes.api.model.extensions.DeploymentBuilder) ImageConfig(org.eclipse.che.plugin.docker.client.json.ImageConfig) TagParams(org.eclipse.che.plugin.docker.client.params.TagParams) CreateContainerParams(org.eclipse.che.plugin.docker.client.params.CreateContainerParams) ServiceList(io.fabric8.kubernetes.api.model.ServiceList) DockerApiVersionPathPrefixProvider(org.eclipse.che.plugin.docker.client.DockerApiVersionPathPrefixProvider) ProbeBuilder(io.fabric8.kubernetes.api.model.ProbeBuilder) Ipam(org.eclipse.che.plugin.docker.client.json.network.Ipam) PullParams(org.eclipse.che.plugin.docker.client.params.PullParams) DockerConnectorConfiguration(org.eclipse.che.plugin.docker.client.DockerConnectorConfiguration) ImageNotFoundException(org.eclipse.che.plugin.docker.client.exception.ImageNotFoundException) Container(io.fabric8.kubernetes.api.model.Container) PutResourceParams(org.eclipse.che.plugin.docker.client.params.PutResourceParams) StopContainerParams(org.eclipse.che.plugin.docker.client.params.StopContainerParams) Strings.isNullOrEmpty(com.google.common.base.Strings.isNullOrEmpty) HashMap(java.util.HashMap) ContainerCreated(org.eclipse.che.plugin.docker.client.json.ContainerCreated) Singleton(javax.inject.Singleton) StartContainerParams(org.eclipse.che.plugin.docker.client.params.StartContainerParams) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Inject(javax.inject.Inject) RemoveImageParams(org.eclipse.che.plugin.docker.client.params.RemoveImageParams) InspectNetworkParams(org.eclipse.che.plugin.docker.client.params.network.InspectNetworkParams) ProgressMonitor(org.eclipse.che.plugin.docker.client.ProgressMonitor) KubernetesEnvVar(org.eclipse.che.plugin.openshift.client.kubernetes.KubernetesEnvVar) CreateNetworkParams(org.eclipse.che.plugin.docker.client.params.network.CreateNetworkParams) PodSpecBuilder(io.fabric8.kubernetes.api.model.PodSpecBuilder) PortBinding(org.eclipse.che.plugin.docker.client.json.PortBinding) PodSpec(io.fabric8.kubernetes.api.model.PodSpec) Named(javax.inject.Named) ContainerInfo(org.eclipse.che.plugin.docker.client.json.ContainerInfo) Service(io.fabric8.kubernetes.api.model.Service) DisconnectContainerFromNetworkParams(org.eclipse.che.plugin.docker.client.params.network.DisconnectContainerFromNetworkParams) KillContainerParams(org.eclipse.che.plugin.docker.client.params.KillContainerParams) Volume(io.fabric8.kubernetes.api.model.Volume) ImageStream(io.fabric8.openshift.api.model.ImageStream) Probe(io.fabric8.kubernetes.api.model.Probe) GetResourceParams(org.eclipse.che.plugin.docker.client.params.GetResourceParams) Logger(org.slf4j.Logger) Pod(io.fabric8.kubernetes.api.model.Pod) IOException(java.io.IOException) Event(org.eclipse.che.plugin.docker.client.json.Event) KubernetesLabelConverter(org.eclipse.che.plugin.openshift.client.kubernetes.KubernetesLabelConverter) RemoveNetworkParams(org.eclipse.che.plugin.docker.client.params.RemoveNetworkParams) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) NetworkCreated(org.eclipse.che.plugin.docker.client.json.NetworkCreated) ContainerInNetwork(org.eclipse.che.plugin.docker.client.json.network.ContainerInNetwork) PodList(io.fabric8.kubernetes.api.model.PodList) DockerConnector(org.eclipse.che.plugin.docker.client.DockerConnector) KubernetesStringUtils(org.eclipse.che.plugin.openshift.client.kubernetes.KubernetesStringUtils) Collections(java.util.Collections) InputStream(java.io.InputStream) HashMap(java.util.HashMap) ContainerConfig(org.eclipse.che.plugin.docker.client.json.ContainerConfig) KubernetesContainer(org.eclipse.che.plugin.openshift.client.kubernetes.KubernetesContainer) Container(io.fabric8.kubernetes.api.model.Container) NetworkSettings(org.eclipse.che.plugin.docker.client.json.NetworkSettings) HostConfig(org.eclipse.che.plugin.docker.client.json.HostConfig) ContainerInfo(org.eclipse.che.plugin.docker.client.json.ContainerInfo) List(java.util.List) ServiceList(io.fabric8.kubernetes.api.model.ServiceList) ArrayList(java.util.ArrayList) PodList(io.fabric8.kubernetes.api.model.PodList) Map(java.util.Map) HashMap(java.util.HashMap)

Example 82 with Stream

use of java.util.stream.Stream in project che by eclipse.

the class MachineProviderImplTest method shouldAddEnvVarsFromMachineConfigToContainerOnDevInstanceCreationFromRecipe.

@Test
public void shouldAddEnvVarsFromMachineConfigToContainerOnDevInstanceCreationFromRecipe() throws Exception {
    // given
    Map<String, String> envVarsFromConfig = new HashMap<>();
    envVarsFromConfig.put("ENV_VAR1", "123");
    envVarsFromConfig.put("ENV_VAR2", "234");
    final boolean isDev = true;
    CheServiceImpl machine = createService();
    machine.setEnvironment(envVarsFromConfig);
    // when
    createInstanceFromRecipe(machine, isDev);
    // then
    ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class);
    verify(dockerConnector).createContainer(argumentCaptor.capture());
    assertTrue(asList(argumentCaptor.getValue().getContainerConfig().getEnv()).containsAll(envVarsFromConfig.entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue()).collect(Collectors.toList())));
}
Also used : RemoveContainerParams(org.eclipse.che.plugin.docker.client.params.RemoveContainerParams) Arrays(java.util.Arrays) Listeners(org.testng.annotations.Listeners) InspectContainerParams(org.eclipse.che.plugin.docker.client.params.InspectContainerParams) DockerConnectorProvider(org.eclipse.che.plugin.docker.client.DockerConnectorProvider) Volume(org.eclipse.che.plugin.docker.client.json.Volume) Test(org.testng.annotations.Test) AfterMethod(org.testng.annotations.AfterMethod) DOCKER_FILE_TYPE(org.eclipse.che.plugin.docker.machine.DockerInstanceProvider.DOCKER_FILE_TYPE) Mockito.doThrow(org.mockito.Mockito.doThrow) Collections.singleton(java.util.Collections.singleton) Collectors.toMap(java.util.stream.Collectors.toMap) Arrays.asList(java.util.Arrays.asList) Matchers.eq(org.mockito.Matchers.eq) Map(java.util.Map) Assert.assertFalse(org.testng.Assert.assertFalse) MockitoTestNGListener(org.mockito.testng.MockitoTestNGListener) MachineConfig(org.eclipse.che.api.core.model.machine.MachineConfig) BeforeMethod(org.testng.annotations.BeforeMethod) RecipeRetriever(org.eclipse.che.api.machine.server.util.RecipeRetriever) Set(java.util.Set) Collectors(java.util.stream.Collectors) WindowsPathEscaper(org.eclipse.che.commons.lang.os.WindowsPathEscaper) MACHINE_SNAPSHOT_PREFIX(org.eclipse.che.plugin.docker.machine.DockerInstanceProvider.MACHINE_SNAPSHOT_PREFIX) Matchers.any(org.mockito.Matchers.any) List(java.util.List) Stream(java.util.stream.Stream) ContainerConfig(org.eclipse.che.plugin.docker.client.json.ContainerConfig) TagParams(org.eclipse.che.plugin.docker.client.params.TagParams) ServerConfImpl(org.eclipse.che.api.machine.server.model.impl.ServerConfImpl) CreateContainerParams(org.eclipse.che.plugin.docker.client.params.CreateContainerParams) SubjectImpl(org.eclipse.che.commons.subject.SubjectImpl) UserSpecificDockerRegistryCredentialsProvider(org.eclipse.che.plugin.docker.client.UserSpecificDockerRegistryCredentialsProvider) CheServiceImpl(org.eclipse.che.api.environment.server.model.CheServiceImpl) PullParams(org.eclipse.che.plugin.docker.client.params.PullParams) DockerConnectorConfiguration(org.eclipse.che.plugin.docker.client.DockerConnectorConfiguration) DataProvider(org.testng.annotations.DataProvider) Mock(org.mockito.Mock) LineConsumer(org.eclipse.che.api.core.util.LineConsumer) RecipeImpl(org.eclipse.che.api.machine.server.recipe.RecipeImpl) Assert.assertEquals(org.testng.Assert.assertEquals) HashMap(java.util.HashMap) ContainerCreated(org.eclipse.che.plugin.docker.client.json.ContainerCreated) Mockito.spy(org.mockito.Mockito.spy) Function(java.util.function.Function) StartContainerParams(org.eclipse.che.plugin.docker.client.params.StartContainerParams) Matchers.anyString(org.mockito.Matchers.anyString) ArrayList(java.util.ArrayList) RemoveImageParams(org.eclipse.che.plugin.docker.client.params.RemoveImageParams) HashSet(java.util.HashSet) EnvironmentContext(org.eclipse.che.commons.env.EnvironmentContext) ProgressMonitor(org.eclipse.che.plugin.docker.client.ProgressMonitor) ArgumentCaptor(org.mockito.ArgumentCaptor) ContainerState(org.eclipse.che.plugin.docker.client.json.ContainerState) Collections.singletonMap(java.util.Collections.singletonMap) ContainerInfo(org.eclipse.che.plugin.docker.client.json.ContainerInfo) Collections.emptySet(java.util.Collections.emptySet) DockerNode(org.eclipse.che.plugin.docker.machine.node.DockerNode) ServerConf(org.eclipse.che.api.core.model.machine.ServerConf) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) Machine(org.eclipse.che.api.core.model.machine.Machine) Mockito.never(org.mockito.Mockito.never) ServerException(org.eclipse.che.api.core.ServerException) DockerConnector(org.eclipse.che.plugin.docker.client.DockerConnector) Assert.assertTrue(org.testng.Assert.assertTrue) Collections(java.util.Collections) Assert.assertEqualsNoOrder(org.testng.Assert.assertEqualsNoOrder) HashMap(java.util.HashMap) CheServiceImpl(org.eclipse.che.api.environment.server.model.CheServiceImpl) CreateContainerParams(org.eclipse.che.plugin.docker.client.params.CreateContainerParams) Matchers.anyString(org.mockito.Matchers.anyString) Test(org.testng.annotations.Test)

Example 83 with Stream

use of java.util.stream.Stream in project che by eclipse.

the class MachineProviderImplTest method shouldAddEnvVarsFromMachineConfigToContainerOnNonDevInstanceCreationFromSnapshot.

@Test
public void shouldAddEnvVarsFromMachineConfigToContainerOnNonDevInstanceCreationFromSnapshot() throws Exception {
    // given
    Map<String, String> envVarsFromConfig = new HashMap<>();
    envVarsFromConfig.put("ENV_VAR1", "123");
    envVarsFromConfig.put("ENV_VAR2", "234");
    final boolean isDev = false;
    CheServiceImpl machine = createService();
    machine.setEnvironment(envVarsFromConfig);
    // when
    createInstanceFromSnapshot(machine, isDev);
    // then
    ArgumentCaptor<CreateContainerParams> argumentCaptor = ArgumentCaptor.forClass(CreateContainerParams.class);
    verify(dockerConnector).createContainer(argumentCaptor.capture());
    assertTrue(asList(argumentCaptor.getValue().getContainerConfig().getEnv()).containsAll(envVarsFromConfig.entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue()).collect(Collectors.toList())));
}
Also used : RemoveContainerParams(org.eclipse.che.plugin.docker.client.params.RemoveContainerParams) Arrays(java.util.Arrays) Listeners(org.testng.annotations.Listeners) InspectContainerParams(org.eclipse.che.plugin.docker.client.params.InspectContainerParams) DockerConnectorProvider(org.eclipse.che.plugin.docker.client.DockerConnectorProvider) Volume(org.eclipse.che.plugin.docker.client.json.Volume) Test(org.testng.annotations.Test) AfterMethod(org.testng.annotations.AfterMethod) DOCKER_FILE_TYPE(org.eclipse.che.plugin.docker.machine.DockerInstanceProvider.DOCKER_FILE_TYPE) Mockito.doThrow(org.mockito.Mockito.doThrow) Collections.singleton(java.util.Collections.singleton) Collectors.toMap(java.util.stream.Collectors.toMap) Arrays.asList(java.util.Arrays.asList) Matchers.eq(org.mockito.Matchers.eq) Map(java.util.Map) Assert.assertFalse(org.testng.Assert.assertFalse) MockitoTestNGListener(org.mockito.testng.MockitoTestNGListener) MachineConfig(org.eclipse.che.api.core.model.machine.MachineConfig) BeforeMethod(org.testng.annotations.BeforeMethod) RecipeRetriever(org.eclipse.che.api.machine.server.util.RecipeRetriever) Set(java.util.Set) Collectors(java.util.stream.Collectors) WindowsPathEscaper(org.eclipse.che.commons.lang.os.WindowsPathEscaper) MACHINE_SNAPSHOT_PREFIX(org.eclipse.che.plugin.docker.machine.DockerInstanceProvider.MACHINE_SNAPSHOT_PREFIX) Matchers.any(org.mockito.Matchers.any) List(java.util.List) Stream(java.util.stream.Stream) ContainerConfig(org.eclipse.che.plugin.docker.client.json.ContainerConfig) TagParams(org.eclipse.che.plugin.docker.client.params.TagParams) ServerConfImpl(org.eclipse.che.api.machine.server.model.impl.ServerConfImpl) CreateContainerParams(org.eclipse.che.plugin.docker.client.params.CreateContainerParams) SubjectImpl(org.eclipse.che.commons.subject.SubjectImpl) UserSpecificDockerRegistryCredentialsProvider(org.eclipse.che.plugin.docker.client.UserSpecificDockerRegistryCredentialsProvider) CheServiceImpl(org.eclipse.che.api.environment.server.model.CheServiceImpl) PullParams(org.eclipse.che.plugin.docker.client.params.PullParams) DockerConnectorConfiguration(org.eclipse.che.plugin.docker.client.DockerConnectorConfiguration) DataProvider(org.testng.annotations.DataProvider) Mock(org.mockito.Mock) LineConsumer(org.eclipse.che.api.core.util.LineConsumer) RecipeImpl(org.eclipse.che.api.machine.server.recipe.RecipeImpl) Assert.assertEquals(org.testng.Assert.assertEquals) HashMap(java.util.HashMap) ContainerCreated(org.eclipse.che.plugin.docker.client.json.ContainerCreated) Mockito.spy(org.mockito.Mockito.spy) Function(java.util.function.Function) StartContainerParams(org.eclipse.che.plugin.docker.client.params.StartContainerParams) Matchers.anyString(org.mockito.Matchers.anyString) ArrayList(java.util.ArrayList) RemoveImageParams(org.eclipse.che.plugin.docker.client.params.RemoveImageParams) HashSet(java.util.HashSet) EnvironmentContext(org.eclipse.che.commons.env.EnvironmentContext) ProgressMonitor(org.eclipse.che.plugin.docker.client.ProgressMonitor) ArgumentCaptor(org.mockito.ArgumentCaptor) ContainerState(org.eclipse.che.plugin.docker.client.json.ContainerState) Collections.singletonMap(java.util.Collections.singletonMap) ContainerInfo(org.eclipse.che.plugin.docker.client.json.ContainerInfo) Collections.emptySet(java.util.Collections.emptySet) DockerNode(org.eclipse.che.plugin.docker.machine.node.DockerNode) ServerConf(org.eclipse.che.api.core.model.machine.ServerConf) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) Machine(org.eclipse.che.api.core.model.machine.Machine) Mockito.never(org.mockito.Mockito.never) ServerException(org.eclipse.che.api.core.ServerException) DockerConnector(org.eclipse.che.plugin.docker.client.DockerConnector) Assert.assertTrue(org.testng.Assert.assertTrue) Collections(java.util.Collections) Assert.assertEqualsNoOrder(org.testng.Assert.assertEqualsNoOrder) HashMap(java.util.HashMap) CheServiceImpl(org.eclipse.che.api.environment.server.model.CheServiceImpl) CreateContainerParams(org.eclipse.che.plugin.docker.client.params.CreateContainerParams) Matchers.anyString(org.mockito.Matchers.anyString) Test(org.testng.annotations.Test)

Example 84 with Stream

use of java.util.stream.Stream in project elasticsearch by elastic.

the class TransportClient method buildTemplate.

private static ClientTemplate buildTemplate(Settings providedSettings, Settings defaultSettings, Collection<Class<? extends Plugin>> plugins, HostFailureListener failureListner) {
    if (Node.NODE_NAME_SETTING.exists(providedSettings) == false) {
        providedSettings = Settings.builder().put(providedSettings).put(Node.NODE_NAME_SETTING.getKey(), "_client_").build();
    }
    final PluginsService pluginsService = newPluginService(providedSettings, plugins);
    final Settings settings = Settings.builder().put(defaultSettings).put(pluginsService.updatedSettings()).build();
    final List<Closeable> resourcesToClose = new ArrayList<>();
    final ThreadPool threadPool = new ThreadPool(settings);
    resourcesToClose.add(() -> ThreadPool.terminate(threadPool, 10, TimeUnit.SECONDS));
    final NetworkService networkService = new NetworkService(settings, Collections.emptyList());
    try {
        final List<Setting<?>> additionalSettings = new ArrayList<>();
        final List<String> additionalSettingsFilter = new ArrayList<>();
        additionalSettings.addAll(pluginsService.getPluginSettings());
        additionalSettingsFilter.addAll(pluginsService.getPluginSettingsFilter());
        for (final ExecutorBuilder<?> builder : threadPool.builders()) {
            additionalSettings.addAll(builder.getRegisteredSettings());
        }
        SettingsModule settingsModule = new SettingsModule(settings, additionalSettings, additionalSettingsFilter);
        SearchModule searchModule = new SearchModule(settings, true, pluginsService.filterPlugins(SearchPlugin.class));
        List<NamedWriteableRegistry.Entry> entries = new ArrayList<>();
        entries.addAll(NetworkModule.getNamedWriteables());
        entries.addAll(searchModule.getNamedWriteables());
        entries.addAll(ClusterModule.getNamedWriteables());
        entries.addAll(pluginsService.filterPlugins(Plugin.class).stream().flatMap(p -> p.getNamedWriteables().stream()).collect(Collectors.toList()));
        NamedWriteableRegistry namedWriteableRegistry = new NamedWriteableRegistry(entries);
        NamedXContentRegistry xContentRegistry = new NamedXContentRegistry(Stream.of(searchModule.getNamedXContents().stream(), pluginsService.filterPlugins(Plugin.class).stream().flatMap(p -> p.getNamedXContent().stream())).flatMap(Function.identity()).collect(toList()));
        ModulesBuilder modules = new ModulesBuilder();
        // plugin modules must be added here, before others or we can get crazy injection errors...
        for (Module pluginModule : pluginsService.createGuiceModules()) {
            modules.add(pluginModule);
        }
        modules.add(b -> b.bind(ThreadPool.class).toInstance(threadPool));
        ActionModule actionModule = new ActionModule(true, settings, null, settingsModule.getIndexScopedSettings(), settingsModule.getClusterSettings(), settingsModule.getSettingsFilter(), threadPool, pluginsService.filterPlugins(ActionPlugin.class), null, null);
        modules.add(actionModule);
        CircuitBreakerService circuitBreakerService = Node.createCircuitBreakerService(settingsModule.getSettings(), settingsModule.getClusterSettings());
        resourcesToClose.add(circuitBreakerService);
        BigArrays bigArrays = new BigArrays(settings, circuitBreakerService);
        resourcesToClose.add(bigArrays);
        modules.add(settingsModule);
        NetworkModule networkModule = new NetworkModule(settings, true, pluginsService.filterPlugins(NetworkPlugin.class), threadPool, bigArrays, circuitBreakerService, namedWriteableRegistry, xContentRegistry, networkService, null);
        final Transport transport = networkModule.getTransportSupplier().get();
        final TransportService transportService = new TransportService(settings, transport, threadPool, networkModule.getTransportInterceptor(), boundTransportAddress -> DiscoveryNode.createLocal(settings, new TransportAddress(TransportAddress.META_ADDRESS, 0), UUIDs.randomBase64UUID()), null);
        modules.add((b -> {
            b.bind(BigArrays.class).toInstance(bigArrays);
            b.bind(PluginsService.class).toInstance(pluginsService);
            b.bind(CircuitBreakerService.class).toInstance(circuitBreakerService);
            b.bind(NamedWriteableRegistry.class).toInstance(namedWriteableRegistry);
            b.bind(Transport.class).toInstance(transport);
            b.bind(TransportService.class).toInstance(transportService);
            b.bind(NetworkService.class).toInstance(networkService);
        }));
        Injector injector = modules.createInjector();
        final TransportClientNodesService nodesService = new TransportClientNodesService(settings, transportService, threadPool, failureListner == null ? (t, e) -> {
        } : failureListner);
        final TransportProxyClient proxy = new TransportProxyClient(settings, transportService, nodesService, actionModule.getActions().values().stream().map(x -> x.getAction()).collect(Collectors.toList()));
        List<LifecycleComponent> pluginLifecycleComponents = new ArrayList<>();
        pluginLifecycleComponents.addAll(pluginsService.getGuiceServiceClasses().stream().map(injector::getInstance).collect(Collectors.toList()));
        resourcesToClose.addAll(pluginLifecycleComponents);
        transportService.start();
        transportService.acceptIncomingRequests();
        ClientTemplate transportClient = new ClientTemplate(injector, pluginLifecycleComponents, nodesService, proxy, namedWriteableRegistry);
        resourcesToClose.clear();
        return transportClient;
    } finally {
        IOUtils.closeWhileHandlingException(resourcesToClose);
    }
}
Also used : NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) Arrays(java.util.Arrays) Injector(org.elasticsearch.common.inject.Injector) NetworkModule(org.elasticsearch.common.network.NetworkModule) BigArrays(org.elasticsearch.common.util.BigArrays) Settings(org.elasticsearch.common.settings.Settings) TimeValue.timeValueSeconds(org.elasticsearch.common.unit.TimeValue.timeValueSeconds) ThreadPool(org.elasticsearch.threadpool.ThreadPool) NamedXContentRegistry(org.elasticsearch.common.xcontent.NamedXContentRegistry) ActionRequest(org.elasticsearch.action.ActionRequest) PluginsService(org.elasticsearch.plugins.PluginsService) Transport(org.elasticsearch.transport.Transport) Setting(org.elasticsearch.common.settings.Setting) Collection(java.util.Collection) UUIDs(org.elasticsearch.common.UUIDs) ClusterModule(org.elasticsearch.cluster.ClusterModule) Collectors(java.util.stream.Collectors) AbstractClient(org.elasticsearch.client.support.AbstractClient) List(java.util.List) Stream(java.util.stream.Stream) TransportAddress(org.elasticsearch.common.transport.TransportAddress) SearchPlugin(org.elasticsearch.plugins.SearchPlugin) Module(org.elasticsearch.common.inject.Module) InternalSettingsPreparer(org.elasticsearch.node.InternalSettingsPreparer) Function(java.util.function.Function) CircuitBreakerService(org.elasticsearch.indices.breaker.CircuitBreakerService) ArrayList(java.util.ArrayList) ActionModule(org.elasticsearch.action.ActionModule) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) NetworkService(org.elasticsearch.common.network.NetworkService) SettingsModule(org.elasticsearch.common.settings.SettingsModule) NetworkPlugin(org.elasticsearch.plugins.NetworkPlugin) NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) TcpTransport(org.elasticsearch.transport.TcpTransport) TimeValue(org.elasticsearch.common.unit.TimeValue) Node(org.elasticsearch.node.Node) ExecutorBuilder(org.elasticsearch.threadpool.ExecutorBuilder) TransportService(org.elasticsearch.transport.TransportService) ActionRequestBuilder(org.elasticsearch.action.ActionRequestBuilder) SearchModule(org.elasticsearch.search.SearchModule) ActionPlugin(org.elasticsearch.plugins.ActionPlugin) ActionResponse(org.elasticsearch.action.ActionResponse) IOUtils(org.apache.lucene.util.IOUtils) Plugin(org.elasticsearch.plugins.Plugin) Action(org.elasticsearch.action.Action) TimeUnit(java.util.concurrent.TimeUnit) Collectors.toList(java.util.stream.Collectors.toList) LifecycleComponent(org.elasticsearch.common.component.LifecycleComponent) Closeable(java.io.Closeable) ModulesBuilder(org.elasticsearch.common.inject.ModulesBuilder) Collections(java.util.Collections) ActionListener(org.elasticsearch.action.ActionListener) NetworkPlugin(org.elasticsearch.plugins.NetworkPlugin) TransportAddress(org.elasticsearch.common.transport.TransportAddress) Closeable(java.io.Closeable) ActionModule(org.elasticsearch.action.ActionModule) ArrayList(java.util.ArrayList) ThreadPool(org.elasticsearch.threadpool.ThreadPool) ActionPlugin(org.elasticsearch.plugins.ActionPlugin) LifecycleComponent(org.elasticsearch.common.component.LifecycleComponent) Injector(org.elasticsearch.common.inject.Injector) NamedXContentRegistry(org.elasticsearch.common.xcontent.NamedXContentRegistry) CircuitBreakerService(org.elasticsearch.indices.breaker.CircuitBreakerService) Settings(org.elasticsearch.common.settings.Settings) PluginsService(org.elasticsearch.plugins.PluginsService) Setting(org.elasticsearch.common.settings.Setting) SearchPlugin(org.elasticsearch.plugins.SearchPlugin) BigArrays(org.elasticsearch.common.util.BigArrays) TransportService(org.elasticsearch.transport.TransportService) SettingsModule(org.elasticsearch.common.settings.SettingsModule) NetworkService(org.elasticsearch.common.network.NetworkService) SearchModule(org.elasticsearch.search.SearchModule) ModulesBuilder(org.elasticsearch.common.inject.ModulesBuilder) NetworkModule(org.elasticsearch.common.network.NetworkModule) ClusterModule(org.elasticsearch.cluster.ClusterModule) Module(org.elasticsearch.common.inject.Module) ActionModule(org.elasticsearch.action.ActionModule) SettingsModule(org.elasticsearch.common.settings.SettingsModule) SearchModule(org.elasticsearch.search.SearchModule) Transport(org.elasticsearch.transport.Transport) TcpTransport(org.elasticsearch.transport.TcpTransport) NetworkModule(org.elasticsearch.common.network.NetworkModule)

Example 85 with Stream

use of java.util.stream.Stream in project elasticsearch by elastic.

the class InternalTestCluster method assertShardIndexCounter.

private void assertShardIndexCounter() throws Exception {
    assertBusy(() -> {
        final Collection<NodeAndClient> nodesAndClients = nodes.values();
        for (NodeAndClient nodeAndClient : nodesAndClients) {
            IndicesService indexServices = getInstance(IndicesService.class, nodeAndClient.name);
            for (IndexService indexService : indexServices) {
                for (IndexShard indexShard : indexService) {
                    int activeOperationsCount = indexShard.getActiveOperationsCount();
                    if (activeOperationsCount > 0) {
                        TaskManager taskManager = getInstance(TransportService.class, nodeAndClient.name).getTaskManager();
                        DiscoveryNode localNode = getInstance(ClusterService.class, nodeAndClient.name).localNode();
                        List<TaskInfo> taskInfos = taskManager.getTasks().values().stream().filter(task -> task instanceof ReplicationTask).map(task -> task.taskInfo(localNode.getId(), true)).collect(Collectors.toList());
                        ListTasksResponse response = new ListTasksResponse(taskInfos, Collections.emptyList(), Collections.emptyList());
                        try {
                            XContentBuilder builder = XContentFactory.jsonBuilder().prettyPrint().value(response);
                            throw new AssertionError("expected index shard counter on shard " + indexShard.shardId() + " on node " + nodeAndClient.name + " to be 0 but was " + activeOperationsCount + ". Current replication tasks on node:\n" + builder.string());
                        } catch (IOException e) {
                            throw new RuntimeException("caught exception while building response [" + response + "]", e);
                        }
                    }
                }
            }
        }
    });
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) ByteSizeUnit(org.elasticsearch.common.unit.ByteSizeUnit) Arrays(java.util.Arrays) Nullable(org.elasticsearch.common.Nullable) Releasables(org.elasticsearch.common.lease.Releasables) NetworkModule(org.elasticsearch.common.network.NetworkModule) ZenDiscovery(org.elasticsearch.discovery.zen.ZenDiscovery) ThreadContext(org.elasticsearch.common.util.concurrent.ThreadContext) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) NodeValidationException(org.elasticsearch.node.NodeValidationException) SearchService(org.elasticsearch.search.SearchService) RecoverySettings(org.elasticsearch.indices.recovery.RecoverySettings) ClusterState(org.elasticsearch.cluster.ClusterState) Future(java.util.concurrent.Future) RandomNumbers(com.carrotsearch.randomizedtesting.generators.RandomNumbers) Map(java.util.Map) Role(org.elasticsearch.cluster.node.DiscoveryNode.Role) Path(java.nio.file.Path) RandomStrings(com.carrotsearch.randomizedtesting.generators.RandomStrings) ServiceDisruptionScheme(org.elasticsearch.test.disruption.ServiceDisruptionScheme) Transport(org.elasticsearch.transport.Transport) MappingUpdatedAction(org.elasticsearch.cluster.action.index.MappingUpdatedAction) Set(java.util.Set) PageCacheRecycler(org.elasticsearch.common.util.PageCacheRecycler) ESTestCase.assertBusy(org.elasticsearch.test.ESTestCase.assertBusy) RandomizedTest(com.carrotsearch.randomizedtesting.RandomizedTest) Logger(org.apache.logging.log4j.Logger) Stream(java.util.stream.Stream) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) TransportSettings(org.elasticsearch.transport.TransportSettings) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) XContentFactory(org.elasticsearch.common.xcontent.XContentFactory) ThrottlingAllocationDecider(org.elasticsearch.cluster.routing.allocation.decider.ThrottlingAllocationDecider) RandomPicks(com.carrotsearch.randomizedtesting.generators.RandomPicks) DiskThresholdSettings(org.elasticsearch.cluster.routing.allocation.DiskThresholdSettings) TransportClient(org.elasticsearch.client.transport.TransportClient) ClusterService(org.elasticsearch.cluster.service.ClusterService) CircuitBreakerService(org.elasticsearch.indices.breaker.CircuitBreakerService) ArrayList(java.util.ArrayList) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) TcpTransport(org.elasticsearch.transport.TcpTransport) CircuitBreaker(org.elasticsearch.common.breaker.CircuitBreaker) IndicesService(org.elasticsearch.indices.IndicesService) TransportService(org.elasticsearch.transport.TransportService) Loggers(org.elasticsearch.common.logging.Loggers) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) FileSystemUtils(org.elasticsearch.common.io.FileSystemUtils) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) OperationRouting(org.elasticsearch.cluster.routing.OperationRouting) Client(org.elasticsearch.client.Client) IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard) IOUtils(org.apache.lucene.util.IOUtils) IOException(java.io.IOException) NodeService(org.elasticsearch.node.NodeService) SeedUtils(com.carrotsearch.randomizedtesting.SeedUtils) ExecutionException(java.util.concurrent.ExecutionException) LuceneTestCase.rarely(org.apache.lucene.util.LuceneTestCase.rarely) HierarchyCircuitBreakerService(org.elasticsearch.indices.breaker.HierarchyCircuitBreakerService) IndicesFieldDataCache(org.elasticsearch.indices.fielddata.cache.IndicesFieldDataCache) TreeMap(java.util.TreeMap) CommonStatsFlags(org.elasticsearch.action.admin.indices.stats.CommonStatsFlags) Assert(org.junit.Assert) ScriptService(org.elasticsearch.script.ScriptService) Builder(org.elasticsearch.common.settings.Settings.Builder) ElasticsearchAssertions.assertAcked(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked) ElasticsearchException(org.elasticsearch.ElasticsearchException) Environment(org.elasticsearch.env.Environment) Random(java.util.Random) TEST_NIGHTLY(org.apache.lucene.util.LuceneTestCase.TEST_NIGHTLY) Assert.assertThat(org.junit.Assert.assertThat) Settings(org.elasticsearch.common.settings.Settings) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SysGlobals(com.carrotsearch.randomizedtesting.SysGlobals) Assert.fail(org.junit.Assert.fail) ClusterName(org.elasticsearch.cluster.ClusterName) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) Predicate(java.util.function.Predicate) Collection(java.util.Collection) ShardLockObtainFailedException(org.elasticsearch.env.ShardLockObtainFailedException) Flag(org.elasticsearch.action.admin.indices.stats.CommonStatsFlags.Flag) NavigableMap(java.util.NavigableMap) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) Engine(org.elasticsearch.index.engine.Engine) ESTestCase.randomFrom(org.elasticsearch.test.ESTestCase.randomFrom) MockTransportClient(org.elasticsearch.transport.MockTransportClient) List(java.util.List) TransportAddress(org.elasticsearch.common.transport.TransportAddress) Matchers.equalTo(org.hamcrest.Matchers.equalTo) DISCOVERY_ZEN_MINIMUM_MASTER_NODES_SETTING(org.elasticsearch.discovery.zen.ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES_SETTING) ElectMasterService(org.elasticsearch.discovery.zen.ElectMasterService) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) HttpServerTransport(org.elasticsearch.http.HttpServerTransport) CommitStats(org.elasticsearch.index.engine.CommitStats) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) Index(org.elasticsearch.index.Index) Function(java.util.function.Function) Strings(org.elasticsearch.common.Strings) ListTasksResponse(org.elasticsearch.action.admin.cluster.node.tasks.list.ListTasksResponse) HashSet(java.util.HashSet) TimeValue(org.elasticsearch.common.unit.TimeValue) Node(org.elasticsearch.node.Node) MockTransportService(org.elasticsearch.test.transport.MockTransportService) ExecutorService(java.util.concurrent.ExecutorService) NodeStats(org.elasticsearch.action.admin.cluster.node.stats.NodeStats) TaskInfo(org.elasticsearch.tasks.TaskInfo) MockNode(org.elasticsearch.node.MockNode) EsExecutors(org.elasticsearch.common.util.concurrent.EsExecutors) Iterator(java.util.Iterator) Plugin(org.elasticsearch.plugins.Plugin) ESTestCase.awaitBusy(org.elasticsearch.test.ESTestCase.awaitBusy) TimeUnit(java.util.concurrent.TimeUnit) NodeEnvironment(org.elasticsearch.env.NodeEnvironment) Closeable(java.io.Closeable) TaskManager(org.elasticsearch.tasks.TaskManager) Collections(java.util.Collections) ReplicationTask(org.elasticsearch.action.support.replication.ReplicationTask) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard) IndicesService(org.elasticsearch.indices.IndicesService) IOException(java.io.IOException) ListTasksResponse(org.elasticsearch.action.admin.cluster.node.tasks.list.ListTasksResponse) TaskInfo(org.elasticsearch.tasks.TaskInfo) TaskManager(org.elasticsearch.tasks.TaskManager) ClusterService(org.elasticsearch.cluster.service.ClusterService) ReplicationTask(org.elasticsearch.action.support.replication.ReplicationTask) TransportService(org.elasticsearch.transport.TransportService) MockTransportService(org.elasticsearch.test.transport.MockTransportService) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder)

Aggregations

Stream (java.util.stream.Stream)161 Collectors (java.util.stream.Collectors)98 List (java.util.List)89 ArrayList (java.util.ArrayList)66 Map (java.util.Map)66 Set (java.util.Set)59 IOException (java.io.IOException)58 Optional (java.util.Optional)45 Collections (java.util.Collections)43 HashMap (java.util.HashMap)43 Arrays (java.util.Arrays)33 HashSet (java.util.HashSet)33 File (java.io.File)32 Path (java.nio.file.Path)32 Function (java.util.function.Function)28 Logger (org.slf4j.Logger)26 LoggerFactory (org.slf4j.LoggerFactory)26 java.util (java.util)25 Predicate (java.util.function.Predicate)23 Objects (java.util.Objects)22