diff --git a/.circleci/config.yml b/.circleci/config.yml index 554e3d70d..7aa472599 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -73,5 +73,5 @@ workflows: - build: matrix: parameters: - jdk-version: ["8.0"] # TODO: Add JDK 11.0 when builds for JDK8 work - category: ["docker"] # TODO: Add builds for kubernetes and openshift \ No newline at end of file + jdk-version: ["11.0"] # TODO: Add JDK 11.0 when builds for JDK8 work + category: ["docker"] # TODO: Add builds for kubernetes and openshift diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties index 6637cedb2..4465bd923 100644 --- a/.mvn/wrapper/maven-wrapper.properties +++ b/.mvn/wrapper/maven-wrapper.properties @@ -1 +1 @@ -distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip \ No newline at end of file +distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.9.6/apache-maven-3.9.6-bin.zip diff --git a/core/pom.xml b/core/pom.xml index 6e2b77d82..45f711185 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -84,7 +84,7 @@ org.hamcrest - hamcrest-library + hamcrest test diff --git a/core/src/main/java/org/arquillian/cube/impl/util/Timespan.java b/core/src/main/java/org/arquillian/cube/impl/util/Timespan.java index 4524b11ee..939aaa893 100644 --- a/core/src/main/java/org/arquillian/cube/impl/util/Timespan.java +++ b/core/src/main/java/org/arquillian/cube/impl/util/Timespan.java @@ -84,7 +84,7 @@ public String getDisplayChar() { final List timeUnits = Arrays.asList(TimeUnit.values()); Collections.reverse(timeUnits); - TIME_UNIT_ORDER = (TimeUnit[]) timeUnits.toArray(); + TIME_UNIT_ORDER = timeUnits.toArray(new TimeUnit[timeUnits.size()]); } static { diff --git a/core/src/test/java/org/arquillian/cube/impl/client/container/ContainerConfigurationControllerTest.java b/core/src/test/java/org/arquillian/cube/impl/client/container/ContainerConfigurationControllerTest.java index e3ec9105c..9e76c8def 100644 --- a/core/src/test/java/org/arquillian/cube/impl/client/container/ContainerConfigurationControllerTest.java +++ b/core/src/test/java/org/arquillian/cube/impl/client/container/ContainerConfigurationControllerTest.java @@ -24,6 +24,7 @@ import org.mockito.junit.MockitoJUnitRunner; import org.yaml.snakeyaml.Yaml; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -67,7 +68,7 @@ public void setup() { Map content = (Map) yaml.load(CONTENT); when(cube.getId()).thenReturn(CUBE_ID); - when(cube.configuration()).thenReturn(content); + lenient().when(cube.configuration()).thenReturn(content); when(cube.getMetadata(HasPortBindings.class)).thenReturn( new TestPortBindings(new Binding("localhost").addPortBinding(8089, 8090))); when(container.getName()).thenReturn(CUBE_ID); diff --git a/core/src/test/java/org/arquillian/cube/impl/client/container/CubeContainerLifecycleControllerTest.java b/core/src/test/java/org/arquillian/cube/impl/client/container/CubeContainerLifecycleControllerTest.java index 774ba27ed..43638d153 100644 --- a/core/src/test/java/org/arquillian/cube/impl/client/container/CubeContainerLifecycleControllerTest.java +++ b/core/src/test/java/org/arquillian/cube/impl/client/container/CubeContainerLifecycleControllerTest.java @@ -29,6 +29,7 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) @@ -164,7 +165,7 @@ public void shouldUseOverriddenCubeId() { Map containerConfig = new HashMap(); containerConfig.put("cubeId", CUBE_ID); - when(container.getName()).thenReturn(MISSING_CUBE_ID); + lenient().when(container.getName()).thenReturn(MISSING_CUBE_ID); when(containerDef.getContainerProperties()).thenReturn(containerConfig); shouldCreateAndStartCubeDuringBeforeStart(); diff --git a/core/src/test/java/org/arquillian/cube/impl/client/container/ProtocolMetaDataUpdaterTestCase.java b/core/src/test/java/org/arquillian/cube/impl/client/container/ProtocolMetaDataUpdaterTestCase.java index b83acf2b2..457bfd63e 100644 --- a/core/src/test/java/org/arquillian/cube/impl/client/container/ProtocolMetaDataUpdaterTestCase.java +++ b/core/src/test/java/org/arquillian/cube/impl/client/container/ProtocolMetaDataUpdaterTestCase.java @@ -123,7 +123,7 @@ public void shouldUpdateWithIPFromDocker() throws Exception { public void shouldNotUpdateIfContainerNotMapped() throws Exception { Binding binding = new Binding(GATEWAY_IP); binding.addPortBinding(EXPOSED_PORT, EXPOSED_PORT); - Mockito.when(cube.getMetadata(HasPortBindings.class)).thenReturn(new TestPortBindings(binding)); + Mockito.lenient().when(cube.getMetadata(HasPortBindings.class)).thenReturn(new TestPortBindings(binding)); bind(ContainerScoped.class, Container.class, diff --git a/docker/assertj/src/main/java/com/github/dockerjava/assertions/ImagesAssert.java b/docker/assertj/src/main/java/com/github/dockerjava/assertions/ImagesAssert.java index 6668356b0..594c9b9ab 100644 --- a/docker/assertj/src/main/java/com/github/dockerjava/assertions/ImagesAssert.java +++ b/docker/assertj/src/main/java/com/github/dockerjava/assertions/ImagesAssert.java @@ -6,8 +6,6 @@ import java.util.List; import org.assertj.core.api.ListAssert; -import static org.assertj.core.api.Assertions.assertThat; - /** * @author EddĂș MelĂ©ndez */ @@ -22,12 +20,12 @@ public ImagesAssert containsImages(String... imageIds) { for (Image image : this.actual) { imageList.add(image.getId()); } - /** rls TODO https://github.com/arquillian/arquillian-cube/issues/1289 - assertThat(this.actual) + + org.assertj.core.api.Assertions.assertThat(this.actual) .extracting("id") .overridingErrorMessage("%nExpecting:%n <%s>%nto contain:%n <%s>", imageList, Arrays.asList(imageIds)) .contains(imageIds); - **/ + return this; } } diff --git a/docker/docker/pom.xml b/docker/docker/pom.xml index 9ae51595e..50f313a4a 100644 --- a/docker/docker/pom.xml +++ b/docker/docker/pom.xml @@ -105,7 +105,7 @@ org.hamcrest - hamcrest-library + hamcrest test diff --git a/docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/config/ExposedPort.java b/docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/config/ExposedPort.java index a27ef7002..fe770f11c 100644 --- a/docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/config/ExposedPort.java +++ b/docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/config/ExposedPort.java @@ -15,6 +15,12 @@ public ExposedPort(int exposed, String type) { } } + public ExposedPort(final String exp) { + final ExposedPort parsed = valueOf(exp); + this.exposed = parsed.exposed; + this.type = parsed.type; + } + public static ExposedPort valueOf(String exp) { int exposed; String type = null; diff --git a/docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/config/Image.java b/docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/config/Image.java index 54df891be..959e565c6 100644 --- a/docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/config/Image.java +++ b/docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/config/Image.java @@ -9,6 +9,12 @@ public Image(String name, String tag) { this.tag = tag; } + public Image(final String nameAndTag) { + final Image parsed = valueOf(nameAndTag); + this.name = parsed.name; + this.tag = parsed.tag; + } + public static Image valueOf(String image) { String name = null; String tag = null; diff --git a/docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/config/Link.java b/docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/config/Link.java index 36f29fe9f..4d0deac17 100644 --- a/docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/config/Link.java +++ b/docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/config/Link.java @@ -14,6 +14,12 @@ public Link(String name, String alias) { this.alias = alias; } + public Link(final String links) { + final Link parsed = valueOf(links); + this.name = parsed.name; + this.alias = parsed.alias; + } + public static Link valueOf(String links) { String[] link = links.split(":"); String name = link[0]; diff --git a/docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/config/PortBinding.java b/docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/config/PortBinding.java index 37a379edd..29390674b 100644 --- a/docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/config/PortBinding.java +++ b/docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/config/PortBinding.java @@ -16,6 +16,13 @@ public PortBinding(String host, int bound, ExposedPort exposed) { this.exposed = exposed; } + public PortBinding(final String portBinding) { + final PortBinding parsed = valueOf(portBinding); + this.host = parsed.host; + this.bound = parsed.bound; + this.exposed = parsed.exposed; + } + public static PortBinding valueOf(String portBinding) { ExposedPort exposed; int bound; diff --git a/docker/docker/src/test/java/org/arquillian/cube/docker/impl/await/DockerHealthAwaitStrategyTest.java b/docker/docker/src/test/java/org/arquillian/cube/docker/impl/await/DockerHealthAwaitStrategyTest.java index 67a7375ab..626c8029a 100644 --- a/docker/docker/src/test/java/org/arquillian/cube/docker/impl/await/DockerHealthAwaitStrategyTest.java +++ b/docker/docker/src/test/java/org/arquillian/cube/docker/impl/await/DockerHealthAwaitStrategyTest.java @@ -47,7 +47,7 @@ public class DockerHealthAwaitStrategyTest { @BeforeClass public static void createDockerClient() { if (!System.getenv().containsKey(DOCKER_HOST) || System.getenv(DOCKER_HOST).equals("")){ - environmentVariables.set(DOCKER_HOST, "unix:///var/run/docker.sock"); + environmentVariables.set(DOCKER_HOST, "unix:///var/run/podman.sock"); } dockerClient = DockerClientBuilder.getInstance().build(); healthSuccessImageId = dockerBuild("DockerHealthAwait/HealthSuccess/Dockerfile"); diff --git a/docker/docker/src/test/java/org/arquillian/cube/docker/impl/client/CubeConfiguratorTest.java b/docker/docker/src/test/java/org/arquillian/cube/docker/impl/client/CubeConfiguratorTest.java index 4ed6fe877..685125f4e 100644 --- a/docker/docker/src/test/java/org/arquillian/cube/docker/impl/client/CubeConfiguratorTest.java +++ b/docker/docker/src/test/java/org/arquillian/cube/docker/impl/client/CubeConfiguratorTest.java @@ -40,6 +40,7 @@ import static org.hamcrest.collection.IsMapContaining.hasKey; import static org.junit.Assert.assertThat; import static org.junit.Assume.assumeThat; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -76,8 +77,8 @@ private static Matcher pathEndsWith(String suffix) { } private void bindNonExistingDockerSocketOS() { - when(operatingSystem.getDefaultFamily()).thenReturn(operatingSystemFamily); - when(operatingSystem.getFamily()).thenReturn(OperatingSystemFamily.MAC); + lenient().when(operatingSystem.getDefaultFamily()).thenReturn(operatingSystemFamily); + lenient().when(operatingSystem.getFamily()).thenReturn(OperatingSystemFamily.MAC); when(operatingSystemFamily.getServerUri()).thenReturn("non/existing/path"); bind(ApplicationScoped.class, OperatingSystemInterface.class, operatingSystem); @@ -107,8 +108,8 @@ public void shouldChangeServerUriInCaseOfRunningDockerInsideDocker() { config.put(CubeDockerConfiguration.DOCKER_URI, "https://dockerHost:22222"); when(extensionDef.getExtensionProperties()).thenReturn(config); - when(arquillianDescriptor.extension("docker")).thenReturn(extensionDef); - when(commandLineExecutor.execCommand("boot2docker", "ip")).thenReturn("192.168.0.1"); + lenient().when(arquillianDescriptor.extension("docker")).thenReturn(extensionDef); + lenient().when(commandLineExecutor.execCommand("boot2docker", "ip")).thenReturn("192.168.0.1"); when(commandLineExecutor.execCommand("docker-machine")).thenThrow(new RuntimeException()); when(top.isSpinning()).thenReturn(true); @@ -127,7 +128,7 @@ public void shouldNotChangeServerUriInCaseODockerInsideDockerIfItIsDisabled() { when(commandLineExecutor.execCommand("boot2docker", "ip")).thenReturn("192.168.0.1"); when(commandLineExecutor.execCommand("docker-machine")).thenThrow(new RuntimeException()); - when(top.isSpinning()).thenReturn(true); + lenient().when(top.isSpinning()).thenReturn(true); fire(new CubeConfiguration()); assertThat(config, hasEntry(CubeDockerConfiguration.DOCKER_URI, "tcp://192.168.0.1:22222")); diff --git a/docker/docker/src/test/java/org/arquillian/cube/docker/impl/client/CubeDockerConfigurationResolverTest.java b/docker/docker/src/test/java/org/arquillian/cube/docker/impl/client/CubeDockerConfigurationResolverTest.java index a3e14620f..d2581feeb 100644 --- a/docker/docker/src/test/java/org/arquillian/cube/docker/impl/client/CubeDockerConfigurationResolverTest.java +++ b/docker/docker/src/test/java/org/arquillian/cube/docker/impl/client/CubeDockerConfigurationResolverTest.java @@ -19,7 +19,6 @@ import org.arquillian.cube.docker.impl.util.Top; import org.junit.BeforeClass; import org.junit.ClassRule; -import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.EnvironmentVariables; import org.junit.runner.RunWith; @@ -31,6 +30,7 @@ import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) @@ -94,7 +94,7 @@ public void shouldDetectsValidDockerDefault() throws Exception { String sockUri = isWindows ?sockURL.toExternalForm().replace("file:/", "") : "unix://" + sockURL.toExternalForm(); when(defaultOperatingSystemFamilyInterface.getServerUri()).thenReturn(sockUri); when(operatingSystemInterface.getDefaultFamily()).thenReturn(defaultOperatingSystemFamilyInterface); - when(operatingSystemInterface.getFamily()).thenReturn(OperatingSystem.MAC_OSX.getFamily()); + lenient().when(operatingSystemInterface.getFamily()).thenReturn(OperatingSystem.MAC_OSX.getFamily()); Map config = new HashMap<>(); @@ -116,7 +116,7 @@ public void shouldSkipsInvalidDockerDefault() throws Exception { new Boot2Docker(boot2dockerCommandLineExecutor), mockDefaultDocker(), operatingSystemInterface); - when(boot2dockerCommandLineExecutor.execCommand(ArgumentMatchers.any())).thenReturn("127.0.0.1"); + when(boot2dockerCommandLineExecutor.execCommand(anyString(), anyString())).thenReturn("127.0.0.1"); String sockUri = "unix:///a/path-that/does/not/exist"; when(defaultOperatingSystemFamilyInterface.getServerUri()).thenReturn(sockUri); @@ -139,11 +139,11 @@ public void shouldNotSetTlsVerifyForTcpSchemeOnOSX() { mockDefaultDocker(), operatingSystemInterface); - when(infoCmd.exec()).thenThrow(new ProcessingException("test exception")); + lenient().when(infoCmd.exec()).thenThrow(new ProcessingException("test exception")); String sockUri = "unix:///a/path-that/does/not/exist"; - when(defaultOperatingSystemFamilyInterface.getServerUri()).thenReturn(sockUri); - when(operatingSystemInterface.getDefaultFamily()).thenReturn(defaultOperatingSystemFamilyInterface); - when(operatingSystemInterface.getFamily()).thenReturn(OperatingSystem.MAC_OSX.getFamily()); + lenient().when(defaultOperatingSystemFamilyInterface.getServerUri()).thenReturn(sockUri); + lenient().when(operatingSystemInterface.getDefaultFamily()).thenReturn(defaultOperatingSystemFamilyInterface); + lenient().when(operatingSystemInterface.getFamily()).thenReturn(OperatingSystem.MAC_OSX.getFamily()); Map config = new HashMap<>(); config.put(CubeDockerConfiguration.DOCKER_URI, "tcp://localhost:2376"); @@ -161,12 +161,12 @@ public void shouldNotSetTlsVerifyForTcpSchemeOnLinux() { new Boot2Docker(null), mockDefaultDocker(), operatingSystemInterface); - when(infoCmd.exec()).thenThrow(new ProcessingException("test exception")); + lenient().when(infoCmd.exec()).thenThrow(new ProcessingException("test exception")); String sockUri = "unix:///a/path-that/does/not/exist"; - when(defaultOperatingSystemFamilyInterface.getServerUri()).thenReturn(sockUri); - when(operatingSystemInterface.getDefaultFamily()).thenReturn(defaultOperatingSystemFamilyInterface); - when(operatingSystemInterface.getFamily()).thenReturn(OperatingSystem.LINUX_OS.getFamily()); + lenient().when(defaultOperatingSystemFamilyInterface.getServerUri()).thenReturn(sockUri); + lenient().when(operatingSystemInterface.getDefaultFamily()).thenReturn(defaultOperatingSystemFamilyInterface); + lenient().when(operatingSystemInterface.getFamily()).thenReturn(OperatingSystem.LINUX_OS.getFamily()); Map config = new HashMap<>(); config.put(CubeDockerConfiguration.DOCKER_URI, "tcp://localhost:2376"); diff --git a/docker/docker/src/test/java/org/arquillian/cube/docker/impl/client/CubeSuiteLifecycleControllerTest.java b/docker/docker/src/test/java/org/arquillian/cube/docker/impl/client/CubeSuiteLifecycleControllerTest.java index cce0a3db0..82614abbf 100644 --- a/docker/docker/src/test/java/org/arquillian/cube/docker/impl/client/CubeSuiteLifecycleControllerTest.java +++ b/docker/docker/src/test/java/org/arquillian/cube/docker/impl/client/CubeSuiteLifecycleControllerTest.java @@ -24,6 +24,7 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -111,9 +112,9 @@ public void shouldCreateAndStartAutoContainersWhenNoAutoStartIsProvided() { ContainerRegistry containerRegistry = mock(ContainerRegistry.class); List containers = new ArrayList<>(); org.jboss.arquillian.container.spi.Container container = mock(org.jboss.arquillian.container.spi.Container.class); - when(container.getName()).thenReturn("a"); + lenient().when(container.getName()).thenReturn("a"); containers.add(container); - when(containerRegistry.getContainers()).thenReturn(containers); + lenient().when(containerRegistry.getContainers()).thenReturn(containers); bind(ApplicationScoped.class, ContainerRegistry.class, containerRegistry); diff --git a/docker/docker/src/test/java/org/arquillian/cube/docker/impl/client/container/DockerServerIPConfiguratorTest.java b/docker/docker/src/test/java/org/arquillian/cube/docker/impl/client/container/DockerServerIPConfiguratorTest.java index 68efcd701..fe0b8bc53 100644 --- a/docker/docker/src/test/java/org/arquillian/cube/docker/impl/client/container/DockerServerIPConfiguratorTest.java +++ b/docker/docker/src/test/java/org/arquillian/cube/docker/impl/client/container/DockerServerIPConfiguratorTest.java @@ -1,5 +1,6 @@ package org.arquillian.cube.docker.impl.client.container; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -89,7 +90,7 @@ public void setup() { Map content = (Map) yaml.load(CONTENT); when(cube.getId()).thenReturn(CUBE_ID); - when(cube.configuration()).thenReturn(content); + lenient().when(cube.configuration()).thenReturn(content); when(container.getName()).thenReturn(CUBE_ID); when(container.getDeployableContainer()).thenReturn(deployableContainer); when(deployableContainer.getConfigurationClass()).thenReturn(ContainerConfiguration.class); diff --git a/docker/docker/src/test/java/org/arquillian/cube/docker/impl/client/containerobject/DockerContainerObjectBuilderTest.java b/docker/docker/src/test/java/org/arquillian/cube/docker/impl/client/containerobject/DockerContainerObjectBuilderTest.java index e107ec40e..d3bfc57f7 100644 --- a/docker/docker/src/test/java/org/arquillian/cube/docker/impl/client/containerobject/DockerContainerObjectBuilderTest.java +++ b/docker/docker/src/test/java/org/arquillian/cube/docker/impl/client/containerobject/DockerContainerObjectBuilderTest.java @@ -195,7 +195,7 @@ public void shouldLinkInnerContainersWithoutLink() { verify(cubeController, times(1)).create("containerWithNonAnnotatedLink"); verify(cubeController, times(1)).start("containerWithNonAnnotatedLink"); - verify(cubeContainerObjectTestEnricher, times(1)).enrich(any(TestContainerObjectWithAnnotatedLink.class)); + verify(cubeContainerObjectTestEnricher, times(1)).enrich(any(TestContainerObjectWithNonAnnotatedLink.class)); } @Test diff --git a/docker/docker/src/test/java/org/arquillian/cube/docker/impl/client/containerobject/dsl/ContainerNetworkObjectDslTestEnricherTest.java b/docker/docker/src/test/java/org/arquillian/cube/docker/impl/client/containerobject/dsl/ContainerNetworkObjectDslTestEnricherTest.java index e487fe99f..45c5ba46e 100644 --- a/docker/docker/src/test/java/org/arquillian/cube/docker/impl/client/containerobject/dsl/ContainerNetworkObjectDslTestEnricherTest.java +++ b/docker/docker/src/test/java/org/arquillian/cube/docker/impl/client/containerobject/dsl/ContainerNetworkObjectDslTestEnricherTest.java @@ -17,6 +17,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -46,7 +47,7 @@ public void should_start_a_network() { containerNetworkObjectDslTestEnricher.networkRegistryInstance = () -> networkRegistry; containerNetworkObjectDslTestEnricher.dockerClientExecutorInstance = () -> dockerClientExecutor; - when(injector.inject(any(Network.class))).then(invocation -> invocation.getArgument(0, Network.class)); + lenient().when(injector.inject(any(Network.class))).then(invocation -> invocation.getArgument(0, Network.class)); when(dockerClientExecutor.createNetwork(eq("default"), any(org.arquillian.cube.docker.impl.client.config.Network.class))).thenReturn("default"); containerNetworkObjectDslTestEnricher.enrich(new NetworkTest()); diff --git a/docker/docker/src/test/java/org/arquillian/cube/docker/impl/requirement/DockerMachineRequirementTest.java b/docker/docker/src/test/java/org/arquillian/cube/docker/impl/requirement/DockerMachineRequirementTest.java index fa8afec63..e1aa03457 100644 --- a/docker/docker/src/test/java/org/arquillian/cube/docker/impl/requirement/DockerMachineRequirementTest.java +++ b/docker/docker/src/test/java/org/arquillian/cube/docker/impl/requirement/DockerMachineRequirementTest.java @@ -1,9 +1,5 @@ package org.arquillian.cube.docker.impl.requirement; -import java.lang.annotation.Annotation; -import java.util.Arrays; -import java.util.Collections; - import org.arquillian.cube.docker.impl.util.CommandLineExecutor; import org.arquillian.cube.spi.requirement.UnsatisfiedRequirementException; import org.arquillian.spacelift.execution.ExecutionException; @@ -11,7 +7,12 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; -import static org.mockito.ArgumentMatchers.any; + +import java.lang.annotation.Annotation; +import java.util.Arrays; +import java.util.Collections; + +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) @@ -22,7 +23,8 @@ public class DockerMachineRequirementTest { @Test(expected = UnsatisfiedRequirementException.class) public void estDockerMachineRequirementCheckWhenExecutionExceptionThrown() throws UnsatisfiedRequirementException { - when(commandLineExecutor.execCommandAsArray(any())).thenThrow(ExecutionException.class); + when(commandLineExecutor.execCommandAsArray(anyString(), anyString(), anyString(), anyString(), anyString(), anyString())) + .thenThrow(ExecutionException.class); DockerMachineRequirement dockerMachineRequirement = new DockerMachineRequirement(commandLineExecutor); dockerMachineRequirement.check(createContext("testing")); @@ -30,7 +32,8 @@ public void estDockerMachineRequirementCheckWhenExecutionExceptionThrown() throw @Test(expected = UnsatisfiedRequirementException.class) public void testDockerMachineRequirementCheckNoMatchingNameFound() throws Exception { - when(commandLineExecutor.execCommandAsArray(any())).thenReturn(Collections.emptyList()); + when(commandLineExecutor.execCommandAsArray(anyString(), anyString(), anyString(), anyString(), anyString(), anyString())) + .thenReturn(Collections.emptyList()); DockerMachineRequirement dockerMachineRequirement = new DockerMachineRequirement(commandLineExecutor); dockerMachineRequirement.check(createContext("testing")); @@ -38,7 +41,8 @@ public void testDockerMachineRequirementCheckNoMatchingNameFound() throws Except @Test(expected = UnsatisfiedRequirementException.class) public void testDockerMachineRequirementCheckNoMachineFound() throws Exception { - when(commandLineExecutor.execCommandAsArray(any())).thenReturn(Arrays.asList(new String[] {"foo", "bar"})); + when(commandLineExecutor.execCommandAsArray(anyString(), anyString(), anyString(), anyString())) + .thenReturn(Arrays.asList(new String[] {"foo", "bar"})); DockerMachineRequirement dockerMachineRequirement = new DockerMachineRequirement(commandLineExecutor); dockerMachineRequirement.check(createContext("")); @@ -46,7 +50,8 @@ public void testDockerMachineRequirementCheckNoMachineFound() throws Exception { @Test(expected = UnsatisfiedRequirementException.class) public void testDockerMachineRequirementCheckNoMatchingNameNotMatched() throws Exception { - when(commandLineExecutor.execCommandAsArray(any())).thenReturn(Arrays.asList(new String[] {"my-docker-machine"})); + when(commandLineExecutor.execCommandAsArray(anyString(), anyString(), anyString(), anyString(), anyString(), anyString())) + .thenReturn(Arrays.asList(new String[] {"my-docker-machine"})); DockerMachineRequirement dockerMachineRequirement = new DockerMachineRequirement(commandLineExecutor); dockerMachineRequirement.check(createContext("testing")); @@ -54,7 +59,8 @@ public void testDockerMachineRequirementCheckNoMatchingNameNotMatched() throws E @Test public void testDockerMachineRequirementCheckNoMatchingNameMatched() throws Exception { - when(commandLineExecutor.execCommandAsArray(any())).thenReturn(Arrays.asList(new String[] {"testing"})); + when(commandLineExecutor.execCommandAsArray(anyString(), anyString(), anyString(), anyString(), anyString(), anyString())) + .thenReturn(Arrays.asList(new String[] {"testing"})); DockerMachineRequirement dockerMachineRequirement = new DockerMachineRequirement(commandLineExecutor); dockerMachineRequirement.check(createContext("testing")); diff --git a/docker/drone/src/test/java/org/arquillian/cube/docker/drone/SeleniumContainersTest.java b/docker/drone/src/test/java/org/arquillian/cube/docker/drone/SeleniumContainersTest.java index 91b353f83..12d277c24 100644 --- a/docker/drone/src/test/java/org/arquillian/cube/docker/drone/SeleniumContainersTest.java +++ b/docker/drone/src/test/java/org/arquillian/cube/docker/drone/SeleniumContainersTest.java @@ -17,6 +17,7 @@ import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.CoreMatchers.startsWith; import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) @@ -65,8 +66,8 @@ public void shouldCreateCustomContainerFromImageName() { @Test public void shouldCreateCustomContainerFromDockerfile() { - when(cubeDroneConfiguration.isBrowserDockerfileDirectorySet()).thenReturn(true); - when(cubeDroneConfiguration.isBrowserImageSet()).thenReturn(false); + lenient().when(cubeDroneConfiguration.isBrowserDockerfileDirectorySet()).thenReturn(true); + lenient().when(cubeDroneConfiguration.isBrowserImageSet()).thenReturn(false); when(cubeDroneConfiguration.getBrowserDockerfileLocation()).thenReturn("src/test/resources/browser"); when(cubeDroneConfiguration.getContainerNameStrategy()).thenReturn(ContainerNameStrategy.STATIC); @@ -80,7 +81,7 @@ public void shouldCreateCustomContainerFromDockerfile() { @Test public void shouldTakePrecedenceDockerfileDirectoryThanImage() { when(cubeDroneConfiguration.isBrowserDockerfileDirectorySet()).thenReturn(true); - when(cubeDroneConfiguration.isBrowserImageSet()).thenReturn(true); + lenient().when(cubeDroneConfiguration.isBrowserImageSet()).thenReturn(true); when(cubeDroneConfiguration.getBrowserDockerfileLocation()).thenReturn("src/test/resources/browser"); when(cubeDroneConfiguration.getContainerNameStrategy()).thenReturn(ContainerNameStrategy.STATIC); diff --git a/docker/drone/src/test/java/org/arquillian/cube/docker/drone/VncRecorderLifecycleManagerTest.java b/docker/drone/src/test/java/org/arquillian/cube/docker/drone/VncRecorderLifecycleManagerTest.java index 20001c2e4..1ec74ce33 100644 --- a/docker/drone/src/test/java/org/arquillian/cube/docker/drone/VncRecorderLifecycleManagerTest.java +++ b/docker/drone/src/test/java/org/arquillian/cube/docker/drone/VncRecorderLifecycleManagerTest.java @@ -21,6 +21,7 @@ import org.mockito.junit.MockitoJUnitRunner; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -135,9 +136,9 @@ public void should_discard_recording_if_configured_in_only_failing_and_passed_te final File destination = temporaryFolder.newFolder("destination"); final File video = temporaryFolder.newFile("file.flv"); - when(seleniumContainers.getVideoRecordingFile()).thenReturn(video.toPath()); - when(after.getTestClass()).thenReturn(new TestClass(VncRecorderLifecycleManagerTest.class)); - when(after.getTestMethod()).thenReturn(VncRecorderLifecycleManagerTest.class.getMethod( + lenient().when(seleniumContainers.getVideoRecordingFile()).thenReturn(video.toPath()); + lenient().when(after.getTestClass()).thenReturn(new TestClass(VncRecorderLifecycleManagerTest.class)); + lenient().when(after.getTestMethod()).thenReturn(VncRecorderLifecycleManagerTest.class.getMethod( "should_discard_recording_if_configured_in_only_failing_and_passed_test")); Map conf = new HashMap<>(); diff --git a/docker/drone/src/test/java/org/arquillian/cube/docker/graphene/location/CubeDockerCustomizableURLResourceProviderTest.java b/docker/drone/src/test/java/org/arquillian/cube/docker/graphene/location/CubeDockerCustomizableURLResourceProviderTest.java index a6bcfd3fe..6ea5673c6 100644 --- a/docker/drone/src/test/java/org/arquillian/cube/docker/graphene/location/CubeDockerCustomizableURLResourceProviderTest.java +++ b/docker/drone/src/test/java/org/arquillian/cube/docker/graphene/location/CubeDockerCustomizableURLResourceProviderTest.java @@ -17,6 +17,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) @@ -92,7 +93,7 @@ public CubeRegistry get() { @Test public void should_resolve_to_docker_host_if_no_url_provided() { final DockerCompositions compositions = ConfigUtil.load(SIMPLE_SCENARIO); - when(cubeDockerConfiguration.getDockerContainersContent()).thenReturn(compositions); + lenient().when(cubeDockerConfiguration.getDockerContainersContent()).thenReturn(compositions); when(grapheneConfiguration.getUrl()).thenReturn(null); assertThatThrownBy(() -> { @@ -104,7 +105,7 @@ public void should_resolve_to_docker_host_if_no_url_provided() { @Test public void should_resolve_internal_ip_of_container() { final DockerCompositions compositions = ConfigUtil.load(SIMPLE_SCENARIO); - when(cubeDockerConfiguration.getDockerContainersContent()).thenReturn(compositions); + lenient().when(cubeDockerConfiguration.getDockerContainersContent()).thenReturn(compositions); when(grapheneConfiguration.getUrl()).thenReturn("http://helloworld:80/context"); final URL url = (URL) dockerCubeCustomizableURLResourceProvider.lookup(null); @@ -119,7 +120,7 @@ public void should_resolve_internal_ip_of_container() { @Test public void should_resolve_internal_ip_of_container_with_default_port() { final DockerCompositions compositions = ConfigUtil.load(SIMPLE_SCENARIO); - when(cubeDockerConfiguration.getDockerContainersContent()).thenReturn(compositions); + lenient().when(cubeDockerConfiguration.getDockerContainersContent()).thenReturn(compositions); when(grapheneConfiguration.getUrl()).thenReturn("http://helloworld/context"); final URL url = (URL) dockerCubeCustomizableURLResourceProvider.lookup(null); @@ -134,7 +135,7 @@ public void should_resolve_internal_ip_of_container_with_default_port() { @Test public void should_not_resolve_ip() { final DockerCompositions compositions = ConfigUtil.load(SIMPLE_SCENARIO); - when(cubeDockerConfiguration.getDockerContainersContent()).thenReturn(compositions); + lenient().when(cubeDockerConfiguration.getDockerContainersContent()).thenReturn(compositions); when(grapheneConfiguration.getUrl()).thenReturn("http://192.168.99.101:80/context"); final URL url = (URL) dockerCubeCustomizableURLResourceProvider.lookup(null); @@ -149,7 +150,7 @@ public void should_not_resolve_ip() { @Test public void should_resolve_docker_host_in_relative_url() { final DockerCompositions compositions = ConfigUtil.load(SIMPLE_SCENARIO); - when(cubeDockerConfiguration.getDockerContainersContent()).thenReturn(compositions); + lenient().when(cubeDockerConfiguration.getDockerContainersContent()).thenReturn(compositions); when(grapheneConfiguration.getUrl()).thenReturn("http://dockerHost:80/context"); final URL url = (URL) dockerCubeCustomizableURLResourceProvider.lookup(null); @@ -164,7 +165,7 @@ public void should_resolve_docker_host_in_relative_url() { @Test public void should_resolve_docker_host_in_relative_url_with_default_port() { final DockerCompositions compositions = ConfigUtil.load(SIMPLE_SCENARIO); - when(cubeDockerConfiguration.getDockerContainersContent()).thenReturn(compositions); + lenient().when(cubeDockerConfiguration.getDockerContainersContent()).thenReturn(compositions); when(grapheneConfiguration.getUrl()).thenReturn("http://dockerHost/context"); final URL url = (URL) dockerCubeCustomizableURLResourceProvider.lookup(null); diff --git a/docker/ftest-boot2docker/pom.xml b/docker/ftest-boot2docker/pom.xml index 192d48731..3cd012e98 100644 --- a/docker/ftest-boot2docker/pom.xml +++ b/docker/ftest-boot2docker/pom.xml @@ -12,7 +12,7 @@ 1.1.1.Final 1.1.0.Final - 8.2.1.Final + 5.0.1.Final 1.0.0.Alpha1 1.12 tcp://localhost:2375 @@ -211,7 +211,7 @@ - org.wildfly + org.wildfly.arquillian wildfly-arquillian-container-remote ${version.wildfly} test @@ -225,7 +225,7 @@ - org.wildfly + org.wildfly.arquillian wildfly-arquillian-container-remote ${version.wildfly} test @@ -240,7 +240,7 @@ - org.wildfly + org.wildfly.arquillian wildfly-arquillian-container-remote ${version.wildfly} test diff --git a/docker/ftest-container-star-operator/pom.xml b/docker/ftest-container-star-operator/pom.xml index ddbed6e76..13e063755 100644 --- a/docker/ftest-container-star-operator/pom.xml +++ b/docker/ftest-container-star-operator/pom.xml @@ -11,7 +11,7 @@ 1.1.1.Final - 8.2.1.Final + 5.0.1.Final @@ -64,7 +64,7 @@ provided - org.wildfly + org.wildfly.arquillian wildfly-arquillian-container-remote ${version.wildfly} test diff --git a/docker/ftest-docker-junit5/pom.xml b/docker/ftest-docker-junit5/pom.xml index 9d6350796..98e9fde1f 100644 --- a/docker/ftest-docker-junit5/pom.xml +++ b/docker/ftest-docker-junit5/pom.xml @@ -26,13 +26,6 @@ maven-surefire-plugin - - - org.junit.platform - junit-platform-surefire-provider - 1.3.2 - - diff --git a/docker/ftest/pom.xml b/docker/ftest/pom.xml index c236dab78..8b29ec282 100644 --- a/docker/ftest/pom.xml +++ b/docker/ftest/pom.xml @@ -12,7 +12,7 @@ 1.1.1.Final 1.1.0.Final - 8.2.1.Final + 5.0.1.Final 1.0.0.Alpha1 @@ -155,7 +155,7 @@ - org.wildfly + org.wildfly.arquillian wildfly-arquillian-container-remote ${version.wildfly} test @@ -169,7 +169,7 @@ - org.wildfly + org.wildfly.arquillian wildfly-arquillian-container-remote ${version.wildfly} test @@ -184,7 +184,7 @@ - org.wildfly + org.wildfly.arquillian wildfly-arquillian-container-remote ${version.wildfly} test diff --git a/docker/junit5/pom.xml b/docker/junit5/pom.xml index 9bb1813df..6baa40dd0 100644 --- a/docker/junit5/pom.xml +++ b/docker/junit5/pom.xml @@ -39,13 +39,6 @@ maven-surefire-plugin - - - org.junit.platform - junit-platform-surefire-provider - 1.3.2 - - maven-failsafe-plugin diff --git a/docker/reporter/src/test/java/org/arquillian/cube/docker/impl/client/reporter/TakeDockerEnvironmentTest.java b/docker/reporter/src/test/java/org/arquillian/cube/docker/impl/client/reporter/TakeDockerEnvironmentTest.java index c9363b820..6085f7685 100644 --- a/docker/reporter/src/test/java/org/arquillian/cube/docker/impl/client/reporter/TakeDockerEnvironmentTest.java +++ b/docker/reporter/src/test/java/org/arquillian/cube/docker/impl/client/reporter/TakeDockerEnvironmentTest.java @@ -53,6 +53,7 @@ import static org.arquillian.cube.docker.impl.client.reporter.DockerEnvironmentReportKey.NETWORK_TOPOLOGY_SCHEMA; import static org.arquillian.reporter.impl.asserts.ReportAssert.assertThatReport; import static org.arquillian.reporter.impl.asserts.SectionAssert.assertThatSection; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -105,7 +106,7 @@ private void configureDockerExecutor() { when(version.getApiVersion()).thenReturn("1.12"); when(version.getArch()).thenReturn("x86"); when(dockerClientExecutor.dockerHostVersion()).thenReturn(version); - when(dockerClientExecutor.isDockerInsideDockerResolution()).thenReturn(true); + lenient().when(dockerClientExecutor.isDockerInsideDockerResolution()).thenReturn(true); } private void configureCube() throws IOException { @@ -113,12 +114,12 @@ private void configureCube() throws IOException { when(cube.getId()).thenReturn(CUBE_ID); cubeRegistry.addCube(cube); Map networks = getNetworks(); - when(statistics.getNetworks()).thenReturn(networks); + lenient().when(statistics.getNetworks()).thenReturn(networks); MemoryStatsConfig memory = getMemory(); - when(statistics.getMemoryStats()).thenReturn(memory); + lenient().when(statistics.getMemoryStats()).thenReturn(memory); BlkioStatsConfig ioStats = getIOStats(); - when(statistics.getBlkioStats()).thenReturn(ioStats); - when(dockerClientExecutor.statsContainer(CUBE_ID)).thenReturn(statistics); + lenient().when(statistics.getBlkioStats()).thenReturn(ioStats); + lenient().when(dockerClientExecutor.statsContainer(CUBE_ID)).thenReturn(statistics); } private void createTakeDockerEnvironmentAndreportDockerEnvironment() { @@ -307,9 +308,9 @@ private ReporterConfiguration getReporterConfiguration() { private Map getNetworks() { Map nw = new LinkedHashMap<>(); StatisticNetworksConfig bytes = mock(StatisticNetworksConfig.class); - when(bytes.getRxBytes()).thenReturn(724L); - when(bytes.getTxBytes()).thenReturn(418L); - when(bytes.getRxPackets()).thenReturn(19L); + lenient().when(bytes.getRxBytes()).thenReturn(724L); + lenient().when(bytes.getTxBytes()).thenReturn(418L); + lenient().when(bytes.getRxPackets()).thenReturn(19L); nw.put("eth0", bytes); return nw; @@ -317,10 +318,10 @@ private Map getNetworks() { private MemoryStatsConfig getMemory() { MemoryStatsConfig memory = mock(MemoryStatsConfig.class); - when(memory.getUsage()).thenReturn(35135488L); - when(memory.getMaxUsage()).thenReturn(35770368L); - when(memory.getLimit()).thenReturn(20444532736L); - when(memory.getStats()).thenReturn(new StatsConfig()); + lenient().when(memory.getUsage()).thenReturn(35135488L); + lenient().when(memory.getMaxUsage()).thenReturn(35770368L); + lenient().when(memory.getLimit()).thenReturn(20444532736L); + lenient().when(memory.getStats()).thenReturn(new StatsConfig()); return memory; } @@ -350,8 +351,8 @@ private BlkioStatsConfig getIOStats() { .withValue(0L); io.add(ioServiceSync); - when(blkIO.getIoServiceBytesRecursive()).thenReturn(io); - when(blkIO.getIoTimeRecursive()).thenReturn(new ArrayList<>()); + lenient().when(blkIO.getIoServiceBytesRecursive()).thenReturn(io); + lenient().when(blkIO.getIoTimeRecursive()).thenReturn(new ArrayList<>()); return blkIO; } diff --git a/kubernetes/fabric8/src/main/java/org/arquillian/cube/kubernetes/fabric8/impl/visitor/SecretsAndServiceAccountVisitor.java b/kubernetes/fabric8/src/main/java/org/arquillian/cube/kubernetes/fabric8/impl/visitor/SecretsAndServiceAccountVisitor.java index 630d01286..ba0934cc7 100644 --- a/kubernetes/fabric8/src/main/java/org/arquillian/cube/kubernetes/fabric8/impl/visitor/SecretsAndServiceAccountVisitor.java +++ b/kubernetes/fabric8/src/main/java/org/arquillian/cube/kubernetes/fabric8/impl/visitor/SecretsAndServiceAccountVisitor.java @@ -36,12 +36,12 @@ public void visit(Object element) { if (element instanceof PodBuilder) { PodBuilder builder = (PodBuilder) element; - serviceAccount = builder.getSpec().getServiceAccountName(); - secrets.addAll(generateSecrets(builder.getMetadata())); + serviceAccount = builder.buildSpec().getServiceAccountName(); + secrets.addAll(generateSecrets(builder.buildMetadata())); } else if (element instanceof PodTemplateSpecBuilder) { PodTemplateSpecBuilder builder = (PodTemplateSpecBuilder) element; - serviceAccount = builder.getSpec().getServiceAccountName(); - secrets.addAll(generateSecrets(builder.getMetadata())); + serviceAccount = builder.buildSpec().getServiceAccountName(); + secrets.addAll(generateSecrets(builder.buildMetadata())); } } @@ -65,20 +65,17 @@ private void createServiceAccount(String serviceAccount, Set secrets) { if (client.serviceAccounts().inNamespace(configuration.getNamespace()).withName(serviceAccount).get() == null) { - /** rls TODO https://github.com/arquillian/arquillian-cube/issues/1291 - client.serviceAccounts().inNamespace(configuration.getNamespace()).createNew() + + client.serviceAccounts().inNamespace(configuration.getNamespace()).create(new io.fabric8.kubernetes.api.model.ServiceAccountBuilder() .withNewMetadata() .withName(serviceAccount) .endMetadata() .withSecrets(refs) - .done(); - **/ + .build()); } else { - /** rls TODO https://github.com/arquillian/arquillian-cube/issues/1291 - client.serviceAccounts().inNamespace(configuration.getNamespace()).withName(serviceAccount).edit() + client.serviceAccounts().inNamespace(configuration.getNamespace()).withName(serviceAccount).edit( s -> new io.fabric8.kubernetes.api.model.ServiceAccountBuilder(s) .withSecrets(refs) - .done(); - **/ + .build()); } } @@ -108,14 +105,13 @@ private Set generateSecrets(ObjectMeta meta) { for (String c : Secrets.getContents(value, name)) { data.put(c, keyType.generate()); } - /** rls TODO https://github.com/arquillian/arquillian-cube/issues/1291 - secret = client.secrets().inNamespace(configuration.getNamespace()).createNew() + + secret = client.secrets().inNamespace(configuration.getNamespace()).create(new io.fabric8.kubernetes.api.model.SecretBuilder() .withNewMetadata() .withName(name) .endMetadata() .withData(data) - .done(); - **/ + .build()); secrets.add(secret); } } diff --git a/kubernetes/ftest-kubernetes-assistant/pom.xml b/kubernetes/ftest-kubernetes-assistant/pom.xml index 67cdfa88c..fddd40cc8 100644 --- a/kubernetes/ftest-kubernetes-assistant/pom.xml +++ b/kubernetes/ftest-kubernetes-assistant/pom.xml @@ -16,6 +16,17 @@ arquillian-cube-kubernetes-assistant-standalone-ftest + + io.fabric8 + kubernetes-client + test + + + io.sundr + builder-annotations + 0.103.1 + test + org.arquillian.cube arquillian-cube-requirement @@ -36,6 +47,11 @@ junit test + + io.rest-assured + rest-assured + test + diff --git a/kubernetes/ftest-kubernetes-assistant/src/test/java/org/arquillian/cube/kubernetes/assistant/HelloWorldKubernetesAssistantTest.java b/kubernetes/ftest-kubernetes-assistant/src/test/java/org/arquillian/cube/kubernetes/assistant/HelloWorldKubernetesAssistantTest.java index 4b348c37a..5db28d1df 100644 --- a/kubernetes/ftest-kubernetes-assistant/src/test/java/org/arquillian/cube/kubernetes/assistant/HelloWorldKubernetesAssistantTest.java +++ b/kubernetes/ftest-kubernetes-assistant/src/test/java/org/arquillian/cube/kubernetes/assistant/HelloWorldKubernetesAssistantTest.java @@ -1,8 +1,7 @@ package org.arquillian.cube.kubernetes.assistant; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.jdkhttp.JdkHttpClientFactory; import org.arquillian.cube.kubernetes.impl.KubernetesAssistant; import org.arquillian.cube.kubernetes.impl.requirement.RequiresKubernetes; import org.arquillian.cube.requirement.ArquillianConditionalRunner; @@ -15,7 +14,11 @@ import java.net.URL; import java.util.Optional; +import static io.restassured.RestAssured.given; import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.Matchers.hasKey; // tag::k8_assistant_example[] @RunWith(ArquillianConditionalRunner.class) @@ -36,13 +39,13 @@ public void should_apply_route_programmatically() throws IOException { kubernetesAssistant.deployApplication("hello-world"); // <1> Optional serviceUrl = kubernetesAssistant.getServiceUrl("hello-world"); // <2> - OkHttpClient okHttpClient = new OkHttpClient(); - Request request = new Request.Builder().get().url(serviceUrl.get()).build(); - Response response = okHttpClient.newCall(request).execute(); - - assertThat(response).isNotNull(); - assertThat(response.code()).isEqualTo(200); - assertThat(response.body().string()).isEqualTo("Hello OpenShift!\n"); + given() + .when() + .get(serviceUrl.get()) + .then() + .assertThat() + .statusCode(200) + .body(is("Hello OpenShift!\n")); } } // end::k8_assistant_example[] diff --git a/kubernetes/ftest-kubernetes/pom.xml b/kubernetes/ftest-kubernetes/pom.xml index e2cc09d24..924a419e4 100644 --- a/kubernetes/ftest-kubernetes/pom.xml +++ b/kubernetes/ftest-kubernetes/pom.xml @@ -25,6 +25,11 @@ junit test + + io.rest-assured + rest-assured + test + diff --git a/kubernetes/ftest-kubernetes/src/test/java/HelloWorldIT.java b/kubernetes/ftest-kubernetes/src/test/java/HelloWorldIT.java index c3c27d12b..8a63be01c 100644 --- a/kubernetes/ftest-kubernetes/src/test/java/HelloWorldIT.java +++ b/kubernetes/ftest-kubernetes/src/test/java/HelloWorldIT.java @@ -1,9 +1,10 @@ import io.fabric8.kubernetes.api.model.Service; import java.io.IOException; import java.net.URL; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; + +import io.restassured.RestAssured; +import io.restassured.builder.RequestSpecBuilder; +import io.restassured.specification.RequestSpecification; import org.arquillian.cube.kubernetes.annotations.Named; import org.arquillian.cube.kubernetes.annotations.PortForward; import org.arquillian.cube.kubernetes.impl.requirement.RequiresKubernetes; @@ -14,6 +15,9 @@ import org.junit.runner.RunWith; import static junit.framework.TestCase.assertFalse; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.hasKey; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -43,15 +47,15 @@ public void shouldFindServiceInstance() throws IOException { @Test public void shouldShowHelloWorld() throws IOException { assertNotNull(url); - OkHttpClient okHttpClient = new OkHttpClient(); - Request request = new Request.Builder().get().url(url).build(); - //#641 mentions issues on repeated calls to the portforwarded service. for (int i = 0; i < 5; i++) { - Response response = okHttpClient.newCall(request).execute(); - assertNotNull(response); - assertEquals(200, response.code()); - assertTrue(response.body().string().contains("Hello OpenShift!\n")); + RestAssured.given() + .when() + .get(url) + .then() + .assertThat() + .statusCode(200) + .body(contains("Hello OpenShift!\n")); } } } diff --git a/kubernetes/istio/istio/pom.xml b/kubernetes/istio/istio/pom.xml index 0874c76f9..2be60b967 100644 --- a/kubernetes/istio/istio/pom.xml +++ b/kubernetes/istio/istio/pom.xml @@ -28,14 +28,31 @@ org.awaitility awaitility + + org.hamcrest + hamcrest + compile + org.arquillian.cube arquillian-cube-istio-kubernetes-api ${project.version} - me.snowdrop - istio-client-uberjar + io.fabric8 + istio-client + + + org.jboss.arquillian.test + arquillian-test-spi + + + io.github.lukehutch + fast-classpath-scanner + + + io.fabric8 + kubernetes-httpclient-jdk org.mockito diff --git a/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioAssistant.java b/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioAssistant.java index e8e5ac6bc..87512e767 100644 --- a/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioAssistant.java +++ b/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioAssistant.java @@ -1,9 +1,17 @@ package org.arquillian.cube.istio.impl; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpRequest; +import io.fabric8.kubernetes.client.http.HttpResponse; +import io.fabric8.kubernetes.client.jdkhttp.JdkHttpClientFactory; import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner; import io.github.lukehutch.fastclasspathscanner.matchprocessor.FileMatchProcessor; +import org.arquillian.cube.kubernetes.impl.utils.ResourceFilter; +import org.awaitility.Awaitility; + import java.io.IOException; import java.io.InputStream; +import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; @@ -11,31 +19,29 @@ import java.util.List; import java.util.concurrent.TimeUnit; import java.util.function.Function; -import me.snowdrop.istio.api.IstioResource; -import me.snowdrop.istio.client.IstioClient; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import org.arquillian.cube.kubernetes.impl.utils.ResourceFilter; -import org.awaitility.Awaitility; public class IstioAssistant { - private final IstioClient istioClient; - private final OkHttpClient httpClient; + private final HttpClient.Factory httpClientFactory = new JdkHttpClientFactory(); + private final HttpClient httpClient; + private final IstioClientAdapter istioClientAdapter; - public IstioAssistant(IstioClient istioClient) { - this.istioClient = istioClient; - this.httpClient = new OkHttpClient(); + public IstioAssistant(IstioClientAdapter istioClientAdapter) { + this.httpClient = httpClientFactory.newBuilder().build(); + this.istioClientAdapter = istioClientAdapter; } public List deployIstioResources(final InputStream inputStream) { - return istioClient.registerCustomResources(inputStream); + return istioClientAdapter.registerCustomResources(inputStream); + } + + public void undeployIstioResource(final IstioResource istioResource) { + istioClientAdapter.unregisterCustomResource(istioResource); } public void undeployIstioResources(final List istioResources) { for (IstioResource istioResource : istioResources) { - istioClient.unregisterCustomResource(istioResource); + undeployIstioResource(istioResource); } } @@ -112,27 +118,23 @@ public List deployIstioResources(final Path directory) throws IOE * @return */ public List deployIstioResources(String content) { - return istioClient.registerCustomResources(content); + return istioClientAdapter.registerCustomResources(content); } - public void await(final URL url, Function checker) { - final Request request = new Request.Builder() - .url(url) + public void await(final URL url, Function, Boolean> checker) throws URISyntaxException { + final HttpRequest request = httpClient.newHttpRequestBuilder() + .uri(url.toURI().toString()) .build(); this.await(request, checker); } - public void await(final Request request, Function checker) { - /** rls TODO https://github.com/arquillian/arquillian-cube/issues/1282 + public void await(final HttpRequest request, Function, Boolean> checker) { Awaitility.await() .atMost(30, TimeUnit.SECONDS) .ignoreExceptions() .until(() -> { - try (Response response = httpClient.newCall(request).execute()) { - return checker.apply(response); - } + return checker.apply(httpClient.sendAsync(request, String.class).get()); }); - **/ } } diff --git a/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioAssistantCreator.java b/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioAssistantCreator.java index 05c50e06d..e6db78e6d 100644 --- a/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioAssistantCreator.java +++ b/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioAssistantCreator.java @@ -1,6 +1,6 @@ package org.arquillian.cube.istio.impl; -import me.snowdrop.istio.client.IstioClient; +import io.fabric8.istio.client.IstioClient; import org.jboss.arquillian.core.api.InstanceProducer; import org.jboss.arquillian.core.api.annotation.ApplicationScoped; import org.jboss.arquillian.core.api.annotation.Inject; @@ -13,7 +13,7 @@ public class IstioAssistantCreator { private InstanceProducer istioAssistantInstanceProducer; public void createIstioAssistant(@Observes IstioClient istioClient) { - IstioAssistant istioAssistant = new IstioAssistant(istioClient); + IstioAssistant istioAssistant = new IstioAssistant(new IstioClientAdapter(istioClient)); istioAssistantInstanceProducer.set(istioAssistant); } } diff --git a/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioClientAdapter.java b/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioClientAdapter.java new file mode 100644 index 000000000..f348418bc --- /dev/null +++ b/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioClientAdapter.java @@ -0,0 +1,156 @@ +package org.arquillian.cube.istio.impl; + +import io.fabric8.istio.client.IstioClient; +import io.fabric8.istio.client.V1alpha3APIGroupDSL; +import io.fabric8.istio.client.V1beta1APIGroupDSL; +import io.fabric8.kubernetes.api.model.APIGroup; +import io.fabric8.kubernetes.api.model.APIGroupList; +import io.fabric8.kubernetes.api.model.APIResourceList; +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.fabric8.kubernetes.api.model.KubernetesResource; +import io.fabric8.kubernetes.api.model.KubernetesResourceList; +import io.fabric8.kubernetes.api.model.RootPaths; +import io.fabric8.kubernetes.client.Client; +import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.RequestConfig; +import io.fabric8.kubernetes.client.dsl.MixedOperation; +import io.fabric8.kubernetes.client.dsl.Resource; +import io.fabric8.kubernetes.client.http.HttpClient; + +import java.io.InputStream; +import java.net.URL; +import java.util.Collections; +import java.util.List; + +public class IstioClientAdapter implements IstioClient { + + private final IstioClient istioClient; + private final MixedOperation> resourceOperation; + + + public IstioClientAdapter(final IstioClient istioClient) { + this.istioClient = istioClient; + this.resourceOperation = istioClient.resources(IstioResource.class, IstioResourceList.class); + } + + public List registerCustomResources(final InputStream resource) { + return Collections.singletonList(resourceOperation.load(resource).create()); + } + + public List registerCustomResources(final String resource) { + return Collections.singletonList(resourceOperation.load(resource).create()); + } + + public Boolean unregisterCustomResource(final IstioResource istioResource) { + return resourceOperation.resource(istioResource).delete().stream().allMatch(d -> d.getCauses().isEmpty()); + } + + public IstioClient unwrap() { + return istioClient; + } + + @Override + public V1beta1APIGroupDSL v1beta1() { + return unwrap().v1beta1(); + } + + @Override + public V1alpha3APIGroupDSL v1alpha3() { + return unwrap().v1alpha3(); + } + + @Override + public Boolean isAdaptable(Class type) { + return unwrap().isAdaptable(type); + } + + @Override + public boolean supports(Class type) { + return unwrap().supports(type); + } + + @Override + public boolean supports(String apiVersion, String kind) { + return unwrap().supports(apiVersion, kind); + } + + @Override + public boolean hasApiGroup(String apiGroup, boolean exact) { + return unwrap().hasApiGroup(apiGroup, exact); + } + + @Override + public C adapt(Class type) { + return unwrap().adapt(type); + } + + @Override + public URL getMasterUrl() { + return unwrap().getMasterUrl(); + } + + @Override + public String getApiVersion() { + return unwrap().getApiVersion(); + } + + @Override + public String getNamespace() { + return unwrap().getNamespace(); + } + + @Override + public RootPaths rootPaths() { + return unwrap().rootPaths(); + } + + @Override + public boolean supportsApiPath(String path) { + return unwrap().supportsApiPath(path); + } + + @Override + public void close() { + unwrap().close(); + } + + @Override + public APIGroupList getApiGroups() { + return unwrap().getApiGroups(); + } + + @Override + public APIGroup getApiGroup(String name) { + return unwrap().getApiGroup(name); + } + + @Override + public APIResourceList getApiResources(String groupVersion) { + return unwrap().getApiResources(groupVersion); + } + + @Override + public , R extends Resource> MixedOperation resources(Class resourceType, Class listClass, Class resourceClass) { + return unwrap().resources(resourceType, listClass, resourceClass); + } + + @Override + public Client newClient(RequestConfig requestConfig) { + return unwrap().newClient(requestConfig); + } + + @Override + public HttpClient getHttpClient() { + return unwrap().getHttpClient(); + } + + @Override + public Config getConfiguration() { + return unwrap().getConfiguration(); + } + + @Override + public String raw(String uri, String method, Object payload) { + return unwrap().raw(uri, method, payload); + } +} diff --git a/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioClientCreator.java b/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioClientCreator.java index a08e3984c..bbf6687c1 100644 --- a/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioClientCreator.java +++ b/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioClientCreator.java @@ -1,7 +1,7 @@ package org.arquillian.cube.istio.impl; +import io.fabric8.istio.client.IstioClient; import io.fabric8.kubernetes.client.KubernetesClient; -import me.snowdrop.istio.client.IstioClient; import org.jboss.arquillian.core.api.InstanceProducer; import org.jboss.arquillian.core.api.annotation.ApplicationScoped; import org.jboss.arquillian.core.api.annotation.Inject; @@ -15,7 +15,7 @@ public class IstioClientCreator { public void createIstioClient(@Observes final KubernetesClient client) { - IstioClient istioClient = client.adapt(IstioClient.class); + IstioClient istioClient = client.adapt(IstioClientAdapter.class); istioClientInstanceProducer.set(istioClient); } diff --git a/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioResource.java b/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioResource.java new file mode 100644 index 000000000..430ad7220 --- /dev/null +++ b/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioResource.java @@ -0,0 +1,6 @@ +package org.arquillian.cube.istio.impl; + +import io.fabric8.kubernetes.api.model.GenericKubernetesResource; + +public class IstioResource extends GenericKubernetesResource { +} diff --git a/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioResourceList.java b/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioResourceList.java new file mode 100644 index 000000000..08209dd3d --- /dev/null +++ b/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioResourceList.java @@ -0,0 +1,9 @@ +package org.arquillian.cube.istio.impl; + +import io.fabric8.istio.api.meta.v1alpha1.IstioStatus; +import io.fabric8.kubernetes.api.model.DefaultKubernetesResourceList; +import io.fabric8.kubernetes.api.model.KubernetesResourceList; +import io.fabric8.kubernetes.client.CustomResource; + +public class IstioResourceList extends DefaultKubernetesResourceList { +} diff --git a/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioResourcesApplier.java b/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioResourcesApplier.java index 0796042a6..ae7c064ad 100644 --- a/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioResourcesApplier.java +++ b/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioResourcesApplier.java @@ -1,16 +1,6 @@ package org.arquillian.cube.istio.impl; import io.fabric8.kubernetes.api.model.ObjectMeta; -import java.io.BufferedInputStream; -import java.io.IOException; -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Logger; -import me.snowdrop.istio.client.IstioClient; import org.arquillian.cube.istio.api.IstioResource; import org.arquillian.cube.istio.api.RestoreIstioResource; import org.arquillian.cube.kubernetes.impl.resolver.ResourceResolver; @@ -23,14 +13,25 @@ import org.jboss.arquillian.test.spi.event.suite.Before; import org.jboss.arquillian.test.spi.event.suite.BeforeClass; +import java.io.BufferedInputStream; +import java.io.IOException; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Logger; + public class IstioResourcesApplier { private static final Logger log = Logger.getLogger(KubernetesResourcesApplier.class.getName()); - private Map> resourcesMap = new ConcurrentHashMap<>(); - private Map> restoredResourcesMap = new ConcurrentHashMap<>(); + private Map> resourcesMap = new ConcurrentHashMap<>(); + private Map> restoredResourcesMap = new ConcurrentHashMap<>(); - public void applyIstioResourcesAtClassScope(@Observes(precedence = -20) BeforeClass beforeClass, final IstioClient istioClient) { + + public void applyIstioResourcesAtClassScope(@Observes(precedence = -20) BeforeClass beforeClass, final IstioClientAdapter istioClient) { final TestClass testClass = beforeClass.getTestClass(); log.info(String.format("Creating Istio resource for %s", testClass.getName())); @@ -38,7 +39,7 @@ public void applyIstioResourcesAtClassScope(@Observes(precedence = -20) BeforeCl createResources(createResourceKey(testClass), istioClient, findAnnotations(testClass)); } - public void applyIstioResourcesAtMethodScope(@Observes(precedence = -20) Before beforeMethod, final IstioClient istioClient) { + public void applyIstioResourcesAtMethodScope(@Observes(precedence = -20) Before beforeMethod, final IstioClientAdapter istioClient) { final TestClass testClass = beforeMethod.getTestClass(); final Method testMethod = beforeMethod.getTestMethod(); @@ -47,7 +48,7 @@ public void applyIstioResourcesAtMethodScope(@Observes(precedence = -20) Before createResources(createResourceKey(testMethod), istioClient, findAnnotations(testMethod)); } - public void removeIstioResourcesAtClassScope(@Observes(precedence = 20) AfterClass afterClass, final IstioClient istioClient) { + public void removeIstioResourcesAtClassScope(@Observes(precedence = 20) AfterClass afterClass, final IstioClientAdapter istioClient) { final TestClass testClass = afterClass.getTestClass(); log.info(String.format("Deleting Istio resource for %s", testClass.getName())); @@ -55,7 +56,7 @@ public void removeIstioResourcesAtClassScope(@Observes(precedence = 20) AfterCla deleteResources(createResourceKey(testClass), istioClient, findRestoreAnnotations(testClass)); } - public void removeIstioResourcesAtMethodScope(@Observes(precedence = 20) After afterMethod, final IstioClient istioClient) { + public void removeIstioResourcesAtMethodScope(@Observes(precedence = 20) After afterMethod, final IstioClientAdapter istioClient) { final TestClass testClass = afterMethod.getTestClass(); final Method testMethod = afterMethod.getTestMethod(); @@ -72,7 +73,7 @@ private String createResourceKey(Method testMethod) { return testMethod.getDeclaringClass().getName() + "_" + testMethod.getName(); } - private void createResources(String resourceKey, IstioClient istioClient, + private void createResources(String resourceKey, IstioClientAdapter istioClient, IstioResource[] annotations) { Arrays.stream(annotations) .map(IstioResource::value) @@ -87,7 +88,7 @@ private void createResources(String resourceKey, IstioClient istioClient, }); } - private void deleteResources(String resourceKey, IstioClient istioClient, RestoreIstioResource[] annotations) { + private void deleteResources(String resourceKey, IstioClientAdapter istioClient, RestoreIstioResource[] annotations) { // We apply the restore method first so the restored rules are populated. createRestoreResources(resourceKey, istioClient, annotations); @@ -96,25 +97,24 @@ private void deleteResources(String resourceKey, IstioClient istioClient, Restor return; } try { - final List istioResources = resourcesMap.get(resourceKey); + final List istioResources = resourcesMap.get(resourceKey); - for (me.snowdrop.istio.api.IstioResource resource : istioResources) { + for (org.arquillian.cube.istio.impl.IstioResource resource : istioResources) { // If no restore or an Istio Resource has not been restored then we need to delete if(!restoredResourcesMap.containsKey(resourceKey) || !restored(resourceKey, resource.getMetadata())) { istioClient.unregisterCustomResource(resource); } } - } finally { resourcesMap.remove(resourceKey); } } private boolean restored(String resourceKey, ObjectMeta istioResourceToDelete) { - final List listRestoredIstioResources = restoredResourcesMap.get(resourceKey); + final List listRestoredIstioResources = restoredResourcesMap.get(resourceKey); - for (me.snowdrop.istio.api.IstioResource restoredIstioResources : listRestoredIstioResources) { + for (org.arquillian.cube.istio.impl.IstioResource restoredIstioResources : listRestoredIstioResources) { final ObjectMeta restoredMetadata = restoredIstioResources.getMetadata(); if (restoredMetadata.getName().equals(istioResourceToDelete.getName()) && restoredMetadata.getNamespace().equals(istioResourceToDelete.getNamespace())) { @@ -126,7 +126,7 @@ private boolean restored(String resourceKey, ObjectMeta istioResourceToDelete) { } - private void createRestoreResources(String resourceKey, IstioClient istioClient, + private void createRestoreResources(String resourceKey, IstioClientAdapter istioClient, RestoreIstioResource[] annotations) { Arrays.stream(annotations) .map(RestoreIstioResource::value) @@ -134,7 +134,8 @@ private void createRestoreResources(String resourceKey, IstioClient istioClient, .map(ResourceResolver::resolve) .forEach(istioResource -> { try (BufferedInputStream istioResourceStream = new BufferedInputStream(istioResource.openStream()) ) { - restoredResourcesMap.put(resourceKey, istioClient.registerCustomResources(istioResourceStream)); + restoredResourcesMap.put(resourceKey, + istioClient.registerCustomResources(istioResourceStream)); } catch (IOException e) { throw new IllegalStateException(e); } @@ -187,11 +188,11 @@ private RestoreIstioResource[] findRestoreAnnotations(Method testMethod) { return new RestoreIstioResource[0]; } - public Map> getResourcesMap() { + public Map> getResourcesMap() { return Collections.unmodifiableMap(resourcesMap); } - public Map> getRestoredResourcesMap() { + public Map> getRestoredResourcesMap() { return Collections.unmodifiableMap(restoredResourcesMap); } } diff --git a/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioSpec.java b/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioSpec.java new file mode 100644 index 000000000..d6f8fcc76 --- /dev/null +++ b/kubernetes/istio/istio/src/main/java/org/arquillian/cube/istio/impl/IstioSpec.java @@ -0,0 +1,6 @@ +package org.arquillian.cube.istio.impl; + +import io.fabric8.kubernetes.api.model.GenericKubernetesResource; + +public class IstioSpec extends GenericKubernetesResource { +} diff --git a/kubernetes/istio/istio/src/test/java/org/arquillian/cube/istio/impl/IstioAssistantTest.java b/kubernetes/istio/istio/src/test/java/org/arquillian/cube/istio/impl/IstioAssistantTest.java index 3802ae054..e50ef65fe 100644 --- a/kubernetes/istio/istio/src/test/java/org/arquillian/cube/istio/impl/IstioAssistantTest.java +++ b/kubernetes/istio/istio/src/test/java/org/arquillian/cube/istio/impl/IstioAssistantTest.java @@ -1,35 +1,35 @@ package org.arquillian.cube.istio.impl; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; -import me.snowdrop.istio.api.IstioResource; -import me.snowdrop.istio.client.IstioClient; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; + @RunWith(MockitoJUnitRunner.class) public class IstioAssistantTest { @Mock - private IstioClient istioClient; + private IstioClientAdapter istioClientAdapter; @Mock private IstioResource istioResource; @Before public void setup_mock_expectations() { - when(istioClient.registerCustomResources(any(InputStream.class))) + when(istioClientAdapter.registerCustomResources(any(InputStream.class))) .thenReturn(Arrays.asList(istioResource)); } @@ -37,7 +37,7 @@ public void setup_mock_expectations() { public void should_load_route_from_url() throws IOException { // given - final IstioAssistant istioAssistant = new IstioAssistant(istioClient); + final IstioAssistant istioAssistant = new IstioAssistant(istioClientAdapter); // when final URL resource = @@ -45,8 +45,7 @@ public void should_load_route_from_url() throws IOException { final List istioResources = istioAssistant.deployIstioResources(resource); // then - assertThat(istioResources) - .hasSize(1); + assertThat(istioResources).isNotNull(); } @@ -54,7 +53,7 @@ public void should_load_route_from_url() throws IOException { public void should_load_all_routes_from_classpath() { // given - final IstioAssistant istioAssistant = new IstioAssistant((istioClient)); + final IstioAssistant istioAssistant = new IstioAssistant(istioClientAdapter); // when final List istioResources = @@ -69,7 +68,7 @@ public void should_load_all_routes_from_classpath() { public void should_load_all_routes_from_path() throws IOException { // given - final IstioAssistant istioAssistant = new IstioAssistant(istioClient); + final IstioAssistant istioAssistant = new IstioAssistant(istioClientAdapter); // when final List istioResources = diff --git a/kubernetes/istio/istio/src/test/java/org/arquillian/cube/istio/impl/IstioClientAdapterTest.java b/kubernetes/istio/istio/src/test/java/org/arquillian/cube/istio/impl/IstioClientAdapterTest.java new file mode 100644 index 000000000..fe939f455 --- /dev/null +++ b/kubernetes/istio/istio/src/test/java/org/arquillian/cube/istio/impl/IstioClientAdapterTest.java @@ -0,0 +1,110 @@ +package org.arquillian.cube.istio.impl; + +import io.fabric8.istio.client.IstioClient; +import io.fabric8.kubernetes.client.dsl.MixedOperation; +import io.fabric8.kubernetes.client.dsl.Resource; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class IstioClientAdapterTest { + @Mock + Resource loadedResource; + @Mock + MixedOperation> resources; + @Mock + private IstioClient istioClient; + + @Before + public void setup_mock_expectations() { + when(istioClient.resources(IstioResource.class, IstioResourceList.class)).thenReturn(resources); + when(resources.load(any(InputStream.class))).thenReturn(loadedResource); + when(resources.load(any(String.class))).thenReturn(loadedResource); + when(resources.resource(any(IstioResource.class))).thenReturn(loadedResource); + when(loadedResource.create()).thenReturn(new IstioResource()); + when(loadedResource.delete()).thenReturn(Collections.emptyList()); + } + + @Test + public void should_deploy_from_input_stream() throws IOException { + + // given + final IstioClientAdapter istioClientAdapter = new IstioClientAdapter(istioClient); + + // when + final URL resource = + Thread.currentThread().getContextClassLoader().getResource("route-rule-reviews-test-v2.yaml"); + try (InputStream is = resource.openStream()) { + final List istioResources = istioClientAdapter.registerCustomResources(is); + + // then + assertThat(istioResources).isNotNull(); + assertThat(istioResources).isNotEmpty(); + assertThat(istioResources).hasSize(1); + } + } + + @Test + public void should_deploy_from_string() throws IOException { + + // given + final IstioClientAdapter istioClientAdapter = new IstioClientAdapter(istioClient); + + // when + final URL resource = + Thread.currentThread().getContextClassLoader().getResource("route-rule-reviews-test-v2.yaml"); + try (InputStream in = resource.openStream()) { + byte[] bytes = in.readAllBytes(); + final List istioResources = istioClientAdapter.registerCustomResources(new String(bytes, StandardCharsets.UTF_8)); + + // then + assertThat(istioResources).isNotNull(); + assertThat(istioResources).isNotEmpty(); + assertThat(istioResources).hasSize(1); + } + } + + @Test + public void should_undeploy() throws IOException { + + // given + final IstioClientAdapter istioClientAdapter = new IstioClientAdapter(istioClient); + + // when + final URL resource = + Thread.currentThread().getContextClassLoader().getResource("route-rule-reviews-test-v2.yaml"); + try (InputStream is = resource.openStream()) { + final List istioResources = istioClientAdapter.registerCustomResources(is); + + Boolean result = istioClientAdapter.unregisterCustomResource(istioResources.get(0)); + + // then + assertThat(result).isTrue(); + } + } + + @Test + public void should_unwrap() { + // given + final IstioClientAdapter istioClientAdapter = new IstioClientAdapter(istioClient); + // when + final IstioClient unwrapped = istioClientAdapter.unwrap(); + // then + assertThat(unwrapped).isNotNull(); + assertThat(unwrapped).isInstanceOf(IstioClient.class); + } +} diff --git a/kubernetes/istio/istio/src/test/java/org/arquillian/cube/istio/impl/IstioResourcesApplierTest.java b/kubernetes/istio/istio/src/test/java/org/arquillian/cube/istio/impl/IstioResourcesApplierTest.java index 08c55f59c..a1fd4d3ff 100644 --- a/kubernetes/istio/istio/src/test/java/org/arquillian/cube/istio/impl/IstioResourcesApplierTest.java +++ b/kubernetes/istio/istio/src/test/java/org/arquillian/cube/istio/impl/IstioResourcesApplierTest.java @@ -1,10 +1,6 @@ package org.arquillian.cube.istio.impl; import io.fabric8.kubernetes.api.model.ObjectMeta; -import java.io.InputStream; -import java.util.Arrays; -import me.snowdrop.istio.api.IstioResource; -import me.snowdrop.istio.client.IstioClient; import org.arquillian.cube.istio.api.RestoreIstioResource; import org.jboss.arquillian.test.spi.event.suite.AfterClass; import org.jboss.arquillian.test.spi.event.suite.BeforeClass; @@ -13,8 +9,13 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Collections; + import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -23,7 +24,7 @@ public class IstioResourcesApplierTest { @Mock - private IstioClient istioClient; + private IstioClientAdapter istioClientAdapter; @Mock private IstioResource istioResource; @@ -43,19 +44,19 @@ public void should_apply_tests_with_istio_resources() { // Given final BeforeClass beforeClass = new BeforeClass(TestWithIstioResource.class); final IstioResourcesApplier istioResourceApplier = createIstioResourceApplier(); - when(istioClient.registerCustomResources(any(InputStream.class))) + when(istioClientAdapter.registerCustomResources(any(InputStream.class))) .thenReturn(Arrays.asList(istioResource)); // When - istioResourceApplier.applyIstioResourcesAtClassScope(beforeClass, istioClient); + istioResourceApplier.applyIstioResourcesAtClassScope(beforeClass, istioClientAdapter); // Then - verify(istioClient, times(1)).registerCustomResources(any(InputStream.class)); + verify(istioClientAdapter, times(1)).registerCustomResources(any(InputStream.class)); assertThat(istioResourceApplier.getResourcesMap()) .hasSize(1) - .containsValue(Arrays.asList(istioResource)); + .containsValue(Collections.singletonList(istioResource)); assertThat(istioResourceApplier.getRestoredResourcesMap()) .hasSize(0); } @@ -66,18 +67,18 @@ public void should_apply_tests_with_istio_resources_and_restore() { // Given final BeforeClass beforeClass = new BeforeClass(TestWithIstioResourceAndRestore.class); final IstioResourcesApplier istioResourceApplier = createIstioResourceApplier(); - when(istioClient.registerCustomResources(any(InputStream.class))) + when(istioClientAdapter.registerCustomResources(any(InputStream.class))) .thenReturn(Arrays.asList(istioResource)); // When - istioResourceApplier.applyIstioResourcesAtClassScope(beforeClass, istioClient); + istioResourceApplier.applyIstioResourcesAtClassScope(beforeClass, istioClientAdapter); // Then - verify(istioClient, times(1)).registerCustomResources(any(InputStream.class)); + verify(istioClientAdapter, times(1)).registerCustomResources(any(InputStream.class)); assertThat(istioResourceApplier.getResourcesMap()) - .hasSize(1) + .isNotNull() .containsValue(Arrays.asList(istioResource)); assertThat(istioResourceApplier.getRestoredResourcesMap()) .hasSize(0); @@ -89,18 +90,18 @@ public void should_delete_registered_istio_resources() { // Given final BeforeClass beforeClass = new BeforeClass(TestWithIstioResource.class); final IstioResourcesApplier istioResourceApplier = createIstioResourceApplier(); - when(istioClient.registerCustomResources(any(InputStream.class))) + when(istioClientAdapter.registerCustomResources(any(InputStream.class))) .thenReturn(Arrays.asList(istioResource)); - istioResourceApplier.applyIstioResourcesAtClassScope(beforeClass, istioClient); + istioResourceApplier.applyIstioResourcesAtClassScope(beforeClass, istioClientAdapter); // When - istioResourceApplier.removeIstioResourcesAtClassScope(new AfterClass(TestWithIstioResource.class), istioClient); + istioResourceApplier.removeIstioResourcesAtClassScope(new AfterClass(TestWithIstioResource.class), istioClientAdapter); // Then - verify(istioClient, times(1)).unregisterCustomResource(istioResource); + verify(istioClientAdapter, times(1)).unregisterCustomResource(istioResource); } @Test @@ -109,18 +110,18 @@ public void should_delete_registered_istio_resources_and_restore() { // Given final BeforeClass beforeClass = new BeforeClass(TestWithIstioResourceAndRestore.class); final IstioResourcesApplier istioResourceApplier = createIstioResourceApplier(); - when(istioClient.registerCustomResources(any(InputStream.class))) + when(istioClientAdapter.registerCustomResources(any(InputStream.class))) .thenReturn(Arrays.asList(istioResource)); - istioResourceApplier.applyIstioResourcesAtClassScope(beforeClass, istioClient); + istioResourceApplier.applyIstioResourcesAtClassScope(beforeClass, istioClientAdapter); // When - istioResourceApplier.removeIstioResourcesAtClassScope(new AfterClass(TestWithIstioResourceAndRestore.class), istioClient); + istioResourceApplier.removeIstioResourcesAtClassScope(new AfterClass(TestWithIstioResourceAndRestore.class), istioClientAdapter); // Then - verify(istioClient, times(2)).registerCustomResources(any(InputStream.class)); - verify(istioClient, times(0)).unregisterCustomResource(istioResource); + verify(istioClientAdapter, times(2)).registerCustomResources(any(InputStream.class)); + verify(istioClientAdapter, times(0)).unregisterCustomResource(istioResource); } @Test @@ -129,18 +130,18 @@ public void should_delete_registered_istio_resources_and_not_restore_if_resource // Given final BeforeClass beforeClass = new BeforeClass(TestWithIstioResourceAndRestore.class); final IstioResourcesApplier istioResourceApplier = createIstioResourceApplier(); - when(istioClient.registerCustomResources(any(InputStream.class))) + when(istioClientAdapter.registerCustomResources(any(InputStream.class))) .thenReturn(Arrays.asList(istioResource), Arrays.asList(istioResource2)); - istioResourceApplier.applyIstioResourcesAtClassScope(beforeClass, istioClient); + istioResourceApplier.applyIstioResourcesAtClassScope(beforeClass, istioClientAdapter); // When - istioResourceApplier.removeIstioResourcesAtClassScope(new AfterClass(TestWithIstioResourceAndRestore.class), istioClient); + istioResourceApplier.removeIstioResourcesAtClassScope(new AfterClass(TestWithIstioResourceAndRestore.class), istioClientAdapter); // Then - verify(istioClient, times(2)).registerCustomResources(any(InputStream.class)); - verify(istioClient, times(1)).unregisterCustomResource(istioResource); + verify(istioClientAdapter, times(2)).registerCustomResources(any(InputStream.class)); + verify(istioClientAdapter, times(1)).unregisterCustomResource(istioResource); } private IstioResourcesApplier createIstioResourceApplier() { @@ -151,10 +152,10 @@ private IstioResourcesApplier createIstioResourceApplier() { when(istioResource2.getMetadata()).thenReturn(meta2); when(meta2.getName()).thenReturn("different"); - when(meta2.getNamespace()).thenReturn("tutorial"); + lenient().when(meta2.getNamespace()).thenReturn("tutorial"); - when(istioClient.registerCustomResources(any(InputStream.class))) - .thenReturn(Arrays.asList(istioResource), Arrays.asList(istioResource2)); + when(istioClientAdapter.unregisterCustomResource(any(IstioResource.class))) + .thenReturn(true); return new IstioResourcesApplier(); } diff --git a/kubernetes/kubernetes/pom.xml b/kubernetes/kubernetes/pom.xml index 02e49cdf7..419672406 100644 --- a/kubernetes/kubernetes/pom.xml +++ b/kubernetes/kubernetes/pom.xml @@ -39,12 +39,12 @@ fabric8-maven-plugin-build - com.squareup.okhttp3 - okhttp + io.fabric8 + kubernetes-client-api io.fabric8 - kubernetes-openshift-uberjar + openshift-client-api org.fusesource.jansi @@ -76,8 +76,6 @@ io.sundr builder-annotations 0.103.1 - compile - true @@ -98,7 +96,7 @@ io.fabric8 - mockwebserver + kubernetes-server-mock test @@ -119,10 +117,19 @@ org.awaitility awaitility + + org.hamcrest + hamcrest + compile + org.jboss.arquillian.config arquillian-config-impl-base + + io.fabric8 + kubernetes-httpclient-jdk + diff --git a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/DefaultConfiguration.java b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/DefaultConfiguration.java index 3e1d8b66a..4e046e7dd 100644 --- a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/DefaultConfiguration.java +++ b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/DefaultConfiguration.java @@ -26,7 +26,7 @@ import static org.arquillian.cube.impl.util.ConfigUtil.getLongProperty; import static org.arquillian.cube.impl.util.ConfigUtil.getStringProperty; -@Buildable(builderPackage = "io.fabric8.kubernetes.api.builder", generateBuilderPackage = false, editableEnabled = false) +@Buildable(generateBuilderPackage = false, editableEnabled = false, lazyCollectionInitEnabled = false, lazyMapInitEnabled = false) public class DefaultConfiguration implements Configuration { private static final String ENV_VAR_REGEX = "env.([a-zA-Z0-9_]+)"; @@ -43,6 +43,7 @@ public class DefaultConfiguration implements Configuration { private final URL environmentTeardownScriptUrl; private final URL environmentConfigUrl; + private final List environmentDependencies; private final boolean namespaceLazyCreateEnabled; @@ -534,7 +535,7 @@ public String toString() { if (masterUrl != null) { appendPropertyWithValue(content, MASTER_URL, masterUrl); } - if (!scriptEnvironmentVariables.isEmpty()) { + if (scriptEnvironmentVariables != null && !scriptEnvironmentVariables.isEmpty()) { appendPropertyWithValue(content, ENVIRONMENT_SCRIPT_ENV, scriptEnvironmentVariables); } if (environmentSetupScriptUrl != null) { @@ -547,7 +548,7 @@ public String toString() { if (environmentConfigUrl != null) { appendPropertyWithValue(content, ENVIRONMENT_CONFIG_URL, environmentConfigUrl); } - if (!environmentDependencies.isEmpty()) { + if (environmentDependencies != null && !environmentDependencies.isEmpty()) { appendPropertyWithValue(content, ENVIRONMENT_DEPENDENCIES, environmentDependencies.toString()); } @@ -570,7 +571,7 @@ public String toString() { appendPropertyWithValue(content, LOGS_COPY, logCopyEnabled); - if (!waitForServiceList.isEmpty()) { + if (waitForServiceList != null && !waitForServiceList.isEmpty()) { appendPropertyWithValue(content, WAIT_FOR_SERVICE_LIST, waitForServiceList); } if (logPath != null) { @@ -602,11 +603,11 @@ public String toString() { appendPropertyWithValue(content, FMP_POM_PATH, fmpPomPath); appendPropertyWithValue(content, FMP_DEBUG_OUTPUT, fmpDebugOutput); appendPropertyWithValue(content, FMP_LOGS, fmpLogsEnabled); - if (!fmpProfiles.isEmpty()) { + if (fmpProfiles != null && !fmpProfiles.isEmpty()) { appendPropertyWithValue(content, FMP_PROFILES, fmpProfiles); } - if (!fmpSystemProperties.isEmpty()) { + if (fmpSystemProperties != null && !fmpSystemProperties.isEmpty()) { appendPropertyWithValue(content, FMP_SYSTEM_PROPERTIES, fmpSystemProperties); } diff --git a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/KubernetesAssistant.java b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/KubernetesAssistant.java index 3e558d978..0d21d85f6 100644 --- a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/KubernetesAssistant.java +++ b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/KubernetesAssistant.java @@ -8,11 +8,12 @@ import io.fabric8.kubernetes.api.model.Service; import io.fabric8.kubernetes.api.model.ServicePort; import io.fabric8.kubernetes.api.model.apps.Deployment; +import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.dsl.NamespaceListVisitFromServerGetDeleteRecreateWaitApplicable; -import io.fabric8.kubernetes.client.internal.readiness.Readiness; +import io.fabric8.kubernetes.client.readiness.Readiness; import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner; import io.github.lukehutch.fastclasspathscanner.matchprocessor.FileMatchProcessor; import org.arquillian.cube.kubernetes.impl.portforward.PortForwarder; @@ -315,7 +316,7 @@ private int portForward(String podName, int targetPort, String namespace) { private int portForward(String podName, int sourcePort, int targetPort, String namespace) { try { - final io.fabric8.kubernetes.client.Config build = new ConfigBuilder(client.getConfiguration()).withNamespace(namespace).build(); + final Config build = new ConfigBuilder(client.getConfiguration()).withNamespace(namespace).build(); final PortForwarder portForwarder = new PortForwarder(build, podName); portForwarder.forwardPort(sourcePort, targetPort); return sourcePort; @@ -379,7 +380,7 @@ private void deleteWithRetries(HasMetadata metadata) { retryCounter++; try { // returns false when successfully deleted - deleteUnsucessful = client.resource(metadata).withGracePeriod(0).delete(); + deleteUnsucessful = client.resource(metadata).withGracePeriod(0).delete().stream().anyMatch(d -> !d.getCauses().isEmpty()); } catch (KubernetesClientException e) { try { TimeUnit.MILLISECONDS.sleep(500); @@ -409,15 +410,13 @@ public void awaitApplicationReadinessOrFail() { * @param applicationName name of the application to wait for pods readiness */ public void awaitApplicationReadinessOrFail(final String applicationName) { - /** rls TODO uncomment code and resolve compile issue. https://github.com/arquillian/arquillian-cube/issues/1282 - await().atMost(5, TimeUnit.MINUTES).until(() -> { + org.awaitility.Awaitility.await().atMost(5, TimeUnit.MINUTES).until(() -> { return client .replicationControllers() .inNamespace(this.namespace) .withName(applicationName).isReady(); } ); - **/ } public String project() { @@ -430,7 +429,6 @@ public String project() { * @param filter used to wait to detect that a pod is up and running. */ public void awaitPodReadinessOrFail(Predicate filter) { - /** rls TODO uncomment code and resolve compile issue. https://github.com/arquillian/arquillian-cube/issues/1282 await().atMost(5, TimeUnit.MINUTES).until(() -> { List list = client.pods().inNamespace(namespace).list().getItems(); return list.stream() @@ -439,7 +437,6 @@ public void awaitPodReadinessOrFail(Predicate filter) { .collect(Collectors.toList()).size() >= 1; } ); - **/ } /** diff --git a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/SessionManager.java b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/SessionManager.java index 981e86326..cfea9dc8f 100644 --- a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/SessionManager.java +++ b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/SessionManager.java @@ -9,18 +9,9 @@ import io.fabric8.kubernetes.api.model.Service; import io.fabric8.kubernetes.api.model.ServiceList; import io.fabric8.kubernetes.api.model.ServicePort; -/* rls TODO There are 2 identical classes except for the package names. - Switching to other version for a clean compile. Must confirm - this is a proper change. https://github.com/arquillian/arquillian-cube/issues/1286 - */ -//import io.fabric8.kubernetes.api.model.apps.ReplicaSet; -//import io.fabric8.kubernetes.api.model.apps.ReplicaSetList; - import io.fabric8.kubernetes.api.model.extensions.ReplicaSet; import io.fabric8.kubernetes.api.model.extensions.ReplicaSetList; - import io.fabric8.kubernetes.client.KubernetesClient; -import io.fabric8.kubernetes.client.KubernetesClientTimeoutException; import java.io.IOException; import java.io.InputStream; import java.net.URL; @@ -32,6 +23,8 @@ import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; + +import io.fabric8.kubernetes.client.KubernetesClientTimeoutException; import org.arquillian.cube.kubernetes.api.AnnotationProvider; import org.arquillian.cube.kubernetes.api.Configuration; import org.arquillian.cube.kubernetes.api.DependencyResolver; @@ -42,6 +35,7 @@ import org.arquillian.cube.kubernetes.api.ResourceInstaller; import org.arquillian.cube.kubernetes.api.Session; import org.arquillian.cube.kubernetes.api.SessionCreatedListener; +import org.codehaus.plexus.util.CollectionUtils; import org.fabric8.maven.plugin.build.Fabric8MavenPluginResourceGeneratorBuilder; import org.jboss.arquillian.core.spi.Validate; @@ -123,7 +117,7 @@ public void createEnvironment() { try { URL configUrl = configuration.getEnvironmentConfigUrl(); List dependencyUrls = - !configuration.getEnvironmentDependencies().isEmpty() ? configuration.getEnvironmentDependencies() + (configuration.getEnvironmentDependencies() != null && !configuration.getEnvironmentDependencies().isEmpty()) ? configuration.getEnvironmentDependencies() : dependencyResolver.resolve(session); if (configuration.isEnvironmentInitEnabled()) { diff --git a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/SessionManagerLifecycle.java b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/SessionManagerLifecycle.java index 37cdae9bb..b3c541251 100644 --- a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/SessionManagerLifecycle.java +++ b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/SessionManagerLifecycle.java @@ -17,7 +17,6 @@ import org.jboss.arquillian.core.api.Instance; import org.jboss.arquillian.core.api.annotation.Inject; import org.jboss.arquillian.core.api.annotation.Observes; -import org.jboss.arquillian.test.spi.TestClass; public class SessionManagerLifecycle { diff --git a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/WatchListener.java b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/WatchListener.java index 3bae4bbd2..4c76ce69f 100644 --- a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/WatchListener.java +++ b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/WatchListener.java @@ -1,14 +1,9 @@ package org.arquillian.cube.kubernetes.impl; -// io/fabric8/kubernetes/api/model/Event.class + import io.fabric8.kubernetes.api.model.Container; import io.fabric8.kubernetes.api.model.Event; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.client.KubernetesClient; -import io.fabric8.kubernetes.client.KubernetesClientException; -import io.fabric8.kubernetes.client.Watch; -import io.fabric8.kubernetes.client.Watcher; -import io.fabric8.kubernetes.client.WatcherException; -import io.fabric8.kubernetes.client.dsl.LogWatch; import java.io.Closeable; import java.io.File; import java.io.FileNotFoundException; @@ -20,6 +15,12 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; + +import io.fabric8.kubernetes.client.KubernetesClientException; +import io.fabric8.kubernetes.client.Watch; +import io.fabric8.kubernetes.client.Watcher; +import io.fabric8.kubernetes.client.WatcherException; +import io.fabric8.kubernetes.client.dsl.LogWatch; import org.arquillian.cube.impl.util.Strings; import org.arquillian.cube.kubernetes.api.Configuration; import org.arquillian.cube.kubernetes.api.Logger; @@ -83,10 +84,7 @@ public void eventReceived(Action action, Event event) { public void onClose(WatcherException cause) { } }; - /** rls TODO find replacement for method inNamespace https://github.com/arquillian/arquillian-cube/issues/1281 - watchEvents = client.events().inNamespace(session.getNamespace()).watch(watcher); - **/ - watchEvents = null; // rls TODO remove this line + watchEvents = client.resources(Event.class).inNamespace(session.getNamespace()).watch(watcher); } void cleanupEventsListener() { diff --git a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/AbstractKubernetesResourceProvider.java b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/AbstractKubernetesResourceProvider.java index a8ed80506..4b3464aa2 100644 --- a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/AbstractKubernetesResourceProvider.java +++ b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/AbstractKubernetesResourceProvider.java @@ -3,7 +3,6 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import io.fabric8.kubernetes.client.KubernetesClient; -import io.fabric8.kubernetes.client.utils.Serialization; import java.io.IOException; import java.lang.annotation.Annotation; @@ -12,6 +11,7 @@ import java.util.HashMap; import java.util.Map; +import io.fabric8.kubernetes.client.utils.Serialization; import org.apache.commons.lang3.StringUtils; import org.arquillian.cube.kubernetes.annotations.Named; import org.arquillian.cube.kubernetes.annotations.WithLabel; diff --git a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/KuberntesServiceUrlResourceProvider.java b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/KuberntesServiceUrlResourceProvider.java index 528b46a9d..416e20843 100644 --- a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/KuberntesServiceUrlResourceProvider.java +++ b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/KuberntesServiceUrlResourceProvider.java @@ -7,7 +7,6 @@ import io.fabric8.kubernetes.api.model.Service; import io.fabric8.kubernetes.api.model.ServicePort; import io.fabric8.kubernetes.client.ConfigBuilder; -import io.fabric8.kubernetes.client.KubernetesClient; import java.io.IOException; import java.lang.annotation.Annotation; import java.net.MalformedURLException; @@ -17,6 +16,8 @@ import java.util.Collection; import java.util.List; import java.util.Random; + +import io.fabric8.kubernetes.client.KubernetesClient; import org.arquillian.cube.impl.util.Strings; import org.arquillian.cube.kubernetes.annotations.Port; import org.arquillian.cube.kubernetes.annotations.PortForward; diff --git a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/external/ClientResourceProvider.java b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/external/ClientResourceProvider.java index 1ff8c78fd..5cda17d44 100644 --- a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/external/ClientResourceProvider.java +++ b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/external/ClientResourceProvider.java @@ -12,7 +12,7 @@ import org.jboss.arquillian.test.spi.enricher.resource.ResourceProvider; /** - * A {@link ResourceProvider} for {@link io.fabric8.kubernetes.client.KubernetesClient}. + * A {@link ResourceProvider} for {@link KubernetesClient}. */ public class ClientResourceProvider extends AbstractKubernetesResourceProvider { diff --git a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/internal/DeploymentResourceProvider.java b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/internal/DeploymentResourceProvider.java index ac1f27659..9a2f7751c 100644 --- a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/internal/DeploymentResourceProvider.java +++ b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/internal/DeploymentResourceProvider.java @@ -8,10 +8,6 @@ import java.util.List; import java.util.Map; -/** rls TODO verify pkg change is appropriate https://github.com/arquillian/arquillian-cube/issues/1280 -import io.fabric8.kubernetes.api.model.apps.Deployment; -import io.fabric8.kubernetes.api.model.apps.DeploymentList; -**/ import io.fabric8.kubernetes.api.model.extensions.Deployment; import io.fabric8.kubernetes.api.model.extensions.DeploymentList; diff --git a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/internal/ReplicaSetListResourceProvider.java b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/internal/ReplicaSetListResourceProvider.java index 3fdf5bed7..04e879ba0 100644 --- a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/internal/ReplicaSetListResourceProvider.java +++ b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/internal/ReplicaSetListResourceProvider.java @@ -1,5 +1,6 @@ package org.arquillian.cube.kubernetes.impl.enricher.internal; +import io.fabric8.kubernetes.api.model.apps.ReplicaSetList; import org.arquillian.cube.kubernetes.impl.enricher.AbstractKubernetesResourceProvider; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.arquillian.test.spi.enricher.resource.ResourceProvider; @@ -7,7 +8,6 @@ import java.lang.annotation.Annotation; import java.util.Map; -import io.fabric8.kubernetes.api.model.apps.ReplicaSetList; /** * A {@link ResourceProvider} for {@link ReplicaSetList}. diff --git a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/internal/ReplicaSetResourceProvider.java b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/internal/ReplicaSetResourceProvider.java index e259aa87a..628609d97 100644 --- a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/internal/ReplicaSetResourceProvider.java +++ b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/enricher/internal/ReplicaSetResourceProvider.java @@ -8,17 +8,9 @@ import java.util.List; import java.util.Map; -/* rls TODO There are 2 identical classes except for the package names. - Switching to other version for a clean compile. Must confirm - this is a proper change. https://github.com/arquillian/arquillian-cube/issues/1286 - */ -//import io.fabric8.kubernetes.api.model.apps.ReplicaSet; -//import io.fabric8.kubernetes.api.model.apps.ReplicaSetList; - import io.fabric8.kubernetes.api.model.extensions.ReplicaSet; import io.fabric8.kubernetes.api.model.extensions.ReplicaSetList; - /** * A {@link ResourceProvider} for {@link ReplicaSet}. * It refers to replica sets that have been created during the current session. diff --git a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/feedback/DefaultFeedbackProvider.java b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/feedback/DefaultFeedbackProvider.java index cbe74ebea..6dee972b4 100644 --- a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/feedback/DefaultFeedbackProvider.java +++ b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/feedback/DefaultFeedbackProvider.java @@ -14,11 +14,15 @@ import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.api.model.apps.ReplicaSet; import io.fabric8.kubernetes.client.KubernetesClient; +import java.util.HashMap; +import java.util.Map; + import io.fabric8.kubernetes.client.Watch; import io.fabric8.kubernetes.client.Watcher; +import io.fabric8.kubernetes.client.dsl.EventingAPIGroupDSL; import io.fabric8.kubernetes.client.dsl.FilterWatchListDeletable; -import java.util.HashMap; -import java.util.Map; +import io.fabric8.kubernetes.client.dsl.PodResource; +import io.fabric8.kubernetes.client.dsl.Resource; import org.arquillian.cube.kubernetes.api.FeedbackProvider; import org.arquillian.cube.kubernetes.api.Logger; import org.arquillian.cube.kubernetes.api.WithToImmutable; @@ -119,12 +123,8 @@ protected void displayPodEvents(Pod pod) { fields.put("involvedObject.uid", pod.getMetadata().getUid()); fields.put("involvedObject.name", pod.getMetadata().getName()); fields.put("involvedObject.namespace", pod.getMetadata().getNamespace()); - - EventList eventList = null; // rls TODO remove this stmt - /** rls TODO uncomment this code and resolve return type https://github.com/arquillian/arquillian-cube/issues/1285 - EventList eventList = client.events().inNamespace(pod.getMetadata().getNamespace()).withFields(fields).list(); - **/ - if (eventList == null) { + EventList eventList = client.events().resources(Event.class, EventList.class).inNamespace(pod.getMetadata().getNamespace()).withFields(fields).list(); + if (eventList == null) { return; } logger.warn("Events of matching pod: [" + pod.getMetadata().getName() + "]"); @@ -180,9 +180,7 @@ public PodList podsOf(T resource) { * The {@link Deployment} */ public PodList findMatching(Deployment deployment) { - return new PodList(); // rls TODO remove this line - /** rls TODO uncomment this code and resolve return type https://github.com/arquillian/arquillian-cube/issues/1285 - FilterWatchListDeletable> podLister = + FilterWatchListDeletable podLister = client.pods().inNamespace(deployment.getMetadata().getNamespace()); if (deployment.getSpec().getSelector().getMatchLabels() != null) { podLister.withLabels(deployment.getSpec().getSelector().getMatchLabels()); @@ -206,7 +204,6 @@ public PodList findMatching(Deployment deployment) { } } return podLister.list(); - **/ } /** @@ -216,9 +213,7 @@ public PodList findMatching(Deployment deployment) { * The {@link ReplicaSet} */ public PodList findMatching(ReplicaSet replicaSet) { - return new PodList(); // rls TODO remove this line - /** rls TODO uncomment this code and resolve return type https://github.com/arquillian/arquillian-cube/issues/1285 - FilterWatchListDeletable> podLister = + FilterWatchListDeletable podLister = client.pods().inNamespace(replicaSet.getMetadata().getNamespace()); if (replicaSet.getSpec().getSelector().getMatchLabels() != null) { podLister.withLabels(replicaSet.getSpec().getSelector().getMatchLabels()); @@ -242,7 +237,6 @@ public PodList findMatching(ReplicaSet replicaSet) { } } return podLister.list(); - **/ } @Override diff --git a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/install/DefaultResourceInstaller.java b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/install/DefaultResourceInstaller.java index 12253697c..28b0b0a87 100644 --- a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/install/DefaultResourceInstaller.java +++ b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/install/DefaultResourceInstaller.java @@ -108,7 +108,7 @@ public Map uninstall(List list) { preUninstallCheck(); for (HasMetadata h : list) { try { - Boolean deleted = client.resource(h).delete(); + Boolean deleted = client.resource(h).delete().stream().allMatch(d -> d.getCauses().isEmpty()); result.put(h, deleted); } catch (Throwable t) { result.put(h, false); diff --git a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/namespace/DefaultNamespaceService.java b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/namespace/DefaultNamespaceService.java index cedd08e1c..84a5c6f3c 100644 --- a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/namespace/DefaultNamespaceService.java +++ b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/namespace/DefaultNamespaceService.java @@ -1,11 +1,15 @@ package org.arquillian.cube.kubernetes.impl.namespace; import io.fabric8.kubernetes.api.model.Namespace; +import io.fabric8.kubernetes.api.model.NamespaceBuilder; +import io.fabric8.kubernetes.api.model.StatusDetails; import io.fabric8.kubernetes.client.KubernetesClient; -import io.fabric8.openshift.client.OpenShiftClient; import java.util.Collections; +import java.util.List; import java.util.Map; import java.util.Scanner; + +import io.fabric8.openshift.client.OpenShiftClient; import org.arquillian.cube.kubernetes.api.Configuration; import org.arquillian.cube.kubernetes.api.LabelProvider; import org.arquillian.cube.kubernetes.api.Logger; @@ -115,39 +119,35 @@ public Namespace create(String namespace) { @Override public Namespace create(String namespace, Map annotations) { logger.status("Creating namespace: " + namespace + "..."); - /** rls TODO file replacement for method createNew() https://github.com/arquillian/arquillian-cube/issues/1284 - Namespace result = client.namespaces().createNew().withNewMetadata() - .withName(namespace) - .withAnnotations(annotations) - .addToLabels(labelProvider.getLabels()) - .addToLabels(PROJECT_LABEL, client.getNamespace()) - .addToLabels(FRAMEWORK_LABEL, ARQUILLIAN_FRAMEWORK) - .addToLabels(COMPONENT_LABEL, ITEST_COMPONENT) - .endMetadata() - .done(); + Namespace result = client.namespaces().create( + new NamespaceBuilder().withNewMetadata() + .withName(namespace) + .withAnnotations(annotations) + .addToLabels(labelProvider.getLabels()) + .addToLabels(PROJECT_LABEL, client.getNamespace()) + .addToLabels(FRAMEWORK_LABEL, ARQUILLIAN_FRAMEWORK) + .addToLabels(COMPONENT_LABEL, ITEST_COMPONENT) + .endMetadata() + .build()); logger.info( "To switch to the new namespace: kubectl config set-context `kubectl config current-context` --namespace=" + namespace); - **/ - Namespace result = null; // rls TODO remove this stmt return result; } @Override public Namespace annotate(String namespace, Map annotations) { - /** rls TODO file replacement for method createNew() https://github.com/arquillian/arquillian-cube/issues/1284 - return client.namespaces().withName(namespace).edit() + return client.namespaces().withName(namespace).edit(n -> new NamespaceBuilder(n) .editMetadata() .addToAnnotations(annotations) - .endMetadata().done(); - **/ - return null; // rls TODO remove this stmt + .endMetadata().build()); } @Override public Boolean delete(String namespace) { logger.info("Deleting namespace: " + namespace + "..."); - Boolean deleted = client.namespaces().withName(namespace).delete(); + List details = client.namespaces().withName(namespace).delete(); + Boolean deleted = details.stream().allMatch(d -> d.getCauses().isEmpty()); if (deleted) { logger.info("Namespace: " + namespace + ", successfully deleted"); } diff --git a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/requirement/KubernetesRequirement.java b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/requirement/KubernetesRequirement.java index 2027c7e29..eb7ef8d06 100644 --- a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/requirement/KubernetesRequirement.java +++ b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/requirement/KubernetesRequirement.java @@ -1,14 +1,20 @@ package org.arquillian.cube.kubernetes.impl.requirement; +import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.DefaultKubernetesClient; -import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpRequest; +import io.fabric8.kubernetes.client.http.HttpResponse; +import io.fabric8.kubernetes.client.http.StandardHttpRequest; +import io.fabric8.kubernetes.client.jdkhttp.JdkHttpClientFactory; import io.fabric8.kubernetes.client.utils.URLUtils; +import io.fabric8.kubernetes.client.KubernetesClient; import java.io.IOException; +import java.net.URL; import java.util.Collections; import java.util.List; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; +import java.util.concurrent.ExecutionException; + import org.arquillian.cube.kubernetes.impl.ClientConfigBuilder; import org.arquillian.cube.kubernetes.impl.DefaultConfiguration; import org.arquillian.cube.kubernetes.impl.ExtensionRegistrar; @@ -19,6 +25,7 @@ //TODO: The kubernetes client currently doesn't expose a method to do a version check. An issue has been raised, but until its done we do the work here. See https://github.com/fabric8io/kubernetes-client/issues/477. public class KubernetesRequirement implements Constraint { + HttpClient.Factory httpClientFactory = new JdkHttpClientFactory(); @Override public void check(RequiresKubernetes context) throws UnsatisfiedRequirementException { @@ -27,22 +34,21 @@ public void check(RequiresKubernetes context) throws UnsatisfiedRequirementExcep final DefaultConfiguration config = new ExtensionRegistrar().loadExtension(extension); - try (KubernetesClient client = new DefaultKubernetesClient( - new ClientConfigBuilder().configuration(config).build())) { - - OkHttpClient httpClient = client.adapt(OkHttpClient.class); + final Config httpClientConfig = new ClientConfigBuilder().configuration(config).build(); + try (KubernetesClient client = new DefaultKubernetesClient(httpClientConfig)) { - Request versionRequest = new Request.Builder() - .get() - .url(URLUtils.join(client.getMasterUrl().toString(), "version")) + HttpClient httpClient = httpClientFactory.newBuilder(httpClientConfig).build(); + HttpRequest versionRequest = new StandardHttpRequest.Builder() + .url(new URL(URLUtils.join(client.getMasterUrl().toString(), "version").toString())) + .method("GET", "*/*", null) .build(); - Response response = httpClient.newCall(versionRequest).execute(); + HttpResponse response = httpClient.sendAsync(versionRequest, String.class).get(); if (!response.isSuccessful()) { throw new UnsatisfiedRequirementException( "Failed to verify kubernetes version, due to: [" + response.message() + "]"); } - } catch (IOException | IllegalArgumentException e) { + } catch (IOException | IllegalArgumentException | InterruptedException | ExecutionException e) { throw new UnsatisfiedRequirementException( "Error while checking kubernetes version: [" + e.getMessage() + "]"); } diff --git a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/visitor/NamespaceVisitor.java b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/visitor/NamespaceVisitor.java index 1bd63048c..ee1bdaa01 100644 --- a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/visitor/NamespaceVisitor.java +++ b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/visitor/NamespaceVisitor.java @@ -1,17 +1,11 @@ package org.arquillian.cube.kubernetes.impl.visitor; import io.fabric8.kubernetes.api.builder.TypedVisitor; -import io.fabric8.kubernetes.api.builder.VisitableBuilder; -import io.fabric8.kubernetes.api.builder.Visitor; -import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import org.arquillian.cube.kubernetes.api.Configuration; import org.jboss.arquillian.core.api.Instance; import org.jboss.arquillian.core.api.annotation.Inject; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - public class NamespaceVisitor extends TypedVisitor { @Inject diff --git a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/visitor/ServiceAccountVisitor.java b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/visitor/ServiceAccountVisitor.java index 3551dc96d..a38bc620e 100644 --- a/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/visitor/ServiceAccountVisitor.java +++ b/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/visitor/ServiceAccountVisitor.java @@ -2,6 +2,8 @@ import io.fabric8.kubernetes.api.builder.Visitor; import io.fabric8.kubernetes.api.model.PodSpecBuilder; +import io.fabric8.kubernetes.api.model.ServiceAccount; +import io.fabric8.kubernetes.api.model.ServiceAccountBuilder; import io.fabric8.kubernetes.client.KubernetesClient; import org.arquillian.cube.impl.util.Strings; import org.arquillian.cube.kubernetes.api.Configuration; @@ -42,12 +44,9 @@ private boolean serviceAccountExists(String serviceAccount) { private void createServiceAccount(String serviceAccount) { KubernetesClient client = this.client.get(); Configuration configuration = this.configuration.get(); - /** rls TODO find replacement for method createNew - client.serviceAccounts().inNamespace(configuration.getNamespace()).createNew() + client.serviceAccounts().inNamespace(configuration.getNamespace()).create(new ServiceAccountBuilder() .withNewMetadata() .withName(serviceAccount) - .endMetadata() - .done(); - **/ + .endMetadata().build()); } } diff --git a/kubernetes/kubernetes/src/test/java/org/arquillian/cube/kubernetes/impl/MockTest.java b/kubernetes/kubernetes/src/test/java/org/arquillian/cube/kubernetes/impl/MockTest.java index b30ac8034..d0b898604 100644 --- a/kubernetes/kubernetes/src/test/java/org/arquillian/cube/kubernetes/impl/MockTest.java +++ b/kubernetes/kubernetes/src/test/java/org/arquillian/cube/kubernetes/impl/MockTest.java @@ -3,7 +3,9 @@ import io.fabric8.kubernetes.api.model.Endpoints; import io.fabric8.kubernetes.api.model.EndpointsBuilder; import io.fabric8.kubernetes.api.model.EndpointsListBuilder; +import io.fabric8.kubernetes.api.model.EventBuilder; import io.fabric8.kubernetes.api.model.NamespaceBuilder; +import io.fabric8.kubernetes.api.model.ObjectReferenceBuilder; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.PodBuilder; import io.fabric8.kubernetes.api.model.PodListBuilder; @@ -18,7 +20,6 @@ import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.server.mock.KubernetesMockServer; -import java.io.IOException; import org.arquillian.cube.kubernetes.api.Configuration; import org.arquillian.cube.kubernetes.impl.requirement.RequiresKubernetes; import org.junit.AfterClass; @@ -40,7 +41,7 @@ public class MockTest { private static final KubernetesMockServer MOCK = new KubernetesMockServer(); @BeforeClass - public static void setUpClass() throws IOException { + public static void setUpClass() { Pod testPod = new PodBuilder() .withNewMetadata() @@ -173,6 +174,20 @@ public static void setUpClass() throws IOException { .and().build()).always(); //test-controller + MOCK.expect() + .get() + .withPath("/api/v1/namespaces/arquillian/replicationcontrollers?fieldSelector=metadata.name%3Dtest-controller") + .andReturn(200, testController) + .once(); + MOCK.expect() + .get() + .withPath("/api/v1/namespaces/arquillian/replicationcontrollers?allowWatchBookmarks=true&fieldSelector=metadata.name%3Dtest-controller&timeoutSeconds=600&watch=true") + .andUpgradeToWebSocket() + .open() + .waitFor(50) + .andEmit(new WatchEvent(testController, "ADDED")) + .done() + .once(); MOCK.expect() .post() .withPath("/api/v1/namespaces/arquillian/replicationcontrollers") @@ -221,8 +236,39 @@ public static void setUpClass() throws IOException { .always(); //test-pod - MOCK.expect().post().withPath("/api/v1/namespaces/arquillian/pods").andReturn(201, testPod).always(); - MOCK.expect().get().withPath("/api/v1/namespaces/arquillian/pods/test-pod").andReturn(404, "").once(); + MOCK.expect() + .get() + .withPath("/api/v1/namespaces/arquillian/pods?fieldSelector=metadata.name%3Dtest-pod") + .andReturn(200, testPod) + .once(); + MOCK.expect() + .get() + .withPath("/api/v1/namespaces/arquillian/pods?allowWatchBookmarks=true&fieldSelector=metadata.name%3Dtest-pod&timeoutSeconds=600&watch=true") + .andUpgradeToWebSocket() + .open() + .waitFor(50) + .andEmit(new WatchEvent(testPod, "ADDED")) + .done() + .once(); + MOCK.expect() + .get() + .withPath("/api/v1/namespaces/arquillian/events?allowWatchBookmarks=true&watch=true") + .andUpgradeToWebSocket() + .open() + .waitFor(50) + .andEmit(new WatchEvent(new EventBuilder() + .withInvolvedObject(new ObjectReferenceBuilder() + .withName(testPod.getMetadata().getName()) + .withKind(testPod.getKind()) + .build()) + .withNewMetadata() + .withName("boh") + .withNamespace("arquillian") + .endMetadata() + .build(), "ADDED")) + .done() + .once(); + MOCK.expect().post().withPath("/api/v1/namespaces/arquillian/pods").andReturn(201, testPod).once(); MOCK.expect().get().withPath("/api/v1/namespaces/arquillian/pods/test-pod").andReturn(200, testPod).always(); MOCK.expect().get().withPath("/api/v1/namespaces/arquillian/pods").andReturn(200, new PodListBuilder() .withNewMetadata() @@ -243,8 +289,21 @@ public static void setUpClass() throws IOException { //test-service + MOCK.expect() + .get() + .withPath("/api/v1/namespaces/arquillian/services?fieldSelector=metadata.name%3Dtest-service") + .andReturn(200, testService) + .once(); + MOCK.expect() + .get() + .withPath("/api/v1/namespaces/arquillian/services?allowWatchBookmarks=true&fieldSelector=metadata.name%3Dtest-service&timeoutSeconds=600&watch=true") + .andUpgradeToWebSocket() + .open() + .waitFor(50) + .andEmit(new WatchEvent(testService, "ADDED")) + .done() + .once(); MOCK.expect().post().withPath("/api/v1/namespaces/arquillian/services").andReturn(201, testService).always(); - MOCK.expect().get().withPath("/api/v1/namespaces/arquillian/services/test-service").andReturn(404, "").once(); MOCK.expect() .get() .withPath("/api/v1/namespaces/arquillian/services/test-service") @@ -276,6 +335,20 @@ public static void setUpClass() throws IOException { .build()).always(); //test-service endpoints + MOCK.expect() + .get() + .withPath("/api/v1/namespaces/arquillian/endpoints?fieldSelector=metadata.name%3Dtest-service") + .andReturn(200, testEndpoints) + .once(); + MOCK.expect() + .get() + .withPath("/api/v1/namespaces/arquillian/endpoints?allowWatchBookmarks=true&fieldSelector=metadata.name%3Dtest-service&timeoutSeconds=600&watch=true") + .andUpgradeToWebSocket() + .open() + .waitFor(50) + .andEmit(new WatchEvent(readyTestEndpoints, "ADDED")) + .done() + .always(); MOCK.expect().post().withPath("/api/v1/namespaces/arquillian/endpoints").andReturn(201, testEndpoints).always(); MOCK.expect() @@ -317,7 +390,7 @@ public static void setUpClass() throws IOException { .andReturn(200, new ReplicaSetBuilder().build()) .always(); - MOCK.init(); + MOCK.start(); String masterUrl = MOCK.url("/").toString(); System.setProperty(Config.KUBERNETES_MASTER_SYSTEM_PROPERTY, masterUrl); @@ -330,7 +403,7 @@ public static void setUpClass() throws IOException { } @AfterClass - public static void tearDownClass() throws IOException { - //MOCK.destroy(); + public static void tearDownClass() { + //MOCK.shutdown(); } } diff --git a/kubernetes/reporter/pom.xml b/kubernetes/reporter/pom.xml index 4a338bd75..bc7d7a928 100644 --- a/kubernetes/reporter/pom.xml +++ b/kubernetes/reporter/pom.xml @@ -52,7 +52,7 @@ io.fabric8 - mockwebserver + kubernetes-server-mock test @@ -60,5 +60,12 @@ junit test + + + + io.sundr + builder-annotations + 0.103.1 + diff --git a/kubernetes/reporter/src/test/java/org/arquillian/cube/kubernetes/reporter/TakeKubernetesResourcesInformationTest.java b/kubernetes/reporter/src/test/java/org/arquillian/cube/kubernetes/reporter/TakeKubernetesResourcesInformationTest.java index 4ea576112..6ced5c4a7 100644 --- a/kubernetes/reporter/src/test/java/org/arquillian/cube/kubernetes/reporter/TakeKubernetesResourcesInformationTest.java +++ b/kubernetes/reporter/src/test/java/org/arquillian/cube/kubernetes/reporter/TakeKubernetesResourcesInformationTest.java @@ -10,6 +10,7 @@ import io.fabric8.kubernetes.api.model.Service; import io.fabric8.kubernetes.api.model.ServiceBuilder; import io.fabric8.kubernetes.api.model.ServiceListBuilder; +import io.fabric8.kubernetes.client.server.mock.EnableKubernetesMockClient; import io.fabric8.kubernetes.client.server.mock.KubernetesMockServer; import java.io.IOException; import java.net.URL; @@ -56,6 +57,7 @@ import static org.mockito.Mockito.verify; @RunWith(MockitoJUnitRunner.class) +@EnableKubernetesMockClient public class TakeKubernetesResourcesInformationTest { private static final KubernetesMockServer server = new KubernetesMockServer(); diff --git a/openshift/ftest-istio-openshift/pom.xml b/openshift/ftest-istio-openshift/pom.xml index 99dec4b7e..625ef7e18 100644 --- a/openshift/ftest-istio-openshift/pom.xml +++ b/openshift/ftest-istio-openshift/pom.xml @@ -46,6 +46,18 @@ openshift-client test + + io.rest-assured + rest-assured + test + + + org.arquillian.cube + arquillian-cube-istio-kubernetes-api + 2.0.0-SNAPSHOT + test + + diff --git a/openshift/ftest-istio-openshift/src/test/java/org/arquillian/cube/openshift/standalone/AbstractReviewsTest.java b/openshift/ftest-istio-openshift/src/test/java/org/arquillian/cube/openshift/standalone/AbstractReviewsTest.java index 4dd51521e..eed4e5d93 100644 --- a/openshift/ftest-istio-openshift/src/test/java/org/arquillian/cube/openshift/standalone/AbstractReviewsTest.java +++ b/openshift/ftest-istio-openshift/src/test/java/org/arquillian/cube/openshift/standalone/AbstractReviewsTest.java @@ -1,24 +1,29 @@ package org.arquillian.cube.openshift.standalone; -import static io.restassured.RestAssured.given; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.Matchers.hasKey; - +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpRequest; +import io.fabric8.kubernetes.client.http.HttpResponse; +import io.fabric8.kubernetes.client.jdkhttp.JdkHttpClientFactory; import io.restassured.builder.RequestSpecBuilder; import io.restassured.path.json.JsonPath; import io.restassured.specification.RequestSpecification; +import org.arquillian.cube.istio.impl.IstioAssistant; + import java.io.IOException; +import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import org.arquillian.cube.istio.impl.IstioAssistant; +import java.util.concurrent.ExecutionException; + +import static io.restassured.RestAssured.given; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.Matchers.hasKey; public abstract class AbstractReviewsTest { + private HttpClient.Builder httpClientBuilder = new JdkHttpClientFactory().newBuilder(); protected void should_get_v1_if_not_logged(URL url) { // given @@ -38,24 +43,26 @@ protected void should_get_v1_if_not_logged(URL url) { } protected void alex_should_use_reviews_v2_version(URL url, - IstioAssistant istioAssistant) throws IOException { + IstioAssistant istioAssistant) throws IOException, ExecutionException, InterruptedException { // given waitUntilRouteIsPopulated(url, istioAssistant); // when - // Using okhttp because I have not find any way of making rest assured working when setting the required cookies - final Request request = new Request.Builder() - .url(url.toString() + "api/v1/products/0/reviews") - .addHeader("Cookie", "user=alex; Domain=" + url.getHost() +"; Path=/") + // This was previously using okhttp because we didn't find any way of making rest assured working when setting + // the required cookies. Now we switch to JdkHttpClient, to see whether we can avoid depending on + // okhttp artifacts at all + final HttpClient httpClient = httpClientBuilder.build(); + final HttpRequest request = httpClient.newHttpRequestBuilder() + .url(new URL(url.toString() + "api/v1/products/0/reviews")) + .header("Cookie", "user=alex; Domain=" + url.getHost() +"; Path=/") .build(); - final OkHttpClient okHttpClient = new OkHttpClient(); - try(Response response = okHttpClient.newCall(request).execute()) { + HttpResponse response = httpClient.sendAsync(request, String.class).get(); // then - final String content = response.body().string(); + final String content = response.body(); final List> ratings = JsonPath.from(content).getList("reviews.rating"); @@ -70,21 +77,18 @@ protected void alex_should_use_reviews_v2_version(URL url, assertThat(ratings) .containsExactlyInAnyOrder(expectationStar4, expectationStar5); - } + } - protected void waitUntilRouteIsPopulated(URL url, IstioAssistant istioAssistant) { - final Request request = new Request.Builder() - .url(url.toString() + "api/v1/products/0/reviews") - .addHeader("Cookie", "user=alex; Domain=" + url.getHost() +"; Path=/") + protected void waitUntilRouteIsPopulated(URL url, IstioAssistant istioAssistant) throws MalformedURLException { + final HttpClient httpClient = httpClientBuilder.build(); + final HttpRequest request = httpClient.newHttpRequestBuilder() + .url(new URL(url.toString() + "api/v1/products/0/reviews")) + .header("Cookie", "user=alex; Domain=" + url.getHost() +"; Path=/") .build(); istioAssistant.await(request, response -> { - try { - return response.body().string().contains("stars"); - } catch (IOException e) { - return false; - } + return response.body().contains("stars"); }); } } diff --git a/openshift/ftest-istio-openshift/src/test/java/org/arquillian/cube/openshift/standalone/ReviewsIT.java b/openshift/ftest-istio-openshift/src/test/java/org/arquillian/cube/openshift/standalone/ReviewsIT.java index e302277a0..9eb53b97c 100644 --- a/openshift/ftest-istio-openshift/src/test/java/org/arquillian/cube/openshift/standalone/ReviewsIT.java +++ b/openshift/ftest-istio-openshift/src/test/java/org/arquillian/cube/openshift/standalone/ReviewsIT.java @@ -2,6 +2,8 @@ import java.io.IOException; import java.net.URL; +import java.util.concurrent.ExecutionException; + import org.arquillian.cube.istio.api.IstioResource; import org.arquillian.cube.istio.impl.IstioAssistant; import org.arquillian.cube.openshift.impl.enricher.AwaitRoute; @@ -36,7 +38,7 @@ public void should_get_v1_if_not_logged() { } @Test - public void alex_should_use_reviews_v2_version() throws IOException { + public void alex_should_use_reviews_v2_version() throws IOException, ExecutionException, InterruptedException { alex_should_use_reviews_v2_version(url, istioAssistant); } diff --git a/openshift/ftest-istio-openshift/src/test/java/org/arquillian/cube/openshift/standalone/ReviewsITLegacy.java b/openshift/ftest-istio-openshift/src/test/java/org/arquillian/cube/openshift/standalone/ReviewsITLegacy.java index 1354a4bfd..532c973b2 100644 --- a/openshift/ftest-istio-openshift/src/test/java/org/arquillian/cube/openshift/standalone/ReviewsITLegacy.java +++ b/openshift/ftest-istio-openshift/src/test/java/org/arquillian/cube/openshift/standalone/ReviewsITLegacy.java @@ -1,23 +1,26 @@ package org.arquillian.cube.openshift.standalone; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpRequest; +import io.fabric8.kubernetes.client.http.HttpResponse; +import io.fabric8.kubernetes.client.jdkhttp.JdkHttpClientFactory; import io.restassured.builder.RequestSpecBuilder; import io.restassured.path.json.JsonPath; import io.restassured.specification.RequestSpecification; import java.io.IOException; +import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; +import java.util.concurrent.ExecutionException; + import org.arquillian.cube.istio.api.IstioResource; import org.arquillian.cube.istio.impl.IstioAssistant; import org.arquillian.cube.openshift.impl.enricher.AwaitRoute; import org.arquillian.cube.openshift.impl.enricher.RouteURL; import org.arquillian.cube.openshift.impl.requirement.RequiresOpenshift; import org.arquillian.cube.requirement.ArquillianConditionalRunner; -import org.assertj.core.api.Assertions; import org.jboss.arquillian.test.api.ArquillianResource; import org.junit.Ignore; import org.junit.Test; @@ -36,6 +39,7 @@ @Ignore("This test assumes that you have a cluster installed with Istio and BookInfo application deployed. We could make a full test preparing all this, but it will take lot of time, not error safe and test execution would take like 10 minutes") public class ReviewsITLegacy { + private HttpClient.Builder httpClientBuilder = new JdkHttpClientFactory().newBuilder(); @RouteURL("productpage") @AwaitRoute private URL url; @@ -66,62 +70,56 @@ public void should_get_v1_if_not_logged() { } @Test - public void alex_should_use_reviews_v2_version() throws IOException { + public void alex_should_use_reviews_v2_version() throws IOException, ExecutionException, InterruptedException { // given waitUntilRouteIsPopulated(); // when - // Using okhttp because I have not find any way of making rest assured working when setting the required cookies - final Request request = new Request.Builder() - .url(url.toString() + "api/v1/products/0/reviews") - .addHeader("Cookie", "user=alex; Domain=" + url.getHost() +"; Path=/") + final HttpClient httpClient = httpClientBuilder.build(); + final HttpRequest request = httpClient.newHttpRequestBuilder() + .url(new URL(url.toString() + "api/v1/products/0/reviews")) + .header("Cookie", "user=alex; Domain=" + url.getHost() +"; Path=/") .build(); - final OkHttpClient okHttpClient = new OkHttpClient(); - try(Response response = okHttpClient.newCall(request).execute()) { - - // then - - final String content = response.body().string(); + HttpResponse response = httpClient.sendAsync(request, String.class).get(); - final List> ratings = JsonPath.from(content).getList("reviews.rating"); + // then - final Map expectationStar5 = new HashMap<>(); - expectationStar5.put("color", "black"); - expectationStar5.put("stars", 5); + final String content = response.body(); - final Map expectationStar4 = new HashMap<>(); - expectationStar4.put("color", "black"); - expectationStar4.put("stars", 4); + final List> ratings = JsonPath.from(content).getList("reviews.rating"); - assertThat(ratings) - .containsExactlyInAnyOrder(expectationStar4, expectationStar5); + final Map expectationStar5 = new HashMap<>(); + expectationStar5.put("color", "black"); + expectationStar5.put("stars", 5); - } + final Map expectationStar4 = new HashMap<>(); + expectationStar4.put("color", "black"); + expectationStar4.put("stars", 4); + assertThat(ratings) + .containsExactlyInAnyOrder(expectationStar4, expectationStar5); } - private void waitUntilRouteIsPopulated() { - final Request request = new Request.Builder() - .url(url.toString() + "api/v1/products/0/reviews") - .addHeader("Cookie", "user=alex; Domain=" + url.getHost() +"; Path=/") + private void waitUntilRouteIsPopulated() throws MalformedURLException { + final HttpClient httpClient = httpClientBuilder.build(); + final HttpRequest request = httpClient.newHttpRequestBuilder() + .url(new URL(url.toString() + "api/v1/products/0/reviews")) + .header("Cookie", "user=alex; Domain=" + url.getHost() +"; Path=/") .build(); istioAssistant.await(request, response -> { - try { - return response.body().string().contains("stars"); - } catch (IOException e) { - return false; - } + return response.body().contains("stars"); }); } - private void waitUntilRouteIsPopulated2() { - final Request request = new Request.Builder() - .url(url.toString() + "api/v1/products/0/reviews") - .addHeader("Cookie", "user=alex; Domain=" + url.getHost() +"; Path=/") + private void waitUntilRouteIsPopulated2() throws MalformedURLException { + final HttpClient httpClient = httpClientBuilder.build(); + final HttpRequest request = httpClient.newHttpRequestBuilder() + .url(new URL(url.toString() + "api/v1/products/0/reviews")) + .header("Cookie", "user=alex; Domain=" + url.getHost() +"; Path=/") .build(); istioAssistant.await(request, response -> "2.0.0".equals(response.header("version"))); diff --git a/openshift/ftest-openshift-assistant-operational-methods/pom.xml b/openshift/ftest-openshift-assistant-operational-methods/pom.xml index 6013a89d2..fa8657a6c 100644 --- a/openshift/ftest-openshift-assistant-operational-methods/pom.xml +++ b/openshift/ftest-openshift-assistant-operational-methods/pom.xml @@ -30,6 +30,21 @@ assertj-core test + + io.fabric8 + kubernetes-openshift-uberjar + test + + + io.fabric8 + kubernetes-client-api + test + + + io.rest-assured + rest-assured + test + diff --git a/openshift/ftest-openshift-assistant-operational-methods/src/test/java/org/arquillian/cube/openshift/operational/methods/OpenShiftAssistantOperationalMethodsIT.java b/openshift/ftest-openshift-assistant-operational-methods/src/test/java/org/arquillian/cube/openshift/operational/methods/OpenShiftAssistantOperationalMethodsIT.java index 0f25fc218..e69ca4d11 100644 --- a/openshift/ftest-openshift-assistant-operational-methods/src/test/java/org/arquillian/cube/openshift/operational/methods/OpenShiftAssistantOperationalMethodsIT.java +++ b/openshift/ftest-openshift-assistant-operational-methods/src/test/java/org/arquillian/cube/openshift/operational/methods/OpenShiftAssistantOperationalMethodsIT.java @@ -2,11 +2,9 @@ import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.kubernetes.api.model.Pod; -import io.fabric8.kubernetes.client.internal.readiness.Readiness; import io.fabric8.openshift.api.model.Project; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; +import io.fabric8.kubernetes.client.readiness.Readiness; +import io.restassured.RestAssured; import org.arquillian.cube.openshift.impl.client.OpenShiftAssistant; import org.arquillian.cube.openshift.impl.requirement.RequiresOpenshift; import org.arquillian.cube.requirement.ArquillianConditionalRunner; @@ -21,6 +19,7 @@ import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.is; @Category(RequiresOpenshift.class) @RequiresOpenshift @@ -45,13 +44,13 @@ public void should_apply_template_programmatically() throws IOException { final Optional route = openShiftAssistant.getRoute(); openShiftAssistant.awaitUrl(route.get()); - OkHttpClient okHttpClient = new OkHttpClient(); - Request request = new Request.Builder().get().url(route.get()).build(); - Response response = okHttpClient.newCall(request).execute(); - - assertThat(response).isNotNull(); - assertThat(response.code()).isEqualTo(200); - assertThat(response.body().string()).isEqualTo("Hello from Arquillian Template\n"); + RestAssured.given() + .when() + .get(route.get()) + .then() + .assertThat() + .statusCode(200) + .body(is("Hello from Arquillian Template\n")); } @Test diff --git a/openshift/ftest-openshift-assistant/pom.xml b/openshift/ftest-openshift-assistant/pom.xml index dd45d240e..3a4eed8ef 100644 --- a/openshift/ftest-openshift-assistant/pom.xml +++ b/openshift/ftest-openshift-assistant/pom.xml @@ -36,6 +36,11 @@ junit test + + io.rest-assured + rest-assured + test + diff --git a/openshift/ftest-openshift-assistant/src/test/java/org/arquillian/cube/openshift/standalone/HelloWorldOpenShiftAssistantIT.java b/openshift/ftest-openshift-assistant/src/test/java/org/arquillian/cube/openshift/standalone/HelloWorldOpenShiftAssistantIT.java index 47e4f5218..1c7374a45 100644 --- a/openshift/ftest-openshift-assistant/src/test/java/org/arquillian/cube/openshift/standalone/HelloWorldOpenShiftAssistantIT.java +++ b/openshift/ftest-openshift-assistant/src/test/java/org/arquillian/cube/openshift/standalone/HelloWorldOpenShiftAssistantIT.java @@ -4,9 +4,9 @@ import java.net.URL; import java.util.List; import java.util.Optional; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; + +import io.fabric8.kubernetes.client.readiness.Readiness; +import io.restassured.RestAssured; import org.arquillian.cube.openshift.impl.client.OpenShiftAssistant; import org.arquillian.cube.openshift.impl.requirement.RequiresOpenshift; import org.arquillian.cube.requirement.ArquillianConditionalRunner; @@ -16,9 +16,9 @@ import org.junit.runner.RunWith; import io.fabric8.kubernetes.api.model.Pod; -import io.fabric8.kubernetes.client.internal.readiness.Readiness; import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.is; @Category(RequiresOpenshift.class) @RequiresOpenshift @@ -57,15 +57,12 @@ public void should_apply_route_programmatically() throws IOException { final Optional route = openShiftAssistant.getRoute(); openShiftAssistant.awaitUrl(route.get()); - - OkHttpClient okHttpClient = new OkHttpClient(); - Request request = new Request.Builder().get().url(route.get()).build(); - Response response = okHttpClient.newCall(request).execute(); - - assertThat(response).isNotNull(); - assertThat(response.code()).isEqualTo(200); - assertThat(response.body().string()).isEqualTo("Hello OpenShift!\n"); + RestAssured.given() + .when() + .get(route.get()) + .then() + .assertThat() + .statusCode(200) + .body(is("Hello OpenShift!\n")); } - - } diff --git a/openshift/ftest-openshift-resources-standalone/pom.xml b/openshift/ftest-openshift-resources-standalone/pom.xml index 21bf75ca6..d4cdb9f4b 100644 --- a/openshift/ftest-openshift-resources-standalone/pom.xml +++ b/openshift/ftest-openshift-resources-standalone/pom.xml @@ -46,6 +46,11 @@ kubernetes-client test + + io.rest-assured + rest-assured + test + diff --git a/openshift/ftest-openshift-resources-standalone/src/test/java/org/arquillian/cube/openshift/standalone/HelloWorldOpenShiftResourcesIT.java b/openshift/ftest-openshift-resources-standalone/src/test/java/org/arquillian/cube/openshift/standalone/HelloWorldOpenShiftResourcesIT.java index 1dd1bce24..4aa3f0627 100644 --- a/openshift/ftest-openshift-resources-standalone/src/test/java/org/arquillian/cube/openshift/standalone/HelloWorldOpenShiftResourcesIT.java +++ b/openshift/ftest-openshift-resources-standalone/src/test/java/org/arquillian/cube/openshift/standalone/HelloWorldOpenShiftResourcesIT.java @@ -6,9 +6,8 @@ import io.fabric8.openshift.client.OpenShiftClient; import java.io.IOException; import java.net.URL; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; + +import io.restassured.RestAssured; import org.arquillian.cube.openshift.api.OpenShiftResource; import org.arquillian.cube.openshift.impl.enricher.AwaitRoute; import org.arquillian.cube.openshift.impl.enricher.RouteURL; @@ -20,6 +19,7 @@ import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.is; @Category(RequiresOpenshift.class) @RequiresOpenshift @@ -39,13 +39,14 @@ public class HelloWorldOpenShiftResourcesIT { @Test public void should_show_hello_world() throws IOException { assertThat(url).isNotNull(); - OkHttpClient okHttpClient = new OkHttpClient(); - Request request = new Request.Builder().get().url(url).build(); - Response response = okHttpClient.newCall(request).execute(); - assertThat(response).isNotNull(); - assertThat(response.code()).isEqualTo(200); - assertThat(response.body().string()).isEqualTo("Hello OpenShift!\n"); + RestAssured.given() + .when() + .get(url) + .then() + .assertThat() + .statusCode(200) + .body(is("Hello OpenShift!\n")); } @Test diff --git a/openshift/ftest-standalone/pom.xml b/openshift/ftest-standalone/pom.xml index 67c51b799..5f7351bb0 100644 --- a/openshift/ftest-standalone/pom.xml +++ b/openshift/ftest-standalone/pom.xml @@ -36,6 +36,11 @@ openshift-client ${version.kubernetes_client} + + io.rest-assured + rest-assured + test + diff --git a/openshift/ftest-standalone/src/test/java/org/arquillian/cube/openshift/standalone/HelloWorldIT.java b/openshift/ftest-standalone/src/test/java/org/arquillian/cube/openshift/standalone/HelloWorldIT.java index 08f334dea..442483af5 100644 --- a/openshift/ftest-standalone/src/test/java/org/arquillian/cube/openshift/standalone/HelloWorldIT.java +++ b/openshift/ftest-standalone/src/test/java/org/arquillian/cube/openshift/standalone/HelloWorldIT.java @@ -4,9 +4,8 @@ import io.fabric8.openshift.client.OpenShiftClient; import java.io.IOException; import java.net.URL; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; + +import io.restassured.RestAssured; import org.arquillian.cube.kubernetes.annotations.Named; import org.arquillian.cube.kubernetes.annotations.PortForward; import org.arquillian.cube.openshift.impl.requirement.RequiresOpenshift; @@ -17,6 +16,7 @@ import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.is; @Category(RequiresOpenshift.class) @RequiresOpenshift @@ -52,12 +52,12 @@ public void service_instance_should_not_be_null() throws IOException { @Test public void should_show_hello_world() throws IOException { assertThat(url).isNotNull(); - OkHttpClient okHttpClient = new OkHttpClient(); - Request request = new Request.Builder().get().url(url).build(); - Response response = okHttpClient.newCall(request).execute(); - - assertThat(response).isNotNull(); - assertThat(response.code()).isEqualTo(200); - assertThat(response.body().string()).isEqualTo("Hello OpenShift!\n"); + RestAssured.given() + .when() + .get(url) + .then() + .assertThat() + .statusCode(200) + .body(is("Hello OpenShift!\n")); } } diff --git a/openshift/ftest-template-standalone/pom.xml b/openshift/ftest-template-standalone/pom.xml index 2b0c3345c..af92386ef 100644 --- a/openshift/ftest-template-standalone/pom.xml +++ b/openshift/ftest-template-standalone/pom.xml @@ -41,6 +41,11 @@ kubernetes-client test + + io.rest-assured + rest-assured + test + diff --git a/openshift/ftest-template-standalone/src/test/java/org/arquillian/cube/openshift/standalone/HelloWorldTemplateIT.java b/openshift/ftest-template-standalone/src/test/java/org/arquillian/cube/openshift/standalone/HelloWorldTemplateIT.java index e11981858..f11584d04 100644 --- a/openshift/ftest-template-standalone/src/test/java/org/arquillian/cube/openshift/standalone/HelloWorldTemplateIT.java +++ b/openshift/ftest-template-standalone/src/test/java/org/arquillian/cube/openshift/standalone/HelloWorldTemplateIT.java @@ -2,9 +2,8 @@ import java.io.IOException; import java.net.URL; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; + +import io.restassured.RestAssured; import org.arquillian.cube.openshift.api.Template; import org.arquillian.cube.openshift.api.TemplateParameter; import org.arquillian.cube.openshift.impl.enricher.AwaitRoute; @@ -16,6 +15,7 @@ import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.is; // tag::openshift_template_example[] @Category(RequiresOpenshift.class) @@ -45,13 +45,14 @@ public void should_create_method_template_resources( private void verifyResponse(URL url) throws IOException { assertThat(url).isNotNull(); - OkHttpClient okHttpClient = new OkHttpClient(); - Request request = new Request.Builder().get().url(url).build(); - Response response = okHttpClient.newCall(request).execute(); - assertThat(response).isNotNull(); - assertThat(response.code()).isEqualTo(200); - assertThat(response.body().string()).isEqualTo("Hello from Arquillian Template\n"); + RestAssured.given() + .when() + .get(url) + .then() + .assertThat() + .statusCode(200) + .body(is("Hello from Arquillian Template\n")); } } // end::openshift_template_example[] diff --git a/openshift/ftest-template-standalone/src/test/java/org/arquillian/cube/openshift/standalone/HelloWorldTemplatesIT.java b/openshift/ftest-template-standalone/src/test/java/org/arquillian/cube/openshift/standalone/HelloWorldTemplatesIT.java index 602a742d8..86a5243a8 100644 --- a/openshift/ftest-template-standalone/src/test/java/org/arquillian/cube/openshift/standalone/HelloWorldTemplatesIT.java +++ b/openshift/ftest-template-standalone/src/test/java/org/arquillian/cube/openshift/standalone/HelloWorldTemplatesIT.java @@ -2,9 +2,8 @@ import java.io.IOException; import java.net.URL; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; + +import io.restassured.RestAssured; import org.arquillian.cube.openshift.api.Template; import org.arquillian.cube.openshift.api.TemplateParameter; import org.arquillian.cube.openshift.api.Templates; @@ -17,6 +16,7 @@ import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.is; @Category(RequiresOpenshift.class) @@ -35,13 +35,13 @@ public class HelloWorldTemplatesIT { @Test public void should_create_resources_from_templates() throws IOException { assertThat(helloOpenshiftTemplates).isNotNull(); - OkHttpClient okHttpClient = new OkHttpClient(); - Request request = new Request.Builder().get().url(helloOpenshiftTemplates).build(); - Response response = okHttpClient.newCall(request).execute(); - - assertThat(response).isNotNull(); - assertThat(response.code()).isEqualTo(200); - assertThat(response.body().string()).isEqualTo("Hello from Arquillian Templates\n"); + RestAssured.given() + .when() + .get(helloOpenshiftTemplates) + .then() + .assertThat() + .statusCode(200) + .body(is("Hello from Arquillian Templates\n")); } } diff --git a/openshift/openshift/pom.xml b/openshift/openshift/pom.xml index 3757414bf..a7878a371 100644 --- a/openshift/openshift/pom.xml +++ b/openshift/openshift/pom.xml @@ -45,6 +45,10 @@ org.arquillian.cube arquillian-cube-kubernetes + + org.arquillian.cube + arquillian-cube-openshift-api + org.jboss.arquillian.core arquillian-core-spi @@ -95,9 +99,24 @@ - org.arquillian.cube - arquillian-cube-openshift-api - ${project.version} + io.fabric8 + kubernetes-client + compile + + + + io.fabric8 + kubernetes-httpclient-jdk + + + + io.fabric8 + kubernetes-client-api + + + + io.fabric8 + openshift-client-api @@ -132,11 +151,6 @@ jackson-jaxrs-json-provider - - com.squareup.okhttp3 - okhttp - - org.kohsuke.metainf-services metainf-services @@ -151,8 +165,6 @@ io.sundr builder-annotations 0.103.1 - compile - true @@ -172,6 +184,11 @@ mockito-core test + + org.hamcrest + hamcrest + compile + junit junit diff --git a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/CubeOpenShiftConfiguration.java b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/CubeOpenShiftConfiguration.java index fb71068bd..3c692614b 100644 --- a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/CubeOpenShiftConfiguration.java +++ b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/CubeOpenShiftConfiguration.java @@ -23,13 +23,13 @@ import static org.arquillian.cube.impl.util.ConfigUtil.getLongProperty; import static org.arquillian.cube.impl.util.ConfigUtil.getStringProperty; -@Buildable(builderPackage = "io.fabric8.kubernetes.api.builder", generateBuilderPackage = false, editableEnabled = false, refs = { +@Buildable(generateBuilderPackage = false, editableEnabled = false, refs = { @BuildableReference(DefaultConfiguration.class) }) public class CubeOpenShiftConfiguration extends DefaultConfiguration implements ConfigurationHandle, Serializable{ - private static final Config FALLBACK_CONFIG = new ConfigBuilder().build(); + private static final Config FALLBACK_CONFIG = new io.fabric8.kubernetes.client.ConfigBuilder().build(); //Deprecated Property Names: { private static final String ORIGIN_SERVER = "originServer"; diff --git a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/GitServer.java b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/GitServer.java index ec1bb13ef..de21cf13b 100644 --- a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/GitServer.java +++ b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/GitServer.java @@ -5,16 +5,16 @@ import io.fabric8.kubernetes.api.model.Service; import io.fabric8.kubernetes.api.model.ServiceBuilder; import io.fabric8.kubernetes.client.Config; -import io.fabric8.openshift.client.NamespacedOpenShiftClient; -import java.io.File; -import java.net.URI; -import java.util.HashMap; -import java.util.Map; import org.apache.commons.io.FileUtils; import org.arquillian.cube.kubernetes.impl.portforward.PortForwarder; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.lib.Repository; +import java.io.File; +import java.net.URI; +import java.util.HashMap; +import java.util.Map; + public class GitServer { private static final String GIT_SERVICE = "git"; private static final String GIT_LOCALPORT = "10001"; diff --git a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/OpenShiftAssistant.java b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/OpenShiftAssistant.java index dc56bd56c..5598e9dda 100644 --- a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/OpenShiftAssistant.java +++ b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/OpenShiftAssistant.java @@ -161,7 +161,6 @@ public void awaitApplicationReadinessOrFail() { */ @Override public void awaitApplicationReadinessOrFail(final String applicationName) { - /** rls TODO https://github.com/arquillian/arquillian-cube/issues/1282 await().atMost(5, TimeUnit.MINUTES).until(() -> { return getClient() .deploymentConfigs() @@ -169,7 +168,6 @@ public void awaitApplicationReadinessOrFail(final String applicationName) { .withName(applicationName).isReady(); } ); - **/ } /** diff --git a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/OpenShiftAssistantTemplate.java b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/OpenShiftAssistantTemplate.java index 97bfd4139..783cee664 100644 --- a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/OpenShiftAssistantTemplate.java +++ b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/OpenShiftAssistantTemplate.java @@ -1,10 +1,7 @@ package org.arquillian.cube.openshift.impl.client; +import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.KubernetesList; -/** rls TODO -import io.fabric8.openshift.api.model.DoneableTemplate; -**/ -import io.fabric8.openshift.api.model.Template; import io.fabric8.openshift.client.OpenShiftClient; import io.fabric8.openshift.client.ParameterValue; import io.fabric8.openshift.client.dsl.TemplateResource; @@ -47,17 +44,15 @@ public OpenShiftAssistantTemplate parameter(String name, String value) { * @throws IOException */ public void deploy() throws IOException { - /** rls TODO fix code in method processTemplate and then remove the comment blk. KubernetesList list = processTemplate(templateURL, parameterValues); createResources(list); - **/ } - /** rls TODO https://github.com/arquillian/arquillian-cube/issues/1291 + private KubernetesList processTemplate(URL templateURL, HashMap parameterValues) throws IOException { List list = new ArrayList<>(); try (InputStream stream = templateURL.openStream()) { - TemplateResource templateHandle = + TemplateResource templateHandle = client.templates().inNamespace(client.getNamespace()).load(stream); list.addAll(parameterValues.entrySet().stream() @@ -67,9 +62,8 @@ private KubernetesList processTemplate(URL templateURL, HashMap return templateHandle.process(list.toArray(new ParameterValue[parameterValues.size()])); } } - **/ - private KubernetesList createResources(KubernetesList list) { - return client.lists().inNamespace(client.getNamespace()).create(list); + private List createResources(KubernetesList list) { + return client.resourceList(list).inNamespace(client.getNamespace()).create(); } } diff --git a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/OpenShiftClient.java b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/OpenShiftClient.java index 45ec53192..1f2db2e76 100644 --- a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/OpenShiftClient.java +++ b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/OpenShiftClient.java @@ -53,7 +53,7 @@ public List clean(ResourceHolder holder) { } } try { - getClient().lists().delete(new KubernetesListBuilder().withItems(resourcesToDelete).build()); + getClient().resourceList(resourcesToDelete).delete(); } catch (Exception e) { exceptions.add(e); } diff --git a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/ResourceUtil.java b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/ResourceUtil.java index 44e92d654..35cb873d4 100644 --- a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/ResourceUtil.java +++ b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/ResourceUtil.java @@ -190,7 +190,6 @@ public static Binding toBinding(Service pod) { */ public static void awaitRoute(URL routeUrl, int timeout, TimeUnit timeoutUnit, int repetitions, int... statusCodes) { AtomicInteger successfulAwaitsInARow = new AtomicInteger(0); - /** rls TODO https://github.com/arquillian/arquillian-cube/issues/1282 await().atMost(timeout, timeoutUnit).until(() -> { if (tryConnect(routeUrl, statusCodes)) { successfulAwaitsInARow.incrementAndGet(); @@ -199,7 +198,6 @@ public static void awaitRoute(URL routeUrl, int timeout, TimeUnit timeoutUnit, i } return successfulAwaitsInARow.get() >= repetitions; }); - **/ } public static void awaitRoute(URL routeUrl, int timeout, TimeUnit timeoutUnit, int... statusCodes) { diff --git a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/dns/ArqCubeNameService.java b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/dns/ArqCubeNameService.java index 28f983193..08c5cff00 100644 --- a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/dns/ArqCubeNameService.java +++ b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/dns/ArqCubeNameService.java @@ -1,9 +1,7 @@ package org.arquillian.cube.openshift.impl.dns; import io.fabric8.openshift.api.model.RouteList; -/** rls TODO https://github.com/arquillian/arquillian-cube/issues/1290 -import sun.net.spi.nameservice.NameService; -**/ + import java.net.InetAddress; import java.net.UnknownHostException; import java.util.HashSet; @@ -16,12 +14,7 @@ * @author Rob Cernich * @author fspolti */ -public class ArqCubeNameService - /** rls TODO https://github.com/arquillian/arquillian-cube/issues/1290 - implements NameService - **/ -{ - +public class ArqCubeNameService implements INameService { private static final Set hosts = new HashSet<>(); private static InetAddress routerAddr; @@ -41,9 +34,8 @@ public static void setRoutes(RouteList routeList, String routerHost) { }); } } - /** rls TODO https://github.com/arquillian/arquillian-cube/issues/1290 + @Override - **/ public InetAddress[] lookupAllHostAddr(String host) throws UnknownHostException { synchronized (hosts) { if (routerAddr != null && hosts.contains(host)) { @@ -53,9 +45,7 @@ public InetAddress[] lookupAllHostAddr(String host) throws UnknownHostException } } - /** rls TODO https://github.com/arquillian/arquillian-cube/issues/1290 @Override - **/ public String getHostByAddr(byte[] addr) throws UnknownHostException { throw new UnknownHostException(); } diff --git a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/dns/ArqCubeNameServiceDescriptor.java b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/dns/ArqCubeNameServiceDescriptor.java deleted file mode 100644 index 05677a4f6..000000000 --- a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/dns/ArqCubeNameServiceDescriptor.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.arquillian.cube.openshift.impl.dns; - -/** rls TODO -import sun.net.spi.nameservice.NameService; -import sun.net.spi.nameservice.NameServiceDescriptor; -**/ -/** - * ArqCubeNameServiceDescriptor - *

