io.fabric8.kubernetes.client.DefaultKubernetesClient Java Examples

The following examples show how to use io.fabric8.kubernetes.client.DefaultKubernetesClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PlatformFeaturesAvailabilityTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testVersionDetectionOpenShift39(VertxTestContext context) throws InterruptedException {
    String version = "{\n" +
            "  \"major\": \"1\",\n" +
            "  \"minor\": \"9\",\n" +
            "  \"gitVersion\": \"v1.9.1+a0ce1bc657\",\n" +
            "  \"gitCommit\": \"a0ce1bc\",\n" +
            "  \"gitTreeState\": \"clean\",\n" +
            "  \"buildDate\": \"2018-06-24T01:54:00Z\",\n" +
            "  \"goVersion\": \"go1.9\",\n" +
            "  \"compiler\": \"gc\",\n" +
            "  \"platform\": \"linux/amd64\"\n" +
            "}";

    HttpServer mockHttp = startMockApi(context, version, Collections.EMPTY_LIST);

    KubernetesClient client = new DefaultKubernetesClient("127.0.0.1:" + mockHttp.actualPort());

    Checkpoint a = context.checkpoint();

    PlatformFeaturesAvailability.create(vertx, client).onComplete(context.succeeding(pfa -> context.verify(() -> {
        assertThat("Versions are not equal", pfa.getKubernetesVersion(), is(KubernetesVersion.V1_9));
        stopMockApi(context, mockHttp);
        a.flag();
    })));
}
 
Example #2
Source File: KubernetesSchedulerTests.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 6 votes vote down vote up
@Test
public void testImagePullPolicyDefault() {
	KubernetesSchedulerProperties kubernetesSchedulerProperties = new KubernetesSchedulerProperties();
	if (kubernetesSchedulerProperties.getNamespace() == null) {
		kubernetesSchedulerProperties.setNamespace("default");
	}
	KubernetesClient kubernetesClient = new DefaultKubernetesClient()
			.inNamespace(kubernetesSchedulerProperties.getNamespace());

	KubernetesScheduler kubernetesScheduler = new KubernetesScheduler(kubernetesClient,
			kubernetesSchedulerProperties);

	AppDefinition appDefinition = new AppDefinition(randomName(), getAppProperties());
	ScheduleRequest scheduleRequest = new ScheduleRequest(appDefinition, getSchedulerProperties(),
			getDeploymentProperties(), getCommandLineArgs(), randomName(), testApplication());

	CronJob cronJob = kubernetesScheduler.createCronJob(scheduleRequest);
	CronJobSpec cronJobSpec = cronJob.getSpec();

	Container container = cronJobSpec.getJobTemplate().getSpec().getTemplate().getSpec().getContainers().get(0);

	assertEquals("Unexpected default image pull policy", ImagePullPolicy.IfNotPresent,
			ImagePullPolicy.relaxedValueOf(container.getImagePullPolicy()));

	kubernetesScheduler.unschedule(cronJob.getMetadata().getName());
}
 
Example #3
Source File: PlatformFeaturesAvailabilityTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testApiDetectionOpenshift(VertxTestContext context) throws InterruptedException {
    List<String> apis = new ArrayList<>();
    apis.add("/apis/route.openshift.io/v1");
    apis.add("/apis/build.openshift.io/v1");
    apis.add("/apis/apps.openshift.io/v1");
    apis.add("/apis/image.openshift.io/v1");

    HttpServer mockHttp = startMockApi(context, apis);

    KubernetesClient client = new DefaultKubernetesClient("127.0.0.1:" + mockHttp.actualPort());

    Checkpoint async = context.checkpoint();

    PlatformFeaturesAvailability.create(vertx, client).onComplete(context.succeeding(pfa -> context.verify(() -> {
        assertThat(pfa.hasRoutes(), is(true));
        assertThat(pfa.hasBuilds(), is(true));
        assertThat(pfa.hasImages(), is(true));
        assertThat(pfa.hasApps(), is(true));
        stopMockApi(context, mockHttp);
        async.flag();
    })));
}
 
