FunTester Fabric8 Kubernetes 教程——OpenShift 客户端

FunTester · 2025年04月05日 · 64 次阅读

OpenShift 客户端(oc)是 Red Hat 推出的开源容器平台 OpenShift 的命令行工具,用于与 OpenShift 集群交互。通过 oc,开发者可以高效管理应用全生命周期——包括部署、扩展、监控及调试容器化应用。它支持 Kubernetes 原生操作,同时扩展了 OpenShift 特有功能(如构建镜像、触发部署)。

Fabric8 Kubernetes 客户端提供了一个 OpenShift 扩展,支持 OpenShift 特有的资源。以下是 OpenShift 客户端 DSL 的使用示例。

1. 初始化 OpenShift 客户端

默认初始化:

try (OpenShiftClient client = new KubernetesClientBuilder().build().adapt(OpenShiftClient.class)) {
    // 使用客户端进行操作
}

自定义配置初始化:

Config kubeConfig = new ConfigBuilder()
    .withMasterUrl("https://api.ci-ln-3sbdl1b-d5d6b.origin-ci-int-aws.dev.FunTestercloud.com:6443")
    .withOauthToken("xxxxxxxx-41FunTesteroafKI6iU637-xxxxxxxxxxxxx")
    .build();

try (OpenShiftClient client = new KubernetesClientBuilder().withConfig(kubeConfig).build().adapt(OpenShiftClient.class)) {
    // 使用客户端进行操作
}

2. DeploymentConfig

从 YAML 加载 DeploymentConfig

DeploymentConfig deploymentConfig = client.deploymentConfigs()
    .inNamespace("FunTester")
    .load(new FileInputStream("FunTester-deploymentconfig.yml")).item();

获取 DeploymentConfig

DeploymentConfig dc = client.deploymentConfigs()
    .inNamespace("FunTester")
    .withName("deploymentconfig1").get();

创建 DeploymentConfig

DeploymentConfig dc = new DeploymentConfigBuilder()
    .withNewMetadata().withName("deploymentconfig1").endMetadata()
    .withNewSpec()
    .withReplicas(2)
    .withNewTemplate()
    .withNewMetadata().addToLabels("app", "database").endMetadata()
    .withNewSpec()
    .addNewContainer()
    .withName("mysql")
    .withImage("openshift/mysql-55-centos7")
    .endContainer()
    .endSpec()
    .endTemplate()
    .endSpec()
    .build();

DeploymentConfig dcCreated = client.deploymentConfigs()
    .inNamespace("FunTester").resource(dc).create();

列出 DeploymentConfig

DeploymentConfigList dcList = client.deploymentConfigs()
    .inNamespace("FunTester").list();

删除 DeploymentConfig

client.deploymentConfigs()
    .inNamespace("FunTester")
    .withName("deploymentconfig1").delete();

3. BuildConfig

从 YAML 加载 BuildConfig

BuildConfig buildConfig = client.buildConfigs()
    .inNamespace("FunTester")
    .load(new FileInputStream("test-buildconfig.yml")).item();

创建 BuildConfig

BuildConfig buildConfig = new BuildConfigBuilder()
    .withNewMetadata().withName("bc1").endMetadata()
    .withNewSpec()
    .addNewTrigger().withType("GitHub").withNewGithub().withSecret("secret101").endGithub().endTrigger()
    .withNewSource().withType("Git").withNewGit().withUri("https://github.com/openshift/ruby-hello-world").endGit().endSource()
    .withNewStrategy().withType("Source").withNewSourceStrategy()
    .withNewFrom().withKind("ImageStreamTag").withName("origin-ruby-sample:latest").endFrom()
    .endSourceStrategy().endStrategy()
    .withNewOutput().withNewTo().withKind("ImageStreamTag").withName("origin-ruby-sample:latest").endTo().endOutput()
    .endSpec()
    .build();

client.buildConfigs().inNamespace("FunTester").resource(buildConfig).create();

列出 BuildConfig

BuildConfigList bcList = client.buildConfigs()
    .inNamespace("FunTester").list();

4. Route

从 YAML 加载 Route

Route route = client.routes()
    .inNamespace("FunTester")
    .load(new FileInputStream("test-route.yml")).item();

创建 Route

Route route = new RouteBuilder()
    .withNewMetadata().withName("route1").endMetadata()
    .withNewSpec()
    .withHost("www.FunTester.com")
    .withNewTo().withKind("Service").withName("service-name1").endTo()
    .endSpec()
    .build();

client.routes().inNamespace("FunTester").resource(route).create();

5. Project

创建 Project

ProjectRequest request = client.projectrequests().create(
    new ProjectRequestBuilder()
        .withNewMetadata().withName("thisisatest").endMetadata()
        .withDescription("Fabric8")
        .withDisplayName("Fabric8")
        .build()
);

列出 Project

ProjectList projectList = client.projects().list();

6. ImageStream

从 YAML 加载 ImageStream