- * Descriptor for OpenShift Route NameService. - * - * @author Rob Cernich - */ -public class ArqCubeNameServiceDescriptor - /** rls TODO https://github.com/arquillian/arquillian-cube/issues/1290 - implements NameServiceDescriptor - **/ -{ - /** rls TODO - @Override - - public NameService createNameService() throws Exception { - return new ArqCubeNameService(); - } - **/ - /** rls TODO - @Override - **/ - public String getProviderName() { - return "ArquillianCubeNameService"; - } - - /** rls TODO - @Override - **/ - public String getType() { - return "dns"; - } - -} diff --git a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/dns/INameService.java b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/dns/INameService.java new file mode 100644 index 000000000..e03cb3ff5 --- /dev/null +++ b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/dns/INameService.java @@ -0,0 +1,69 @@ +package org.arquillian.cube.openshift.impl.dns; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.Arrays; + +/** + * Provides an invocation handler to register a DNS service + * + * See https://stackoverflow.com/questions/11647629/how-to-configure-hostname-resolution-to-use-a-custom-dns-server-in-java + */ +public interface INameService extends InvocationHandler { + public static void install(final INameService dns) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, ClassNotFoundException { + final Class inetAddressClass = InetAddress.class; + Object neu; + Field nameServiceField; + try { + final Class iface = Class.forName("java.net.InetAddress$NameService"); + nameServiceField = inetAddressClass.getDeclaredField("nameService"); + neu = Proxy.newProxyInstance(iface.getClassLoader(), new Class[] { iface }, dns); + } catch(final ClassNotFoundException|NoSuchFieldException e) { + nameServiceField = inetAddressClass.getDeclaredField("nameServices"); + final Class iface = Class.forName("sun.net.spi.nameservice.NameService"); + neu = Arrays.asList(Proxy.newProxyInstance(iface.getClassLoader(), new Class[] { iface }, dns)); + } + nameServiceField.setAccessible(true); + nameServiceField.set(inetAddressClass, neu); + } + + /** + * Lookup a host mapping by name. Retrieve the IP addresses associated with a host + * + * @param host the specified hostname + * @return array of IP addresses for the requested host + * @throws UnknownHostException if no IP address for the {@code host} could be found + */ + InetAddress[] lookupAllHostAddr(final String host) throws UnknownHostException; + + /** + * Lookup the host corresponding to the IP address provided + * + * @param addr byte array representing an IP address + * @return {@code String} representing the host name mapping + * @throws UnknownHostException + * if no host found for the specified IP address + */ + String getHostByAddr(final byte[] addr) throws UnknownHostException; + + @Override default public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { + switch(method.getName()) { + case "lookupAllHostAddr": return lookupAllHostAddr((String)args[0]); + case "getHostByAddr" : return getHostByAddr ((byte[])args[0]); + default : + final StringBuilder o = new StringBuilder(); + o.append(method.getReturnType().getCanonicalName()+" "+method.getName()+"("); + final Class[] ps = method.getParameterTypes(); + for(int i=0;i0) o.append(", "); + o.append(ps[i].getCanonicalName()).append(" p").append(i); + } + o.append(")"); + throw new UnsupportedOperationException(o.toString()); + } + } +} diff --git a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/enricher/AwaitRoute.java b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/enricher/AwaitRoute.java index 899cf3b74..c09831f18 100644 --- a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/enricher/AwaitRoute.java +++ b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/enricher/AwaitRoute.java @@ -6,7 +6,7 @@ import java.lang.annotation.Target; import java.util.concurrent.TimeUnit; -import javax.inject.Qualifier; +import jakarta.inject.Qualifier; import static java.lang.annotation.RetentionPolicy.RUNTIME; diff --git a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/enricher/RouteURL.java b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/enricher/RouteURL.java index 5b8067373..9e9a0fee8 100644 --- a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/enricher/RouteURL.java +++ b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/enricher/RouteURL.java @@ -1,6 +1,6 @@ package org.arquillian.cube.openshift.impl.enricher; -import javax.inject.Qualifier; +import jakarta.inject.Qualifier; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/fabric8/F8OpenShiftAdapter.java b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/fabric8/F8OpenShiftAdapter.java index c77fa593e..108e222c2 100644 --- a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/fabric8/F8OpenShiftAdapter.java +++ b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/fabric8/F8OpenShiftAdapter.java @@ -25,19 +25,15 @@ import io.fabric8.kubernetes.api.model.Container; import io.fabric8.kubernetes.api.model.ContainerPort; -/** rls TODO https://github.com/arquillian/arquillian-cube/issues/1291 -import io.fabric8.kubernetes.api.model.DoneablePod; -**/ import io.fabric8.kubernetes.api.model.EnvVar; import io.fabric8.kubernetes.api.model.ExecAction; import io.fabric8.kubernetes.api.model.HTTPGetAction; -/** rls TODO https://github.com/arquillian/arquillian-cube/issues/1291 -import io.fabric8.kubernetes.api.model.Handler; -**/ import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.IntOrString; import io.fabric8.kubernetes.api.model.KubernetesList; +import io.fabric8.kubernetes.api.model.KubernetesListBuilder; import io.fabric8.kubernetes.api.model.Lifecycle; +import io.fabric8.kubernetes.api.model.LifecycleHandler; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.kubernetes.api.model.PersistentVolumeClaim; import io.fabric8.kubernetes.api.model.Pod; @@ -61,24 +57,18 @@ import io.fabric8.openshift.api.model.Build; import io.fabric8.openshift.api.model.BuildList; import io.fabric8.openshift.api.model.DeploymentConfig; +import io.fabric8.openshift.api.model.DeploymentConfigBuilder; import io.fabric8.openshift.api.model.DeploymentConfigList; import io.fabric8.openshift.api.model.DeploymentConfigStatus; -/** rls TODO https://github.com/arquillian/arquillian-cube/issues/1291 -import io.fabric8.openshift.api.model.DoneableDeploymentConfig; -import io.fabric8.openshift.api.model.DoneableTemplate; -**/ import io.fabric8.openshift.api.model.Project; +import io.fabric8.openshift.api.model.ProjectRequestBuilder; import io.fabric8.openshift.api.model.RoleBinding; import io.fabric8.openshift.api.model.RoleBindingBuilder; import io.fabric8.openshift.api.model.Template; -import io.fabric8.openshift.client.DefaultOpenShiftClient; import io.fabric8.openshift.client.NamespacedOpenShiftClient; -import io.fabric8.openshift.client.OpenShiftConfig; -import io.fabric8.openshift.client.OpenShiftConfigBuilder; import io.fabric8.openshift.client.ParameterValue; import io.fabric8.openshift.client.dsl.DeployableScalableResource; import io.fabric8.openshift.client.dsl.TemplateResource; -import okhttp3.Response; import org.arquillian.cube.openshift.api.MountSecret; import org.arquillian.cube.openshift.api.model.OpenShiftResource; import org.arquillian.cube.openshift.impl.adapter.AbstractOpenShiftAdapter; @@ -161,15 +151,12 @@ protected Proxy createProxy() { private Object createProject() { // oc new-project - return null; // rls TODO remove this stmt - /** rls TODO https://github.com/arquillian/arquillian-cube/issues/1291 return client.projectrequests() - .createNew() + .create(new ProjectRequestBuilder() .withNewMetadata() .withName(configuration.getNamespace()) .endMetadata() - .done(); - **/ + .build()); } public boolean checkProject() { @@ -183,29 +170,26 @@ public boolean checkProject() { } public boolean deleteProject() { - return client.projects().withName(configuration.getNamespace()).delete(); + return client.projects().withName(configuration.getNamespace()).delete().stream().allMatch(d -> d.getCauses().isEmpty()); } public void deletePod(String podName, long gracePeriodSeconds) { - /** rls TODO https://github.com/arquillian/arquillian-cube/issues/1291 - PodResource resource = + PodResource resource = client.pods().inNamespace(configuration.getNamespace()).withName(podName); - Deletable deletable = resource; + Deletable deletable = resource; if (gracePeriodSeconds >= 0) { deletable = resource.withGracePeriod(gracePeriodSeconds); } deletable.delete(); - **/ } public void triggerDeploymentConfigUpdate(String prefix, boolean wait, Map variables) throws Exception { DeploymentConfigList list = client.deploymentConfigs().inNamespace(configuration.getNamespace()).list(); String actualName = getActualName(prefix, list.getItems(), "No such deployment config: " + prefix); - /** rls TODO https://github.com/arquillian/arquillian-cube/issues/1291 - final DeployableScalableResource ccr = - client.deploymentConfigs().inNamespace(configuration.getNamespace()).withName(actualName); - List containers = ccr.get().getSpec().getTemplate().getSpec().getContainers(); + final DeploymentConfig ccr = + client.deploymentConfigs().inNamespace(configuration.getNamespace()).withName(actualName).get(); + List containers = ccr.getSpec().getTemplate().getSpec().getContainers(); if (containers.size() > 0) { // there should be one to do upgrade Container container = containers.get(0); @@ -221,7 +205,7 @@ public void triggerDeploymentConfigUpdate(String prefix, boolean wait, Map new DeploymentConfigBuilder(d) .editSpec() .editTemplate() .editSpec() @@ -229,13 +213,13 @@ public void triggerDeploymentConfigUpdate(String prefix, boolean wait, Map getContainers(String name, RCContext context) throws Exc Lifecycle lifecycle = null; if (!context.isIgnorePreStop() && context.getLifecycleHook() != null && context.getPreStopPath() != null) { lifecycle = new Lifecycle(); - /** rls TODO https://github.com/arquillian/arquillian-cube/issues/1291 - Handler preStopHandler = createHandler(context.getLifecycleHook(), context.getPreStopPath(), cps); - lifecycle.setPreStop(preStopHandler); - **/ - lifecycle.setPreStop(null); // rls TODO remove this stmt + LifecycleHandler preStopHandler = createHandler(context.getLifecycleHook(), context.getPreStopPath(), cps); + lifecycle.setPreStop(preStopHandler); } Probe probe = null; @@ -344,9 +324,9 @@ private List getContainers(String name, RCContext context) throws Exc return Collections.singletonList(container); } - /** rls TODO https://github.com/arquillian/arquillian-cube/issues/1291 - private Handler createHandler(HookType hookType, String preStopPath, List ports) { - Handler preStopHandler = new Handler(); + + private LifecycleHandler createHandler(HookType hookType, String preStopPath, List ports) { + LifecycleHandler preStopHandler = new LifecycleHandler(); switch (hookType) { case HTTP_GET: HTTPGetAction httpGet = new HTTPGetAction(); @@ -363,7 +343,6 @@ private Handler createHandler(HookType hookType, String preStopPath, List probeCommands, List ports) { switch (hookType) { @@ -425,8 +404,7 @@ private KubernetesList processTemplate(String templateURL, List throws IOException { try (InputStream stream = new URL(templateURL).openStream()) { - /** rls TODO https://github.com/arquillian/arquillian-cube/issues/1291 - TemplateResource templateHandle = + TemplateResource templateHandle = client.templates().inNamespace(configuration.getNamespace()).load(stream); Template template = templateHandle.get(); if (template.getLabels() == null) { @@ -434,13 +412,13 @@ private KubernetesList processTemplate(String templateURL, List } template.getLabels().putAll(labels); return templateHandle.process(values.toArray(new ParameterValue[values.size()])); - **/ - return null; } } private KubernetesList createResources(KubernetesList list) { - return client.lists().inNamespace(configuration.getNamespace()).create(list); + return new KubernetesListBuilder() + .withItems(client.resourceList(list).inNamespace(configuration.getNamespace()).create()) + .build(); } protected OpenShiftResourceHandle createResourceFromStream(InputStream stream) throws IOException { @@ -452,12 +430,12 @@ protected OpenShiftResourceHandle createResourceFromStream(InputStream stream) t } } - public Object deleteTemplate(String templateKey) throws Exception { + public Object deleteTemplate(String templateKey) { KubernetesList config = templates.get(templateKey); if (config != null) { - return client.lists().inNamespace(configuration.getNamespace()).delete(config); + return client.resourceList(config).inNamespace(configuration.getNamespace()).delete(); } - return config; + return null; } protected OpenShiftResourceHandle createRoleBinding(String roleRefName, String userName) { @@ -488,14 +466,10 @@ public Service getService(String namespace, String serviceName) { return client.services().inNamespace(namespace).withName(serviceName).get(); } - private Object getDC(String prefix) throws Exception { - /** rls TODO https://github.com/arquillian/arquillian-cube/issues/1291 - private DeployableScalableResource getDC(String prefix) throws Exception { + private DeployableScalableResource getDC(String prefix) throws Exception { DeploymentConfigList list = client.deploymentConfigs().inNamespace(configuration.getNamespace()).list(); String actualName = getActualName(prefix, list.getItems(), "No DC found starting with " + prefix); return client.deploymentConfigs().inNamespace(configuration.getNamespace()).withName(actualName); - **/ - return null; // rls TODO remove this stmt } private void delayDeployment(DeploymentConfig dc, String prefix, int replicas, Operator op) throws Exception { @@ -509,17 +483,11 @@ private void delayDeployment(DeploymentConfig dc, String prefix, int replicas, O } protected Map getLabels(String prefix) throws Exception { - /** rls todo return getDC(prefix).get().getSpec().getSelector(); - **/ - return new HashMap(); // rls TODO remove this stmt } public void scaleDeployment(final String prefix, final int replicas) throws Exception { - /** rls TODO DeploymentConfig dc = getDC(prefix).scale(replicas); - **/ - DeploymentConfig dc = null; // rls TODO remove this stmt delayDeployment(dc, prefix, replicas, Operator.EQUAL); } @@ -548,8 +516,7 @@ public InputStream streamLog(String podName) throws Exception { public String getLog(String prefix, Map labels) throws Exception { List pods; - /** rls TODO https://github.com/arquillian/arquillian-cube/issues/1291 - NonNamespaceOperation> allPods = + NonNamespaceOperation allPods = client.pods().inNamespace(configuration.getNamespace()); if (labels == null) { @@ -557,8 +524,6 @@ public String getLog(String prefix, Map labels) throws Exception } else { pods = allPods.withLabels(labels).list().getItems(); } - **/ - pods = new ArrayList<>(); // rls TODO remove this stmt String actualName; @@ -652,7 +617,8 @@ public void cleanServices(String... ids) throws Exception { for (String id : ids) { try { boolean exists = - client.services().inNamespace(configuration.getNamespace()).withName(id).cascading(false).delete(); + client.services().inNamespace(configuration.getNamespace()).withName(id).cascading(false).delete() + .stream().allMatch(d -> d.getCauses().isEmpty()); log.info(String.format("Service [%s] delete: %s.", id, exists)); } catch (Exception e) { log.log(Level.WARNING, String.format("Exception while deleting service [%s]: %s", id, e), e); @@ -667,7 +633,7 @@ public void cleanReplicationControllers(String... ids) throws Exception { .inNamespace(configuration.getNamespace()) .withName(id) .cascading(false) - .delete(); + .delete().stream().allMatch(d -> d.getCauses().isEmpty());; log.info(String.format("RC [%s] delete: %s.", id, exists)); } catch (Exception e) { log.log(Level.WARNING, String.format("Exception while deleting RC [%s]: %s", id, e), e); @@ -680,7 +646,7 @@ public void cleanPods(Map labels) throws Exception { try { for (Pod pod : pods.getItems()) { String podId = getName(pod.getMetadata()); - boolean exists = client.pods().inNamespace(configuration.getNamespace()).withName(podId).delete(); + boolean exists = client.pods().inNamespace(configuration.getNamespace()).withName(podId).delete().stream().allMatch(d -> d.getCauses().isEmpty());; log.info(String.format("Pod [%s] delete: %s.", podId, exists)); } } catch (Exception e) { @@ -700,7 +666,7 @@ private void cleanBuilds(Map labels) throws Exception { for (Build build : builds.getItems()) { String buildId = getName(build.getMetadata()); - boolean exists = client.builds().inNamespace(configuration.getNamespace()).withName(buildId).delete(); + boolean exists = client.builds().inNamespace(configuration.getNamespace()).withName(buildId).delete().stream().allMatch(d -> d.getCauses().isEmpty());; log.info(String.format("Build [%s] delete: %s.", buildId, exists)); } } catch (Exception e) { @@ -716,7 +682,7 @@ private void cleanDeployments(Map labels) throws Exception { String rcId = getName(rc.getMetadata()); client.replicationControllers().inNamespace(configuration.getNamespace()).withName(rcId).scale(0, true); boolean exists = - client.replicationControllers().inNamespace(configuration.getNamespace()).withName(rcId).delete(); + client.replicationControllers().inNamespace(configuration.getNamespace()).withName(rcId).delete().stream().allMatch(d -> d.getCauses().isEmpty());; log.info(String.format("ReplicationController [%s] delete: %s.", rcId, exists)); } } catch (Exception e) { @@ -733,7 +699,7 @@ public void close() throws IOException { static IntOrString toIntOrString(ContainerPort port) { IntOrString intOrString = new IntOrString(); - intOrString.setIntVal(port.getContainerPort()); + intOrString.setValue(port.getContainerPort()); return intOrString; } diff --git a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/fabric8/F8Proxy.java b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/fabric8/F8Proxy.java index dee1fd0f2..4b5a6b85d 100644 --- a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/fabric8/F8Proxy.java +++ b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/fabric8/F8Proxy.java @@ -26,24 +26,27 @@ import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.PodCondition; import io.fabric8.kubernetes.api.model.PodStatus; -import io.fabric8.kubernetes.client.Adapters; +import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.http.HttpClient; import io.fabric8.kubernetes.client.internal.SSLUtils; +import io.fabric8.kubernetes.client.jdkhttp.JdkHttpClientFactory; import io.fabric8.openshift.client.NamespacedOpenShiftClient; import io.fabric8.openshift.client.OpenShiftClient; + import java.util.List; import java.util.Map; +import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; -import okhttp3.OkHttpClient; +import org.arquillian.cube.kubernetes.impl.ClientConfigBuilder; import org.arquillian.cube.openshift.impl.client.CubeOpenShiftConfiguration; import org.arquillian.cube.openshift.impl.proxy.AbstractProxy; -import org.arquillian.cube.openshift.impl.utils.OkHttpClientUtils; /** * @author Ales Justin */ public class F8Proxy extends AbstractProxy { private final OpenShiftClient client; - private OkHttpClient httpClient; + private HttpClient httpClient; public F8Proxy(CubeOpenShiftConfiguration configuration, NamespacedOpenShiftClient client) { super(configuration); @@ -58,12 +61,16 @@ public SSLContext getSSLContext() { } } - protected synchronized OkHttpClient getHttpClient() { + protected synchronized HttpClient getHttpClient() { if (httpClient == null) { - OkHttpClient okHttpClient = Adapters.get(OkHttpClient.class).adapt(client); - OkHttpClient.Builder builder = okHttpClient.newBuilder(); // clone - OkHttpClientUtils.applyConnectTimeout(builder, configuration.getHttpClientTimeout()); - OkHttpClientUtils.applyCookieJar(builder); + final Config httpClientConfig = new ClientConfigBuilder().configuration(configuration).build(); + final HttpClient.Factory httpClientFactory = new JdkHttpClientFactory(); + HttpClient.Builder builder = httpClientFactory.newBuilder(httpClientConfig); // clone + //Increasing timeout to avoid this issue: + //Caused by: io.fabric8.kubernetes.client.KubernetesClientException: Error executing: GET at: + //https://localhost:8443/api/v1/namespaces/cearq-jws-tcznhcfw354/pods?labelSelector=deploymentConfig%3Djws-app. Cause: timeout + builder.connectTimeout(configuration.getHttpClientTimeout(), TimeUnit.SECONDS); + // TODO - TBD - OkHttpClientUtils.applyCookieJar(builder); httpClient = builder.build(); } return httpClient; diff --git a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/namespace/OpenshiftNamespaceService.java b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/namespace/OpenshiftNamespaceService.java index e891a9b2e..fe80ca3e6 100644 --- a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/namespace/OpenshiftNamespaceService.java +++ b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/namespace/OpenshiftNamespaceService.java @@ -76,7 +76,7 @@ public Boolean delete(String namespace) { logger.info("Deleting project: " + namespace + "..."); OpenShiftClient openShiftClient = client.adapt(OpenShiftClient.class); - Boolean deleted = openShiftClient.projects().withName(namespace).delete(); + Boolean deleted = openShiftClient.projects().withName(namespace).delete().stream().allMatch(d -> d.getCauses().isEmpty()); if (deleted) { logger.info("Project: " + namespace + ", successfully deleted"); } diff --git a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/oauth/OauthUtils.java b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/oauth/OauthUtils.java index d18890b0e..d963ec907 100644 --- a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/oauth/OauthUtils.java +++ b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/oauth/OauthUtils.java @@ -1,10 +1,13 @@ package org.arquillian.cube.openshift.impl.oauth; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpRequest; +import io.fabric8.kubernetes.client.http.HttpResponse; +import io.fabric8.kubernetes.client.jdkhttp.JdkHttpClientFactory; + +import java.net.URL; import java.util.Base64; import java.util.logging.Logger; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; /** * Created by fspolti on 6/20/16. @@ -23,15 +26,16 @@ public static String getToken(String openshiftUrl, String uid, String pwd) throw String password = pwd != null ? pwd : PASSWORD; log.info("Issuing a new token for user: " + username); - OkHttpClient client = new OkHttpClient(); - Request request = new Request.Builder() - .url(url + "/" + TOKEN_REQUEST_URI) + final HttpClient.Builder httpClientBuilder = new JdkHttpClientFactory().newBuilder(); + final HttpClient httpClient = httpClientBuilder.build(); + final HttpRequest request = httpClient.newHttpRequestBuilder() + .url(new URL(url + "/" + TOKEN_REQUEST_URI)) .header("Authorization", "Basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes())) .build(); - Response response = client.newCall(request).execute(); + HttpResponse response = httpClient.sendAsync(request, String.class).get(); - String result = response.body().string(); + String result = response.body(); String token = result.substring(result.indexOf("") + 6, result.indexOf("")); log.info("Got token: " + token); diff --git a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/proxy/AbstractProxy.java b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/proxy/AbstractProxy.java index 337506bcd..ea16b432f 100644 --- a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/proxy/AbstractProxy.java +++ b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/proxy/AbstractProxy.java @@ -23,25 +23,29 @@ package org.arquillian.cube.openshift.impl.proxy; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpRequest; +import io.fabric8.kubernetes.client.http.HttpResponse; +import org.arquillian.cube.openshift.api.ManagementHandle; +import org.arquillian.cube.openshift.impl.client.CubeOpenShiftConfiguration; +import org.arquillian.cube.openshift.impl.utils.ManagementHandleImpl; + +import javax.net.ssl.SSLContext; +import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; -import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.HttpURLConnection; +import java.net.URL; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; -import javax.net.ssl.SSLContext; -import okhttp3.MediaType; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import org.arquillian.cube.openshift.api.ManagementHandle; -import org.arquillian.cube.openshift.impl.client.CubeOpenShiftConfiguration; -import org.arquillian.cube.openshift.impl.utils.ManagementHandleImpl; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; /** * @author Ales Justin @@ -114,13 +118,12 @@ public String findPod(Map labels, int index) { } } - protected abstract OkHttpClient getHttpClient(); + protected abstract HttpClient getHttpClient(); public T post(String url, Class returnType, Object requestObject) throws Exception { - final OkHttpClient httpClient = getHttpClient(); + final HttpClient httpClient = getHttpClient(); - Request.Builder builder = new Request.Builder(); - builder.url(url); + HttpRequest.Builder builder = httpClient.newHttpRequestBuilder().url(new URL(url)); if (requestObject != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); @@ -130,20 +133,17 @@ public T post(String url, Class returnType, Object requestObject) throws } catch (Exception e) { throw new RuntimeException("Error sending request Object, " + requestObject, e); } - RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"), baos.toByteArray()); - builder.post(body); + builder.post("application/octet-stream", baos.toByteArray()); } - Request request = builder.build(); - Response response = httpClient.newCall(request).execute(); + HttpRequest request = builder.build(); + HttpResponse response = httpClient.sendAsync(request, returnType).get(); int responseCode = response.code(); if (responseCode == HttpURLConnection.HTTP_OK) { Object o; - try (ObjectInputStream ois = new ObjectInputStream(response.body().byteStream())) { - o = ois.readObject(); - } + o = new ObjectMapper().readValue(response.bodyString(), returnType); if (returnType.isInstance(o) == false) { throw new IllegalStateException("Error reading results, expected a " + returnType.getName() + " but got " + o); @@ -160,20 +160,21 @@ public T post(String url, Class returnType, Object requestObject) throws } public InputStream post(String url, String encoding, byte[] bytes) throws IOException { - final OkHttpClient httpClient = getHttpClient(); - - Request.Builder builder = new Request.Builder(); - builder.url(url); + final HttpClient httpClient = getHttpClient(); + HttpRequest.Builder builder = httpClient.newHttpRequestBuilder().url(new URL(url)); if (bytes != null) { - RequestBody body = RequestBody.create(MediaType.parse(encoding), bytes); - builder.post(body); + builder.post(encoding, bytes); + } + try { + HttpRequest request = builder.build(); + final HttpResponse response = httpClient + .sendAsync(request, byte[].class) + .get(10, TimeUnit.SECONDS); + return new ByteArrayInputStream(response.body()); + } catch (InterruptedException | ExecutionException | TimeoutException e) { + throw new RuntimeException(e); } - - Request request = builder.build(); - Response response = httpClient.newCall(request).execute(); - - return response.body().byteStream(); } public InputStream post(String podName, int port, String path) throws Exception { @@ -192,9 +193,9 @@ private InputStream getInputStream(String url) throws IOException { public int status(String url) { try { - OkHttpClient httpClient = getHttpClient(); - Request request = new Request.Builder().url(url).build(); - Response response = httpClient.newCall(request).execute(); + HttpClient httpClient = getHttpClient(); + HttpRequest request = httpClient.newHttpRequestBuilder().url(new URL(url)).build(); + HttpResponse response = httpClient.sendAsync(request, Void.class).get(); return response.code(); } catch (Exception e) { throw new IllegalStateException(e); diff --git a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/requirement/OpenshiftRequirement.java b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/requirement/OpenshiftRequirement.java index e12142989..8fdc69c08 100644 --- a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/requirement/OpenshiftRequirement.java +++ b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/requirement/OpenshiftRequirement.java @@ -1,15 +1,20 @@ package org.arquillian.cube.openshift.impl.requirement; +import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.http.HttpClient; +import io.fabric8.kubernetes.client.http.HttpRequest; +import io.fabric8.kubernetes.client.http.HttpResponse; +import io.fabric8.kubernetes.client.jdkhttp.JdkHttpClientFactory; import io.fabric8.kubernetes.client.utils.URLUtils; import io.fabric8.openshift.client.OpenShiftClient; import java.io.IOException; +import java.net.URL; import java.util.Arrays; import java.util.List; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; +import java.util.concurrent.ExecutionException; + import org.arquillian.cube.kubernetes.impl.ClientConfigBuilder; import org.arquillian.cube.kubernetes.impl.DefaultConfiguration; import org.arquillian.cube.kubernetes.impl.ExtensionRegistrar; @@ -27,17 +32,18 @@ public void check(RequiresOpenshift context) throws UnsatisfiedRequirementExcept final DefaultConfiguration config = new ExtensionRegistrar().loadExtension(extension); - try (KubernetesClient client = new DefaultKubernetesClient( - new ClientConfigBuilder().configuration(config).build())) { + final Config httpClientConfig = new ClientConfigBuilder().configuration(config).build(); + try (KubernetesClient client = new DefaultKubernetesClient(httpClientConfig)) { - OkHttpClient httpClient = client.adapt(OkHttpClient.class); + HttpClient.Factory httpClientFactory = new JdkHttpClientFactory(); + HttpClient httpClient = httpClientFactory.newBuilder(httpClientConfig).build(); - Request versionRequest = new Request.Builder() - .get() - .url(URLUtils.join(client.getMasterUrl().toString(), "version")) + HttpRequest versionRequest = httpClient.newHttpRequestBuilder() + .url(new URL(URLUtils.join(client.getMasterUrl().toString(), "version").toString())) + .method("GET", "*/*", null) .build(); - Response response = httpClient.newCall(versionRequest).execute(); + HttpResponse response = httpClient.sendAsync(versionRequest, String.class).get(); if (!response.isSuccessful()) { throw new UnsatisfiedRequirementException( "Failed to verify Openshift version, due to: [" + response.message() + "]"); @@ -45,7 +51,7 @@ public void check(RequiresOpenshift context) throws UnsatisfiedRequirementExcept throw new UnsatisfiedRequirementException( "A valid Kubernetes environmnet was found, but not Openshift."); } - } catch (IOException | IllegalArgumentException e) { + } catch (IOException | IllegalArgumentException | InterruptedException | ExecutionException e) { throw new UnsatisfiedRequirementException( "Error while checking Openshift version: [" + e.getMessage() + "]"); } diff --git a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/utils/OkHttpClientUtils.java b/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/utils/OkHttpClientUtils.java deleted file mode 100644 index 20a624380..000000000 --- a/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/utils/OkHttpClientUtils.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * JBoss, Home of Professional Open Source - * Copyright 2015 Red Hat Inc. and/or its affiliates and other - * contributors as indicated by the @author tags. All rights reserved. - * See the copyright.txt in the distribution for a full listing of - * individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ - -package org.arquillian.cube.openshift.impl.utils; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.TimeUnit; -import okhttp3.Cookie; -import okhttp3.CookieJar; -import okhttp3.HttpUrl; -import okhttp3.OkHttpClient; - -/** - * Handle OkHttpClient. - * - * @author Ales Justin - */ -public class OkHttpClientUtils { - private static final SimpleCookieJar COOKIE_JAR = new SimpleCookieJar(); - - public static void applyConnectTimeout(OkHttpClient.Builder builder, long timeout) { - //Increasing timeout to avoid this issue: - //Caused by: io.fabric8.kubernetes.client.KubernetesClientException: Error executing: GET at: - //https://localhost:8443/api/v1/namespaces/cearq-jws-tcznhcfw354/pods?labelSelector=deploymentConfig%3Djws-app. Cause: timeout - builder.connectTimeout(timeout, TimeUnit.SECONDS); - } - - public static void applyCookieJar(OkHttpClient.Builder builder) { - COOKIE_JAR.clear(); // reset - builder.cookieJar(COOKIE_JAR); - } - - /** - * Just copy cookies based on proxy path. - */ - private static class SimpleCookieJar implements CookieJar { - private static final String _PROXY = "/proxy"; - private Map> cookiesMap = new ConcurrentHashMap<>(); - - private void clear() { - cookiesMap.clear(); - } - - private static String path(HttpUrl url) { - String path = url.encodedPath(); - int p = path.indexOf(_PROXY); - return path.substring(p + _PROXY.length()); - } - - public synchronized void saveFromResponse(HttpUrl url, List cookies) { - cookiesMap.put(path(url), cookies); - } - - public synchronized List loadForRequest(HttpUrl url) { - String path = path(url); - List list = new ArrayList<>(); - for (Map.Entry> entry : cookiesMap.entrySet()) { - if (path.startsWith(entry.getKey())) { - for (Cookie cookie : entry.getValue()) { - list.add(cookie); - } - } - } - return list.isEmpty() ? Collections.emptyList() : list; - } - } -} diff --git a/openshift/openshift/src/main/resources/META-INF/services/sun.net.spi.nameservice.NameServiceDescriptor b/openshift/openshift/src/main/resources/META-INF/services/sun.net.spi.nameservice.NameServiceDescriptor deleted file mode 100644 index 75d094b2e..000000000 --- a/openshift/openshift/src/main/resources/META-INF/services/sun.net.spi.nameservice.NameServiceDescriptor +++ /dev/null @@ -1 +0,0 @@ -org.arquillian.cube.openshift.impl.dns.ArqCubeNameServiceDescriptor diff --git a/openshift/openshift/src/test/java/org/arquillian/cube/openshift/impl/DnsServiceTest.java b/openshift/openshift/src/test/java/org/arquillian/cube/openshift/impl/DnsServiceTest.java index afb3b657c..658eb9cf3 100644 --- a/openshift/openshift/src/test/java/org/arquillian/cube/openshift/impl/DnsServiceTest.java +++ b/openshift/openshift/src/test/java/org/arquillian/cube/openshift/impl/DnsServiceTest.java @@ -4,6 +4,7 @@ import io.fabric8.openshift.api.model.RouteList; import io.fabric8.openshift.api.model.RouteSpec; import org.arquillian.cube.openshift.impl.dns.ArqCubeNameService; +import org.arquillian.cube.openshift.impl.dns.INameService; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -19,9 +20,8 @@ public class DnsServiceTest { private static String ROUTER_HOST = "127.0.0.1"; @Before - public void prepareEnv(){ - System.setProperty("sun.net.spi.nameservice.provider.1", "dns,ArquillianCubeNameService"); - System.setProperty("sun.net.spi.nameservice.provider.2","default"); + public void prepareEnv() throws NoSuchFieldException, ClassNotFoundException, IllegalAccessException { + INameService.install(new ArqCubeNameService()); } @Test diff --git a/openshift/openshift/src/test/java/org/arquillian/cube/openshift/impl/model/BuildablePodCubeTest.java b/openshift/openshift/src/test/java/org/arquillian/cube/openshift/impl/model/BuildablePodCubeTest.java index cd83c715b..f1d065755 100644 --- a/openshift/openshift/src/test/java/org/arquillian/cube/openshift/impl/model/BuildablePodCubeTest.java +++ b/openshift/openshift/src/test/java/org/arquillian/cube/openshift/impl/model/BuildablePodCubeTest.java @@ -3,10 +3,10 @@ import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.PodSpec; +import io.fabric8.kubernetes.client.dsl.MixedOperation; +import io.fabric8.kubernetes.client.dsl.Resource; +import io.fabric8.openshift.api.model.Route; import io.fabric8.openshift.api.model.RouteList; -/** rls TODO -import io.fabric8.openshift.client.dsl.internal.RouteOperationsImpl; -**/ import org.arquillian.cube.openshift.impl.client.CubeOpenShiftConfiguration; import org.arquillian.cube.openshift.impl.client.OpenShiftClient; import org.arquillian.cube.spi.event.lifecycle.AfterCreate; @@ -24,13 +24,11 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.arquillian.cube.openshift.impl.client.OpenShiftClient.ResourceHolder; -/** rls TODO -import static org.mockito.Matchers.anyObject; -**/ import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) @@ -44,22 +42,21 @@ public class BuildablePodCubeTest extends AbstractManagerTestBase { @Mock private io.fabric8.openshift.client.OpenShiftClient openShiftClientExt; - /** rls TODO + @Mock - private RouteOperationsImpl routeOperations; - **/ + private MixedOperation> routeOperations; + @Inject private Instance injectorInst; private BuildablePodCube buildablePodCube; - /** rls TODO https://github.com/arquillian/arquillian-cube/issues/1292 @Before public void setup() throws Exception { final Pod pod = new Pod("v1", "Pod", new ObjectMeta(), new PodSpec(), null); final ResourceHolder resourceHolder = new ResourceHolder(pod); - when(openShiftClient.build(anyObject())).thenReturn(resourceHolder); + when(openShiftClient.build(ArgumentMatchers.any())).thenReturn(resourceHolder); when(openShiftClient.getClientExt()).thenReturn(openShiftClientExt); when(openShiftClientExt.routes()).thenReturn(routeOperations); @@ -142,6 +139,5 @@ public void shouldNotFireLifecycleEventsIfTryingToStopAlreadyStoppedCube() { assertEventFired(BeforeStop.class, 1); assertEventFired(AfterStop.class, 1); } - **/ } diff --git a/openshift/openshift/src/test/resources/services/sun.net.spi.nameservice.NameServiceDescriptor b/openshift/openshift/src/test/resources/services/sun.net.spi.nameservice.NameServiceDescriptor deleted file mode 100644 index 75d094b2e..000000000 --- a/openshift/openshift/src/test/resources/services/sun.net.spi.nameservice.NameServiceDescriptor +++ /dev/null @@ -1 +0,0 @@ -org.arquillian.cube.openshift.impl.dns.ArqCubeNameServiceDescriptor diff --git a/pom.xml b/pom.xml index 6f51f7d48..3b82c13ea 100644 --- a/pom.xml +++ b/pom.xml @@ -71,7 +71,7 @@ 4.13.2 2.2 3.3.4 - 5.12.4 + 6.9.2 2.2 3.2.1 1.2.6 @@ -87,14 +87,13 @@ 1.19.0 1.7.0.Final 2.16.0 - 4.12.0 + 1.11 1.7.2 3.1.13 - 1.7.7.1 - 4.2.0 + 4.0.1 5.10.1 @@ -249,11 +248,6 @@ ${version.jgit} provided - - com.squareup.okhttp3 - okhttp - ${version.ok-http-client} - io.github.lukehutch fast-classpath-scanner @@ -341,12 +335,12 @@ mockito-core ${version.mockito} test - - - org.hamcrest - hamcrest-core - - + + + + + + org.assertj @@ -376,14 +370,14 @@ ${version.kubernetes_client} - me.snowdrop - istio-client-uberjar - ${version.istio} + io.fabric8 + istio-client + ${version.kubernetes_client} io.fabric8 - mockwebserver - ${version.fabric8_mockwebserver} + kubernetes-server-mock + ${version.kubernetes_client} test @@ -432,7 +426,7 @@ org.hamcrest - hamcrest-library + hamcrest ${version.hamcrest} test @@ -452,7 +446,16 @@ io.fabric8 kubernetes-client-api ${version.kubernetes_client} - test + + + io.fabric8 + openshift-client-api + ${version.kubernetes_client} + + + io.fabric8 + kubernetes-httpclient-jdk + ${version.kubernetes_client} @@ -461,17 +464,6 @@ maven-surefire-plugin - - - - - org.apache.maven.surefire - surefire-api - 3.2.2 - - maven-failsafe-plugin