Example #4
Source File: PlatformFeaturesAvailabilityTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testApiDetectionKubernetes(VertxTestContext context) throws InterruptedException {
    HttpServer mockHttp = startMockApi(context, Collections.EMPTY_LIST);

    KubernetesClient client = new DefaultKubernetesClient("127.0.0.1:" + mockHttp.actualPort());

    Checkpoint async = context.checkpoint();

    PlatformFeaturesAvailability.create(vertx, client).onComplete(context.succeeding(pfa -> context.verify(() -> {
        assertThat(pfa.hasRoutes(), is(false));
        assertThat(pfa.hasBuilds(), is(false));
        assertThat(pfa.hasImages(), is(false));
        assertThat(pfa.hasApps(), is(false));
        stopMockApi(context, mockHttp);
        async.flag();
    })));
}
 
Example #5
Source File: KubernetesSchedulerTests.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 6 votes vote down vote up
@Test
public void testImagePullSecretDefault() {
	KubernetesSchedulerProperties kubernetesSchedulerProperties = new KubernetesSchedulerProperties();
	if (kubernetesSchedulerProperties.getNamespace() == null) {
		kubernetesSchedulerProperties.setNamespace("default");
	}
	KubernetesClient kubernetesClient = new DefaultKubernetesClient()
			.inNamespace(kubernetesSchedulerProperties.getNamespace());

	KubernetesScheduler kubernetesScheduler = new KubernetesScheduler(kubernetesClient,
			kubernetesSchedulerProperties);

	AppDefinition appDefinition = new AppDefinition(randomName(), getAppProperties());
	ScheduleRequest scheduleRequest = new ScheduleRequest(appDefinition, getSchedulerProperties(),
			getDeploymentProperties(), getCommandLineArgs(), randomName(), testApplication());

	CronJob cronJob = kubernetesScheduler.createCronJob(scheduleRequest);
	CronJobSpec cronJobSpec = cronJob.getSpec();

	List<LocalObjectReference> secrets = cronJobSpec.getJobTemplate().getSpec().getTemplate().getSpec()
			.getImagePullSecrets();
	assertTrue("There should be no secrets", secrets.isEmpty());

	kubernetesScheduler.unschedule(cronJob.getMetadata().getName());
}
 
Example #6
Source File: KubernetesSchedulerTests.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 6 votes vote down vote up
private void testEnvironmentVariables(KubernetesSchedulerProperties kubernetesSchedulerProperties,
		Map<String, String> schedulerProperties, EnvVar[] expectedVars) {
	if (kubernetesSchedulerProperties.getNamespace() == null) {
		kubernetesSchedulerProperties.setNamespace("default");
	}
	KubernetesClient kubernetesClient = new DefaultKubernetesClient()
			.inNamespace(kubernetesSchedulerProperties.getNamespace());

	KubernetesScheduler kubernetesScheduler = new KubernetesScheduler(kubernetesClient,
			kubernetesSchedulerProperties);

	AppDefinition appDefinition = new AppDefinition(randomName(), getAppProperties());
	ScheduleRequest scheduleRequest = new ScheduleRequest(appDefinition, schedulerProperties,
			null, getCommandLineArgs(), randomName(), testApplication());

	CronJob cronJob = kubernetesScheduler.createCronJob(scheduleRequest);
	CronJobSpec cronJobSpec = cronJob.getSpec();

	Container container = cronJobSpec.getJobTemplate().getSpec().getTemplate().getSpec().getContainers().get(0);

	assertTrue("Environment variables should not be empty", !container.getEnv().isEmpty());

	assertThat(container.getEnv()).contains(expectedVars);

	kubernetesScheduler.unschedule(cronJob.getMetadata().getName());
}
 