ImageStream imageStream = client.imageStreams()
    .load(new FileInputStream("test-imagestream.yml")).item();

创建 ImageStream

ImageStream imageStream = new ImageStreamBuilder()
    .withNewMetadata().withName("FunTester-camel-cdi").endMetadata()
    .withNewSpec()
    .addNewTag().withName("latest").endTag()
    .withDockerImageRepository("fabric8/FunTester-camel-cdi")
    .endSpec()
    .build();

client.imageStreams().inNamespace("FunTester").resource(imageStream).create();

7. CatalogSource

创建 CatalogSource

CatalogSource cs = new CatalogSourceBuilder()
    .withNewMetadata().withName("foo").endMetadata()
    .withNewSpec()
    .withSourceType("Foo")
    .withImage("nginx:latest")
    .withDisplayName("Foo Bar")
    .withPublisher("Fabric8")
    .endSpec()
    .build();

client.operatorHub().catalogSources().inNamespace("FunTester").resource(cs).create();

8. PrometheusRule

创建 PrometheusRule

PrometheusRule prometheusRule = new PrometheusRuleBuilder()
    .withNewMetadata().withName("foo").endMetadata()
    .withNewSpec()
    .addNewGroup()
    .withName("./FunTester-rules")
    .addNewRule()
    .withAlert("FunTesterAlert")
    .withNewExpr().withStrVal("vector(1)").endExpr()
    .endRule()
    .endGroup()
    .endSpec()
    .build();

client.monitoring().prometheusRules().inNamespace("FunTester").resource(prometheusRule).create();

9. ServiceMonitor

创建 ServiceMonitor

ServiceMonitor serviceMonitor = new ServiceMonitorBuilder()
    .withNewMetadata()
    .withName("foo")
    .addToLabels("prometheus", "frontend")
    .endMetadata()
    .withNewSpec()
    .withNewNamespaceSelector().withAny(true).endNamespaceSelector()
    .withNewSelector()
    .addToMatchLabels("prometheus", "frontend")
    .endSelector()
    .addNewEndpoint()
    .withPort("http-metric")
    .withInterval("15s")
    .endEndpoint()
    .endSpec()
    .build();

client.monitoring().serviceMonitors().inNamespace("FunTester").resource(serviceMonitor).create();

10. ClusterResourceQuota

创建 ClusterResourceQuota

Map<String, Quantity> hard = new HashMap<>();
hard.put("pods", new Quantity("10"));
hard.put("secrets", new Quantity("20"));

ClusterResourceQuota crq = new ClusterResourceQuotaBuilder()
    .withNewMetadata().withName("foo").endMetadata()
    .withNewSpec()
    .withNewSelector()
    .addToAnnotations("openshift.io/requester", "foo-user")
    .endSelector()
    .withQuota(new ResourceQuotaSpecBuilder().withHard(hard).build())
    .endSpec()
    .build();

client.quotas().clusterResourceQuotas().resource(crq).create();

11. EgressNetworkPolicy

创建 EgressNetworkPolicy

EgressNetworkPolicy enp = new EgressNetworkPolicyBuilder()
    .withNewMetadata()
    .withName("foo")
    .withNamespace("FunTester")
    .endMetadata()
    .withNewSpec()
    .addNewEgress()
    .withType("Allow")
    .withNewTo().withCidrSelector("1.2.3.0/24").endTo()
    .endEgress()
    .addNewEgress()
    .withType("Allow")
    .withNewTo().withDnsName("www.foo.com").endTo()
    .endEgress()
    .endSpec()
    .build();

client.egressNetworkPolicies().inNamespace("FunTester").resource(enp).create();

12. Tekton 客户端

初始化 Tekton 客户端:

try (TektonClient client = new KubernetesClientBuilder().build().adapt(TektonClient.class)) {
    // 使用客户端进行操作
}

创建 PipelineRun

PipelineRun pipelineRun = new PipelineRunBuilder()
    .withNewMetadata().withName("demo-run-1").endMetadata()
    .withNewSpec()
    .withNewPipelineRef().withName("demo-pipeline").endPipelineRef()
    .addNewParam().withName("greeting").withNewValue("Hello World!").endParam()
    .endSpec()
    .build();

client.v1().pipelineRuns().inNamespace("FunTester").resource(pipelineRun).create();

13. Knative 客户端

初始化 Knative 客户端:

try (KnativeClient client = new KubernetesClientBuilder().build().adapt(KnativeClient.class)) {
    // 使用客户端进行操作
}

创建 Service

Service service = new ServiceBuilder()
    .withNewMetadata().withName("helloworld-go").endMetadata()
    .withNewSpec()
    .withNewTemplate()
    .withNewSpec()
    .addToContainers(new ContainerBuilder()
        .withImage("gcr.io/knative-samples/helloworld-go")
        .addNewEnv().withName("TARGET").withValue("Go Sample V1").endEnv()
        .build())
    .endSpec()
    .endTemplate()
    .endSpec()
    .build();

client.services().inNamespace("FunTester").resource(service).serverSideApply();

