Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ballerina/Dependencies.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

[ballerina]
dependencies-toml-version = "2"
distribution-version = "2201.12.0"
distribution-version = "2201.13.0-m2"

[[package]]
org = "ballerina"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
/*
* Copyright (c) 2025, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package io.ballerina.c2c.test.samples;

import io.ballerina.c2c.KubernetesConstants;
import io.ballerina.c2c.exceptions.KubernetesPluginException;
import io.ballerina.c2c.test.utils.KubernetesTestUtils;
import io.ballerina.c2c.utils.KubernetesUtils;
import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.apps.Deployment;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientBuilder;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import static io.ballerina.c2c.KubernetesConstants.DOCKER;
import static io.ballerina.c2c.KubernetesConstants.OPENSHIFT;
import static io.ballerina.c2c.test.utils.KubernetesTestUtils.deployK8s;
import static io.ballerina.c2c.test.utils.KubernetesTestUtils.getEntryPoint;
import static io.ballerina.c2c.test.utils.KubernetesTestUtils.getExposedPorts;
import static io.ballerina.c2c.test.utils.KubernetesTestUtils.loadImage;

/**
* Test cases for openshift sample.
*/
public class OpenshiftSampleTest extends SampleTest {

private static final Path SOURCE_DIR_PATH = SAMPLE_DIR.resolve("openshift-yaml-with-ballerina-project");
private static final Path DOCKER_TARGET_PATH =
SOURCE_DIR_PATH.resolve("target").resolve(DOCKER).resolve("hello");
private static final Path OPENSHIFT_TARGET_PATH =
SOURCE_DIR_PATH.resolve("target").resolve(OPENSHIFT).resolve("hello");
private static final String DOCKER_IMAGE = "anuruddhal/hello-api:1.0.0";
private static final Path INGRESS_PATH =
Paths.get("src", "test", "resources", "openshift-yaml-with-ballerina-project");
private Deployment deployment;
private Service service;

@BeforeClass
public void compileSample() throws IOException, InterruptedException {
Assert.assertEquals(KubernetesTestUtils.compileBallerinaProject(SOURCE_DIR_PATH)
, 0);
File artifactYaml = OPENSHIFT_TARGET_PATH.resolve("hello.yaml").toFile();
Assert.assertTrue(artifactYaml.exists());
KubernetesClient client = new KubernetesClientBuilder().build();
List<HasMetadata> k8sItems = client.load(new FileInputStream(artifactYaml)).items();
for (HasMetadata data : k8sItems) {
switch (data.getKind()) {
case "Deployment":
deployment = (Deployment) data;
break;
case "Service":
service = (Service) data;
break;
case "Secret":
case "HorizontalPodAutoscaler":
break;
default:
Assert.fail("Unexpected k8s resource found: " + data.getKind());
break;
}
}
}

@Test
public void validateDeployment() {
Assert.assertNotNull(deployment);
Assert.assertEquals(deployment.getMetadata().getName(), "hello-deployment");
Assert.assertEquals(deployment.getSpec().getReplicas().intValue(), 1);
Assert.assertEquals(deployment.getMetadata().getLabels().get(KubernetesConstants
.KUBERNETES_SELECTOR_KEY), "hello");
Assert.assertEquals(deployment.getSpec().getTemplate().getSpec().getContainers().size(), 1);

// Assert Containers
Container container = deployment.getSpec().getTemplate().getSpec().getContainers().get(0);
Assert.assertEquals(container.getImage(), DOCKER_IMAGE);
Assert.assertEquals(container.getPorts().size(), 1);
}

@Test
public void validateService() {
Assert.assertNotNull(service);
Assert.assertEquals(1, service.getMetadata().getLabels().size());
Assert.assertEquals("hello-svc", service.getMetadata().getName());
Assert.assertEquals("ClusterIP", service.getSpec().getType());
Assert.assertEquals(1, service.getSpec().getPorts().size());
Assert.assertEquals(9090, service.getSpec().getPorts().get(0).getPort().intValue());
Assert.assertEquals(9090, service.getSpec().getPorts().get(0).getTargetPort().getIntVal().intValue());
Assert.assertEquals("TCP", service.getSpec().getPorts().get(0).getProtocol());
Assert.assertEquals("port-1-hello-sv", service.getSpec().getPorts().get(0).getName());
}

@Test
public void validateDockerfile() {
File dockerFile = DOCKER_TARGET_PATH.resolve("Dockerfile").toFile();
Assert.assertTrue(dockerFile.exists());
}

@Test
public void validateDockerImage() {
List<String> ports = getExposedPorts(DOCKER_IMAGE);
Assert.assertEquals(ports.size(), 1);
Assert.assertEquals(ports.get(0), "9090/tcp");
// Validate ballerina.conf in run command
Assert.assertEquals(getEntryPoint(DOCKER_IMAGE).toString(), "[java, -Xdiag, -cp, " +
"hello-hello-0.0.1.jar:jars/*, hello.hello.0.$_init]");
}

@Test(groups = {"integration"})
public void deploySample() throws IOException, InterruptedException {
Assert.assertEquals(0, loadImage(DOCKER_IMAGE));
Assert.assertEquals(0, deployK8s(OPENSHIFT_TARGET_PATH));
Assert.assertEquals(0, deployK8s(INGRESS_PATH));
Assert.assertTrue(KubernetesTestUtils.validateService(
"http://c2c.deployment.test/helloWorld/sayHello",
"Hello, World from service helloWorld ! \n"));
KubernetesTestUtils.deleteK8s(OPENSHIFT_TARGET_PATH);
KubernetesTestUtils.deleteK8s(INGRESS_PATH);
}

@AfterClass
public void cleanUp() throws KubernetesPluginException, IOException, InterruptedException {
KubernetesUtils.deleteDirectory(OPENSHIFT_TARGET_PATH);
KubernetesUtils.deleteDirectory(DOCKER_TARGET_PATH);
KubernetesTestUtils.deleteDockerImage(DOCKER_IMAGE);
}
}
1 change: 1 addition & 0 deletions compiler-plugin-tests/src/test/resources/testng.xml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
<class name="io.ballerina.c2c.test.docker.DockerInvalidCopyTest"/>
<class name="io.ballerina.c2c.test.docker.BalTestCMDOptionsTests"/>
<class name="io.ballerina.c2c.test.samples.JobTest"/>
<class name="io.ballerina.c2c.test.samples.OpenshiftSampleTest"/>
<class name="io.ballerina.c2c.test.samples.Sample1Test"/>
<class name="io.ballerina.c2c.test.samples.Sample2Test"/>
<class name="io.ballerina.c2c.test.samples.Sample3Test"/>
Expand Down
1 change: 1 addition & 0 deletions compiler-plugin/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ dependencies {
implementation group: 'io.fabric8', name: 'kubernetes-model-apps', version: "${fabric8KubernetesClientVersion}"
implementation group: 'io.fabric8', name: 'kubernetes-model-autoscaling', version: "${fabric8KubernetesClientVersion}"
implementation group: 'io.fabric8', name: 'kubernetes-model-batch', version: "${fabric8KubernetesClientVersion}"
implementation group: 'io.fabric8', name: 'openshift-client', version: "${fabric8KubernetesClientVersion}"

implementation group: 'org.ballerinalang', name: 'ballerina-cli', version: "${ballerinaLangVersion}"
implementation group: 'org.ballerinalang', name: 'ballerina-lang', version: "${ballerinaLangVersion}"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

package io.ballerina.c2c;

import io.ballerina.c2c.diagnostics.NullLocation;
import io.ballerina.c2c.exceptions.KubernetesPluginException;
import io.ballerina.c2c.handlers.ChoreoHandler;
import io.ballerina.c2c.handlers.ConfigMapHandler;
Expand All @@ -32,7 +33,9 @@
import io.ballerina.c2c.models.KubernetesContext;
import io.ballerina.c2c.models.KubernetesDataHolder;
import io.ballerina.c2c.models.ServiceModel;
import io.ballerina.c2c.util.C2CDiagnosticCodes;
import io.ballerina.c2c.utils.KubernetesUtils;
import io.ballerina.tools.diagnostics.Diagnostic;
import io.fabric8.kubernetes.api.model.ContainerPort;
import io.fabric8.kubernetes.api.model.ContainerPortBuilder;

Expand Down Expand Up @@ -62,12 +65,16 @@ public ArtifactManager() {
* @throws KubernetesPluginException if an error occurs while generating artifacts
*/
public void createArtifacts(String cloudType, boolean isNative) throws KubernetesPluginException {
if (cloudType.equals("k8s")) {
createKubernetesArtifacts(isNative);
} else if (cloudType.equals("docker")) {
createDockerArtifacts(isNative);
} else {
createChoreoArtifacts(isNative);
switch (cloudType) {
case "k8s" -> createKubernetesArtifacts(isNative);
case "docker" -> createDockerArtifacts(isNative);
case "openshift" -> createOpenshiftArtifacts(isNative);
case "choreo" -> createChoreoArtifacts(isNative);
default -> {
Diagnostic diagnostic = C2CDiagnosticCodes.createDiagnostic(C2CDiagnosticCodes.ARTIFACT_GEN_FAILED,
new NullLocation(), "deployment", cloudType);
throw new KubernetesPluginException(diagnostic);
}
}
}

Expand Down Expand Up @@ -97,6 +104,28 @@ public void createKubernetesArtifacts(boolean isNative) throws KubernetesPluginE
printInstructions();
}

public void createOpenshiftArtifacts(boolean isNative) throws KubernetesPluginException {
// add default kubernetes instructions.
setDefaultOpenshiftInstructions();
kubernetesDataHolder.setK8sArtifactOutputPath(kubernetesDataHolder.getOpenshiftArtifactOutputPath());
OUT.println("\nGenerating artifacts\n");
if (kubernetesDataHolder.getJobModel() != null) {
new CloudTomlResolver().resolveToml(kubernetesDataHolder.getJobModel());
new ConfigMapHandler().createArtifacts();
new SecretHandler().createArtifacts();
new JobHandler().createArtifacts();
} else {
new CloudTomlResolver().resolveToml(kubernetesDataHolder.getDeploymentModel());
new ServiceHandler().createArtifacts();
new ConfigMapHandler().createArtifacts();
new SecretHandler().createArtifacts();
new DeploymentHandler().createArtifacts();
new HPAHandler().createArtifacts();
}
new DockerHandler(isNative).createArtifacts();
printInstructions();
}

public void createDockerArtifacts(boolean isNative) throws KubernetesPluginException {
OUT.println("\nGenerating artifacts\n");
DockerModel dockerModel = getDockerModel(false);
Expand Down Expand Up @@ -191,4 +220,13 @@ private void setDefaultKubernetesInstructions() {
.replace(KubernetesConstants.DEPLOYMENT_POSTFIX, "-svc-local"));
}
}


/**
* Set instructions for openshift artifacts.
*/
private void setDefaultOpenshiftInstructions() {
instructions.put("Execute the below command to deploy the openshift artifacts: ",
"\toc apply -f " + this.kubernetesDataHolder.getOpenshiftArtifactOutputPath().toAbsolutePath());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ public class KubernetesConstants {
public static final String CONFIG_MAP_FILE_POSTFIX = "_config_map";
public static final String VOLUME_CLAIM_FILE_POSTFIX = "_volume_claim";
public static final String HPA_FILE_POSTFIX = "_hpa";
public static final String BUILD_CONFIG_FILE_POSTFIX = "_build_config";
public static final String YAML = ".yaml";
public static final String DOCKER_LATEST_TAG = ":latest";
public static final String BALLERINA_HOME = "/home/ballerina";
Expand All @@ -58,6 +59,7 @@ public class KubernetesConstants {
public static final String CPU = "cpu";
public static final String CHOREO = "choreo";
public static final String K8S = "k8s";
public static final String OPENSHIFT = "openshift";

/**
* Restart policy enum.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
* Copyright (c) 2025, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package io.ballerina.c2c.handlers;

import io.ballerina.c2c.KubernetesConstants;
import io.ballerina.c2c.diagnostics.NullLocation;
import io.ballerina.c2c.exceptions.KubernetesPluginException;
import io.ballerina.c2c.util.C2CDiagnosticCodes;
import io.ballerina.c2c.utils.KubernetesUtils;
import io.ballerina.tools.diagnostics.Diagnostic;
import io.fabric8.openshift.api.model.BuildConfig;
import io.fabric8.openshift.api.model.BuildConfigBuilder;

import java.io.IOException;

/**
* Generates kubernetes deployment from annotations.
*/
public class BuildConfigHandler extends AbstractArtifactHandler {


@Override
public void createArtifacts() throws KubernetesPluginException {
BuildConfig buildConfig = new BuildConfigBuilder()
.withApiVersion("build.openshift.io/v1")
.withKind("BuildConfig")
.withNewMetadata()
.withName("dockerfile-binary-build")
.endMetadata()
.withNewSpec()
.withNewSource()
.withType("Binary")
.endSource()
.withNewStrategy()
.withType("Docker")
.withNewDockerStrategy()
.withNoCache(false)
.endDockerStrategy()
.endStrategy()
.withNewOutput()
.withNewTo()
.withKind("ImageStreamTag")
.withName("dockerfile-app:latest")
.endTo()
.endOutput()
.endSpec()
.build();
String outputFileName = KubernetesConstants.BUILD_CONFIG_FILE_POSTFIX + KubernetesConstants.YAML;
try {
String buildConfigYAML = KubernetesUtils.asYaml(buildConfig);
if (dataHolder.isSingleYaml()) {
outputFileName = buildConfig.getMetadata().getName() + KubernetesConstants.YAML;
}
OUT.println("\t@openshift:BuildConfig");
KubernetesUtils.writeToFile(dataHolder.getOpenshiftArtifactOutputPath(), buildConfigYAML, outputFileName);
} catch (IOException e) {
Diagnostic diagnostic = C2CDiagnosticCodes.createDiagnostic(C2CDiagnosticCodes.ARTIFACT_GEN_FAILED,
new NullLocation(), "buildConfig", outputFileName);
throw new KubernetesPluginException(diagnostic);
}
}

}

Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ public class KubernetesDataHolder {
private Path k8sArtifactOutputPath;
private Path dockerArtifactOutputPath;
private Path choreoArtifactOutputPath;
private Path openshiftArtifactOutputPath;
private String namespace;
private Path sourceRoot;
private PackageID packageID;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public void perform(CompilationAnalysisContext compilationAnalysisContext) {
Package currentPackage = compilationAnalysisContext.currentPackage();
final Project project = compilationAnalysisContext.currentPackage().project();
String cloud = project.buildOptions().cloud();
if (cloud == null || !KubernetesUtils.isBuildOptionDockerOrK8s(cloud)) {
if (cloud == null || !KubernetesUtils.isValidBuildOption(cloud)) {
return;
}
KubernetesContext.getInstance().setCurrentPackage(KubernetesUtils.getProjectID(currentPackage));
Expand Down
Loading