Example #7
Source File: PodMetricsReaderTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test @Ignore
public void readTest() {
    String podName = "dbtest1-2-3nvf3";
    String integration = "DBTest1";
    String integrationId = "-L5ApZneYNfmLWG-PKQt";
    String version = "1";
    PodMetricsReader reader = new PodMetricsReader(
            new DefaultKubernetesClient(),
            podName,
            integration,
            integrationId,
            version,
            new LogRawMetrics());
    reader.run();

}
 
Example #8
Source File: AbstractResourceOperatorIT.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@BeforeAll
public static void before() {
    cluster = KubeClusterResource.getInstance();
    cluster.setTestNamespace(namespace);

    assertDoesNotThrow(() -> KubeCluster.bootstrap(), "Could not bootstrap server");
    vertx = Vertx.vertx();
    client = new DefaultKubernetesClient();

    if (cluster.getTestNamespace() != null && System.getenv("SKIP_TEARDOWN") == null) {
        log.warn("Namespace {} is already created, going to delete it", namespace);
        kubeClient().deleteNamespace(namespace);
        cmdKubeClient().waitForResourceDeletion("Namespace", namespace);
    }

    log.info("Creating namespace: {}", namespace);
    kubeClient().createNamespace(namespace);
    cmdKubeClient().waitForResourceCreation("Namespace", namespace);
}
 
Example #9
Source File: Sample4Test.java    From module-ballerina-kubernetes with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void compileSample() throws IOException, InterruptedException {
    Assert.assertEquals(KubernetesTestUtils.compileBallerinaFile(SOURCE_DIR_PATH, "hello_world_ssl_k8s.bal"), 0);
    File artifactYaml = KUBERNETES_TARGET_PATH.resolve("hello_world_ssl_k8s.yaml").toFile();
    Assert.assertTrue(artifactYaml.exists());
    KubernetesClient client = new DefaultKubernetesClient();
    List<HasMetadata> k8sItems = client.load(new FileInputStream(artifactYaml)).get();
    for (HasMetadata data : k8sItems) {
        switch (data.getKind()) {
            case "Deployment":
                deployment = (Deployment) data;
                break;
            case "Secret":
                secret = (Secret) data;
                break;
            case "Ingress":
                ingress = (Ingress) data;
                break;
            case "Service":
                break;
            default:
                Assert.fail("Unexpected k8s resource found: " + data.getKind());
                break;
        }
    }
}
 
Example #10
Source File: Sample1Test.java    From module-ballerina-kubernetes with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void compileSample() throws IOException, InterruptedException {
    Assert.assertEquals(KubernetesTestUtils.compileBallerinaFile(SOURCE_DIR_PATH, "hello_world_k8s.bal"), 0);
    File artifactYaml = KUBERNETES_TARGET_PATH.resolve("hello_world_k8s.yaml").toFile();
    Assert.assertTrue(artifactYaml.exists());
    KubernetesClient client = new DefaultKubernetesClient();
    List<HasMetadata> k8sItems = client.load(new FileInputStream(artifactYaml)).get();
    for (HasMetadata data : k8sItems) {
        switch (data.getKind()) {
            case "Deployment":
                deployment = (Deployment) data;
                break;
            case "Service":
                service = (Service) data;
                break;
            default:
                Assert.fail("Unexpected k8s resource found: " + data.getKind());
                break;
        }
    }
}
 
Example #11
Source File: KubernetesSchedulerTests.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 6 votes vote down vote up
@AfterClass
public static void cleanup() {
	KubernetesSchedulerProperties kubernetesSchedulerProperties = new KubernetesSchedulerProperties();
	kubernetesSchedulerProperties.setNamespace("default");

	KubernetesClient kubernetesClient = new DefaultKubernetesClient()
			.inNamespace(kubernetesSchedulerProperties.getNamespace());

	KubernetesScheduler kubernetesScheduler = new KubernetesScheduler(kubernetesClient,
			kubernetesSchedulerProperties);

	List<ScheduleInfo> scheduleInfos = kubernetesScheduler.list();

	for (ScheduleInfo scheduleInfo : scheduleInfos) {
		kubernetesScheduler.unschedule(scheduleInfo.getScheduleName());
	}
	// Cleanup the schedules that aren't part of the list() - created from listScheduleWithExternalCronJobs test
	kubernetesScheduler.unschedule("job2");
	kubernetesScheduler.unschedule("job3");
}
 