14. 日志记录

配置日志记录:

simplelogger.properties 文件中设置日志级别:

org.slf4j.simpleLogger.defaultLogLevel=trace

Show You Code

以下是一个完整的示例,展示如何使用 Fabric8 OpenShift 客户端 DSL 来管理 OpenShift 集群中的资源。这个示例包括初始化 OpenShift 客户端、创建 DeploymentConfig、创建 Route,以及列出和删除资源。

示例代码

import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.ConfigBuilder;
import io.fabric8.openshift.api.model.*;
import io.fabric8.openshift.client.OpenShiftClient;
import io.fabric8.openshift.client.DefaultOpenShiftClient;

import java.io.FileInputStream;
import java.util.Collections;

public class OpenShiftClientFunTester {

    public static void main(String[] args) {
        // 初始化 OpenShift 客户端
        try (OpenShiftClient client = new DefaultOpenShiftClient()) {
            String namespace = "FunTester";

            // 1. 创建 DeploymentConfig
            DeploymentConfig deploymentConfig = new DeploymentConfigBuilder()
                    .withNewMetadata()
                    .withName("FunTester-dc")
                    .endMetadata()
                    .withNewSpec()
                    .withReplicas(2)
                    .withNewTemplate()
                    .withNewMetadata()
                    .addToLabels("app", "FunTester-app")
                    .endMetadata()
                    .withNewSpec()
                    .addNewContainer()
                    .withName("nginx")
                    .withImage("nginx:latest")
                    .addNewPort().withContainerPort(80).endPort()
                    .endContainer()
                    .endSpec()
                    .endTemplate()
                    .endSpec()
                    .build();

            // 创建 DeploymentConfig
            client.deploymentConfigs().inNamespace(namespace).resource(deploymentConfig).create();
            System.out.println("DeploymentConfig 创建成功!");

            // 2. 创建 Route
            Route route = new RouteBuilder()
                    .withNewMetadata()
                    .withName("FunTester-route")
                    .endMetadata()
                    .withNewSpec()
                    .withHost("www.FunTester.com")
                    .withNewTo()
                    .withKind("Service")
                    .withName("FunTester-service")
                    .endTo()
                    .endSpec()
                    .build();

            // 创建 Route
            client.routes().inNamespace(namespace).resource(route).create();
            System.out.println("Route 创建成功!");

            // 3. 列出 DeploymentConfig
            DeploymentConfigList dcList = client.deploymentConfigs().inNamespace(namespace).list();
            System.out.println("当前命名空间中的 DeploymentConfig:");
            dcList.getItems().forEach(dc -> System.out.println(dc.getMetadata().getName()));

            // 4. 列出 Route
            RouteList routeList = client.routes().inNamespace(namespace).list();
            System.out.println("当前命名空间中的 Route:");
            routeList.getItems().forEach(r -> System.out.println(r.getMetadata().getName()));

            // 5. 删除 DeploymentConfig
            client.deploymentConfigs().inNamespace(namespace).withName("FunTester-dc").delete();
            System.out.println("DeploymentConfig 删除成功!");

            // 6. 删除 Route
            client.routes().inNamespace(namespace).withName("FunTester-route").delete();
            System.out.println("Route 删除成功!");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

示例说明

  1. 初始化 OpenShift 客户端

    • 使用 DefaultOpenShiftClient 初始化客户端,默认会从 ~/.kube/config 文件中读取配置。
  2. 创建 DeploymentConfig

    • 定义了一个 DeploymentConfig,包含 2 个副本的 Nginx 容器。
    • 使用 client.deploymentConfigs().create() 方法创建资源。
  3. 创建 Route

    • 定义了一个 Route,将流量路由到名为 FunTester-service 的服务。
    • 使用 client.routes().create() 方法创建资源。
  4. 列出资源

    • 使用 client.deploymentConfigs().list()client.routes().list() 列出当前命名空间中的资源。
  5. 删除资源

    • 使用 client.deploymentConfigs().delete()client.routes().delete() 删除之前创建的资源。

运行示例

  1. 确保已安装 OpenShift 集群,并且 kubeconfig 文件已正确配置。
  2. 将上述代码保存为 OpenShiftClientFunTester.java
  3. 编译并运行: bash javac -cp fabric8-openshift-client-<version>.jar OpenShiftClientFunTester.java java -cp .:fabric8-openshift-client-<version>.jar OpenShiftClientFunTester
  4. 观察控制台输出,确认资源创建、列出和删除的操作是否成功。

输出示例

DeploymentConfig 创建成功!
Route 创建成功!
当前命名空间中的 DeploymentConfig:
FunTester-dc
当前命名空间中的 Route:
FunTester-route
DeploymentConfig 删除成功!
Route 删除成功!
FunTester 原创精华
【免费合集】从 Java 开始性能测试
故障测试与 Web 前端
服务端功能测试
性能测试专题
Java、Groovy、Go
测试开发、自动化、白盒
测试理论、FunTester 风采
视频专题
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册