Example #12
Source File: Sample5Test.java    From module-ballerina-kubernetes with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void compileSample() throws IOException, InterruptedException {
    Assert.assertEquals(KubernetesTestUtils.compileBallerinaFile(SOURCE_DIR_PATH, "pizzashack.bal"), 0);
    File artifactYaml = KUBERNETES_TARGET_PATH.resolve("pizzashack.yaml").toFile();
    Assert.assertTrue(artifactYaml.exists());
    KubernetesClient client = new DefaultKubernetesClient();
    List<HasMetadata> k8sItems = client.load(new FileInputStream(artifactYaml)).get();
    for (HasMetadata data : k8sItems) {
        switch (data.getKind()) {
            case "HorizontalPodAutoscaler":
                podAutoscaler = (HorizontalPodAutoscaler) data;
                break;
            case "Service":
            case "Ingress":
            case "Secret":
            case "Deployment":
                break;
            default:
                Assert.fail("Unexpected k8s resource found: " + data.getKind());
                break;
        }
    }
}
 
Example #13
Source File: PlatformFeaturesAvailabilityTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testVersionDetectionMinikube114(VertxTestContext context) throws InterruptedException {
    String version = "{\n" +
            "  \"major\": \"1\",\n" +
            "  \"minor\": \"14\",\n" +
            "  \"gitVersion\": \"v1.14.0\",\n" +
            "  \"gitCommit\": \"641856db18352033a0d96dbc99153fa3b27298e5\",\n" +
            "  \"gitTreeState\": \"clean\",\n" +
            "  \"buildDate\": \"2019-03-25T15:45:25Z\",\n" +
            "  \"goVersion\": \"go1.12.1\",\n" +
            "  \"compiler\": \"gc\",\n" +
            "  \"platform\": \"linux/amd64\"\n" +
            "}";

    HttpServer mockHttp = startMockApi(context, version, Collections.EMPTY_LIST);

    KubernetesClient client = new DefaultKubernetesClient("127.0.0.1:" + mockHttp.actualPort());

    Checkpoint async = context.checkpoint();

    PlatformFeaturesAvailability.create(vertx, client).onComplete(context.succeeding(pfa -> context.verify(() -> {
        assertThat("Versions are not equal", pfa.getKubernetesVersion(), is(KubernetesVersion.V1_14));
        stopMockApi(context, mockHttp);
        async.flag();
    })));
}
 
Example #14
Source File: Sample12Test.java    From module-ballerina-kubernetes with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void compileSample() throws IOException, InterruptedException {
    Assert.assertEquals(KubernetesTestUtils.compileBallerinaFile(SOURCE_DIR_PATH, "hello_world_copy_file.bal"), 0);
    File artifactYaml = KUBERNETES_TARGET_PATH.resolve("hello_world_copy_file.yaml").toFile();
    Assert.assertTrue(artifactYaml.exists());
    KubernetesClient client = new DefaultKubernetesClient();
    List<HasMetadata> k8sItems = client.load(new FileInputStream(artifactYaml)).get();
    for (HasMetadata data : k8sItems) {
        switch (data.getKind()) {
            case "Deployment":
                deployment = (Deployment) data;
                break;
            case "Service":
            case "Ingress":
            case "Secret":
                break;
            default:
                Assert.fail("Unexpected k8s resource found: " + data.getKind());
                break;
        }
    }
}
 
Example #15
Source File: Main.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

        log.info("Init-kafka {} is starting", Main.class.getPackage().getImplementationVersion());
        InitWriterConfig config = InitWriterConfig.fromMap(System.getenv());

        // Workaround for https://github.com/fabric8io/kubernetes-client/issues/2212
        // Can be removed after upgrade to Fabric8 4.10.2 or higher or to Java 11
        if (Util.shouldDisableHttp2()) {
            System.setProperty("http2.disable", "true");
        }

        KubernetesClient client = new DefaultKubernetesClient();

        log.info("Init-kafka started with config: {}", config);

        InitWriter writer = new InitWriter(client, config);

        if (config.getRackTopologyKey() != null) {
            if (!writer.writeRack()) {
                System.exit(1);
            }
        }

        if (config.isExternalAddress()) {
            if (!writer.writeExternalAddress()) {
                System.exit(1);
            }
        }

        client.close();
    }
 
Example #16
Source File: KubernetesServiceTest.java    From vault-crd with Apache License 2.0 5 votes vote down vote up
@Bean
@Primary
public KubernetesClient client() {
    KubernetesClient kubernetesClient = new DefaultKubernetesClient();
    TestHelper.createCrd(kubernetesClient);

    return kubernetesClient;
}
 
Example #17
Source File: KubernetesClientFactory.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 5 votes vote down vote up
public static KubernetesClient getKubernetesClient(KubernetesDeployerProperties kubernetesDeployerProperties) {
	Config config = kubernetesDeployerProperties.getFabric8();

	// use any fabric8 auto-detected properties, only set namespace from deployer properties if not null
	if (kubernetesDeployerProperties.getNamespace() != null) {
		config.setNamespace(kubernetesDeployerProperties.getNamespace());
	}

	return new DefaultKubernetesClient(config);
}
 
Example #18
Source File: KubernetesSchedulerTests.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithShellEntryPoint() {
	KubernetesSchedulerProperties kubernetesSchedulerProperties = new KubernetesSchedulerProperties();
	if (kubernetesSchedulerProperties.getNamespace() == null) {
		kubernetesSchedulerProperties.setNamespace("default");
	}
	kubernetesSchedulerProperties.setEntryPointStyle(EntryPointStyle.shell);

	KubernetesClient kubernetesClient = new DefaultKubernetesClient()
			.inNamespace(kubernetesSchedulerProperties.getNamespace());

	KubernetesScheduler kubernetesScheduler = new KubernetesScheduler(kubernetesClient,
			kubernetesSchedulerProperties);

	AppDefinition appDefinition = new AppDefinition(randomName(), getAppProperties());
	ScheduleRequest scheduleRequest = new ScheduleRequest(appDefinition, getSchedulerProperties(), null,
			getCommandLineArgs(), randomName(), testApplication());

	CronJob cronJob = kubernetesScheduler.createCronJob(scheduleRequest);
	CronJobSpec cronJobSpec = cronJob.getSpec();

	Container container = cronJobSpec.getJobTemplate().getSpec().getTemplate().getSpec().getContainers().get(0);

	assertNotNull("Command line arguments should not be null", container.getArgs());
	assertEquals("Invalid number of command line arguments", 0, container.getArgs().size());

	assertNotNull("Environment variables should not be null", container.getEnv());
	assertTrue("Invalid number of environment variables", container.getEnv().size() > 1);

	kubernetesScheduler.unschedule(cronJob.getMetadata().getName());
}
 
Example #19
Source File: Minikube.java    From enmasse with Apache License 2.0 5 votes vote down vote up
protected Minikube(Environment environment) {
    super(environment, () -> {
        Config config = new ConfigBuilder().build();
        OkHttpClient httpClient = HttpClientUtils.createHttpClient(config);
        // Workaround https://github.com/square/okhttp/issues/3146
        httpClient = httpClient.newBuilder()
                .protocols(Collections.singletonList(Protocol.HTTP_1_1))
                .connectTimeout(environment.getKubernetesApiConnectTimeout())
                .writeTimeout(environment.getKubernetesApiWriteTimeout())
                .readTimeout(environment.getKubernetesApiReadTimeout())
                .build();
        return new DefaultKubernetesClient(httpClient, config);
    });
}
 
Example #20
Source File: NoAnnotationsTest.java    From module-ballerina-kubernetes with Apache License 2.0 5 votes vote down vote up
@Test(timeOut = 90000)
public void mainWithNoAnnotationTest() throws IOException, InterruptedException, DockerTestException,
        KubernetesPluginException {
    Assert.assertEquals(KubernetesTestUtils.compileBallerinaFile(BAL_DIRECTORY, "no_annotations_main.bal"), 0);
    File yamlFile = KUBERNETES_TARGET_PATH.resolve("no_annotations_main.yaml").toFile();
    Assert.assertTrue(yamlFile.exists());
    KubernetesClient client = new DefaultKubernetesClient();
    List<HasMetadata> k8sItems = client.load(new FileInputStream(yamlFile)).get();
    for (HasMetadata data : k8sItems) {
        if ("Job".equals(data.getKind())) {
            Job job = (Job) data;
            Assert.assertEquals(job.getMetadata().getName(), "no-annotations-main-job");
            Assert.assertEquals(job.getSpec().getTemplate().getSpec().getContainers().size(), 1);

            Container container = job.getSpec().getTemplate().getSpec().getContainers().get(0);
            Assert.assertEquals(container.getImage(), "no_annotations_main:latest");
            Assert.assertEquals(container.getImagePullPolicy(),
                    KubernetesConstants.ImagePullPolicy.IfNotPresent.name());
            Assert.assertEquals(job.getSpec().getTemplate().getSpec()
                    .getRestartPolicy(), KubernetesConstants.RestartPolicy.Never.name());
        }
    }
    
    validateDockerfile();
    
    KubernetesUtils.deleteDirectory(KUBERNETES_TARGET_PATH);
    KubernetesUtils.deleteDirectory(DOCKER_TARGET_PATH);
    KubernetesTestUtils.deleteDockerImage("no_annotations_main:latest");
}
 
Example #21
Source File: TestCharts.java    From microbean-helm with Apache License 2.0 5 votes vote down vote up
@Test
public void testRoundTrip() throws ExecutionException, IOException, InterruptedException {
  assumeFalse(Boolean.getBoolean("skipClusterTests"));
  try (final DefaultKubernetesClient client = new DefaultKubernetesClient();
       final Tiller tiller = new Tiller(client);
       final org.microbean.helm.ReleaseManager chartManager = new org.microbean.helm.ReleaseManager(tiller)) {
    final InstallReleaseRequest.Builder requestBuilder = InstallReleaseRequest.newBuilder();
    assertNotNull(requestBuilder);
    requestBuilder.setTimeout(300L);
    requestBuilder.setName("test-charts");
    requestBuilder.setWait(true);

    Chart.Builder chartBuilder = null;
    try (final AbstractChartLoader<URL> loader = new URLChartLoader()) {
      chartBuilder = loader.load(this.redisUrl);
    }
    assertNotNull(chartBuilder);
    
    final Future<InstallReleaseResponse> releaseFuture = chartManager.install(requestBuilder, chartBuilder);
    assertNotNull(releaseFuture);
    final Release release = releaseFuture.get().getRelease();
    assertNotNull(release);
    assertNotNull(release.getName());
    assertTrue(release.hasChart());
    assertTrue(release.hasConfig());

    final UninstallReleaseRequest.Builder uninstallRequestBuilder = UninstallReleaseRequest.newBuilder();
    assertNotNull(uninstallRequestBuilder);
    uninstallRequestBuilder.setTimeout(300L);
    uninstallRequestBuilder.setName("test-charts");
    uninstallRequestBuilder.setPurge(true);

    final Future<UninstallReleaseResponse> uninstallReleaseResponseFuture = chartManager.uninstall(uninstallRequestBuilder.build());
    assertNotNull(uninstallReleaseResponseFuture);
    final UninstallReleaseResponse response = uninstallReleaseResponseFuture.get();
    assertNotNull(response);
    assertNotNull(response.getRelease());
  }
}
 
Example #22
Source File: Sample19Test.java    From module-ballerina-kubernetes with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void compileSample() throws IOException, InterruptedException {
    Assert.assertEquals(KnativeTestUtils.compileBallerinaFile(SOURCE_DIR_PATH, "hello_world_knative_config_map.bal")
            , 0);
    File artifactYaml = KUBERNETES_TARGET_PATH.resolve(KNATIVE).resolve("hello_world_knative_config_map.yaml")
            .toFile();
    Assert.assertTrue(artifactYaml.exists());
    Handlers.register(new KnativeTestUtils.ServiceHandler());
    KubernetesClient client = new DefaultKubernetesClient();
    List<HasMetadata> k8sItems = client.load(new FileInputStream(artifactYaml)).get();
    for (HasMetadata data : k8sItems) {
        switch (data.getKind()) {
            case "Service":
                this.knativeService = (Service) data;
                break;
            case "ConfigMap":
                switch (data.getMetadata().getName()) {
                    case "helloworld-ballerina-conf-config-map":
                        this.ballerinaConf = (ConfigMap) data;
                        break;
                    case "helloworld-config-map":
                        this.dataMap = (ConfigMap) data;
                        break;
                    default:
                        break;
                }
                break;
            default:
                Assert.fail("Unexpected k8s resource found: " + data.getKind());
                break;
        }
    }
}
 
Example #23
Source File: ServiceTest.java    From module-ballerina-kubernetes with Apache License 2.0 5 votes vote down vote up
@Test
public void nodePortTest() throws IOException, InterruptedException, KubernetesPluginException,
        DockerTestException {
    Assert.assertEquals(KubernetesTestUtils.compileBallerinaFile(BAL_DIRECTORY, "node_port.bal"), 0);
    File yamlFile = KUBERNETES_TARGET_PATH.resolve("node_port.yaml").toFile();
    Assert.assertTrue(yamlFile.exists());
    KubernetesClient client = new DefaultKubernetesClient();
    List<HasMetadata> k8sItems = client.load(new FileInputStream(yamlFile)).get();
    for (HasMetadata data : k8sItems) {
        if ("Service".equals(data.getKind())) {
            Service service = (Service) data;
            Assert.assertNotNull(service);
            Assert.assertEquals("hello", service.getMetadata().getName());
            Assert.assertEquals("node_port", service.getMetadata().getLabels().get(KubernetesConstants
                    .KUBERNETES_SELECTOR_KEY));
            Assert.assertEquals(KubernetesConstants.ServiceType.NodePort.name(), service.getSpec().getType());
            Assert.assertEquals(1, service.getSpec().getPorts().size());
            Assert.assertEquals(31100, service.getSpec().getPorts().get(0).getNodePort().intValue());
        }
    }

    validateDockerfile();
    validateDockerImage(DOCKER_IMAGE);

    KubernetesUtils.deleteDirectory(KUBERNETES_TARGET_PATH);
    KubernetesUtils.deleteDirectory(DOCKER_TARGET_PATH);
    KubernetesTestUtils.deleteDockerImage(DOCKER_IMAGE);
}
 
Example #24
Source File: PKIChainTest.java    From vault-crd with Apache License 2.0 5 votes vote down vote up
@Bean
@Primary
public KubernetesClient client() {
    KubernetesClient kubernetesClient = new DefaultKubernetesClient();
    TestHelper.createCrd(kubernetesClient);

    return kubernetesClient;
}
 
Example #25
Source File: KubernetesClientFactory.java    From kubernetes-elastic-agents with Apache License 2.0 5 votes vote down vote up
private KubernetesClient createClientFor(PluginSettings pluginSettings) {
    final ConfigBuilder configBuilder = new ConfigBuilder()
            .withOauthToken(pluginSettings.getSecurityToken())
            .withMasterUrl(pluginSettings.getClusterUrl())
            .withCaCertData(pluginSettings.getCaCertData())
            .withNamespace(pluginSettings.getNamespace());

    return new DefaultKubernetesClient(configBuilder.build());
}
 
Example #26
Source File: MySQLSchemaOperator.java    From java-operator-sdk with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    log.info("MySQL Schema Operator starting");

    Config config = new ConfigBuilder().withNamespace(null).build();
    KubernetesClient client = new DefaultKubernetesClient(config);
    Operator operator = new Operator(client);
    operator.registerControllerForAllNamespaces(new SchemaController(client));

    new FtBasic(
            new TkFork(new FkRegex("/health", "ALL GOOD!")), 8080
    ).start(Exit.NEVER);
}
 
Example #27
Source File: Sample11Test.java    From module-ballerina-kubernetes with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void compileSample() throws IOException, InterruptedException {
    Assert.assertEquals(KubernetesTestUtils.compileBallerinaFile(SOURCE_DIR_PATH, "hello_world_job.bal"), 0);
    File artifactYaml = KUBERNETES_TARGET_PATH.resolve("hello_world_job.yaml").toFile();
    Assert.assertTrue(artifactYaml.exists());
    KubernetesClient client = new DefaultKubernetesClient();
    List<HasMetadata> k8sItems = client.load(new FileInputStream(artifactYaml)).get();
    for (HasMetadata data : k8sItems) {
        if ("Job".equals(data.getKind())) {
            job = (Job) data;
        } else {
            Assert.fail("Unexpected k8s resource found: " + data.getKind());
        }
    }
}
 
Example #28
Source File: WebServerOperator.java    From java-operator-sdk with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    log.info("WebServer Operator starting!");

    Config config = new ConfigBuilder().withNamespace(null).build();
    KubernetesClient client = new DefaultKubernetesClient(config);
    Operator operator = new Operator(client);
    operator.registerControllerForAllNamespaces(new WebServerController(client));

    new FtBasic(
            new TkFork(new FkRegex("/health", "ALL GOOD!")), 8080
    ).start(Exit.NEVER);
}
 
Example #29
Source File: DeviceRegistryTokenAuthProvider.java    From enmasse with Apache License 2.0 5 votes vote down vote up
public DeviceRegistryTokenAuthProvider(final Tracer tracer, final Duration tokenExpiration) {
    log.info("Using token cache expiration of {}", tokenExpiration);
    this.tracer = tracer;
    this.client = new DefaultKubernetesClient();
    this.authApi = new KubeAuthApi(this.client, this.client.getConfiguration().getOauthToken());
    final ConfigurationBuilder config = new ConfigurationBuilder();
    config.expiration().lifespan(tokenExpiration.toSeconds(), TimeUnit.SECONDS);
    this.cacheManager.defineConfiguration("tokens", config.build());
    this.cacheManager.defineConfiguration("subjects", config.build());
    this.tokens = cacheManager.getCache("tokens");
    this.authorizations = cacheManager.getCache("subjects");

}
 
Example #30
Source File: Sample8Test.java    From module-ballerina-kubernetes with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void compileSample() throws IOException, InterruptedException {
    Assert.assertEquals(KubernetesTestUtils.compileBallerinaFile(SOURCE_DIR_PATH, "hello_world_config_map_k8s.bal")
            , 0);
    File artifactYaml = KUBERNETES_TARGET_PATH.resolve("hello_world_config_map_k8s.yaml").toFile();
    Assert.assertTrue(artifactYaml.exists());
    KubernetesClient client = new DefaultKubernetesClient();
    List<HasMetadata> k8sItems = client.load(new FileInputStream(artifactYaml)).get();
    for (HasMetadata data : k8sItems) {
        switch (data.getKind()) {
            case "Deployment":
                deployment = (Deployment) data;
                break;
            case "ConfigMap":
                switch (data.getMetadata().getName()) {
                    case "helloworld-ballerina-conf-config-map":
                        ballerinaConf = (ConfigMap) data;
                        break;
                    case "helloworld-config-map":
                        dataMap = (ConfigMap) data;
                        break;
                    default:
                        break;
                }
                break;
            case "Service":
            case "Secret":
            case "Ingress":
                break;
            default:
                Assert.fail("Unexpected k8s resource found: " + data.getKind());
                break;
        }
    }
}