Kubernetes

Fabric8操作Kubernetes(二)

2020-11-09  本文已影响0人  王勇1024

前言

Fabric8操作Kubernetes(一) 一文中我们介绍了初始化 KubernetesClient的方法。今天我们一起来学习一下如果通过 KubernetesClient 创建各种资源对象

Pods

通过 client.pods() 可以实现对 Pods 的操作。下面是一些常用方法:

Pod myPod = client.pods().load(new FileInputStream("some-pod.yml")).get();
PodList podList = client.pods().inNamespace("default").list();
PodList podList = client.pods().inAnyNamespace().list();
PodList podList = client.pods().inNamespace("default").withLabel("foo", "bar").list();
Pod myPod = client.pods().inNamespace("default").withName("nginx-pod").get();
Pod aPod = new PodBuilder().withNewMetadata().withName("demo-pod1").endMetadata()
    .withNewSpec()
    .addNewContainer()
    .withName("nginx")
    .withImage("nginx:1.7.9")
    .addNewPort().withContainerPort(80).endPort()
    .endContainer()
    .endSpec()
    .build();
Pod createdPod = client.pods().inNamespace("default").create(aPod);
client.pods().inNamespace("default").createOrReplace(aPod);
client.pods().inNamespace("default").createOrReplaceWithNew()
    .withNewMetadata().withName("demo-pod1").endMetadata()
    .withNewSpec()
    .addNewContainer()
    .withName("nginx")
    .withImage("nginx:1.7.9")
    .addNewPort().withContainerPort(80).endPort()
    .endContainer()
    .endSpec()
    .done();
client.pods().inNamespace("default").withName("nginx").edit()
    .editOrNewMetadata().addToLabels("new","label").endMetadata().done()
String log = client.pods().inNamespace("default").withName("test-pod").getLog();
LogWatch watch = client.pods().inNamespace(namespace).withName(podName).tailingLines(10).watchLog(System.out);
Boolean isDeleted = client.pods().inNamespace("default").withName("nginx").delete();
Boolean isDeleted = client.pods().inNamespace("default").delete(pod1, pod2);
Pod pod = client.pods().inNamespace("default").withName("nginx").waitUntilReady(5, TimeUnit.MINUTES);
Pod pod = client.pods().inNamespace("default").withName("nginx").waitUntilCondition(pod -> pod.getStatus().getPhase().equals("Succeeded"), 1, TimeUnit.MINUTES)
int containerPort =  client.pods().inNamespace("default").withName("testpod").get().getSpec().getContainers().get(0).getPorts().get(0).getContainerPort();
LocalPortForward portForward = client.pods().inNamespace("default").withName("testpod").portForward(containerPort, 8080);
final CountDownLatch deleteLatch = new CountDownLatch(1);
Watch watch = client.pods().withName("pod1").watch(new Watcher<Pod>() {
   @Override
   public void eventReceived(Action action, Pod resource) {
     switch (action) {
       case DELETED:
         deleteLatch.countDown();
       }
    }

    @Override
    public void onClose(KubernetesClientException cause) { }
});
deleteLatch.await(10, TimeUnit.MINUTES)
   client.pods().inNamespace(currentNamespace).withName(pod1.getMetadata().getName())
      .file("/tmp/toBeUploaded").upload(tmpFile.toPath());
    try (InputStream is = client.pods().inNamespace(currentNamespace).withName(pod1.getMetadata().getName()).file("/msg").read())  {
      String result = new BufferedReader(new InputStreamReader(is)).lines().collect(Collectors.joining("\n"));
    }

Service

通过 client.services() 可以实现对 Service 的操作。下面是一些常用方法:

Service aService = client.services().load(new FileInputStream("service.yml")).get();

Service service = client.services().inNamespace("default").withName("some-service").get();

Service createdSvc = client.services().inNamespace("default").create(svc);

Service createdSvc = client.services().inNamespace("default").createOrReplace(svc);

Service createdSvc = client.services().inNamespace("default").createOrReplaceWithNew()
    .withNewMetadata().withName("svc2").endMetadata()
    .withNewSpec().withType("ExternalName").withExternalName("my.database.example.com")
    .addNewPort().withName("80").withProtocol("TCP").withPort(80).endPort()
    .endSpec()
    .withNewStatus()
    .withNewLoadBalancer()
    .addNewIngress()
    .withIp("146.148.47.155")
    .endIngress()
    .endLoadBalancer()
    .endStatus()
    .done();

ServiceList svcList = client.services().inNamespace("default").list();

ServiceList svcList = client.services().inAnyNamespace().list();

ServiceList svcList = client.services().inNamespace("default").withLabel("foo", "bar").list();

Boolean isDeleted = client.services().inNamespace("default").withName("some-svc").delete();

client.services().inNamespace("default").watch(new Watcher<Service>() {
    @Override
    public void eventReceived(Action action, Service resource) {
      // Perform something depending upon action
    }

    @Override
    public void onClose(KubernetesClientException cause) {

    }
});

Deployment

通过 client.apps().deployment() 可以实现对 Deployment 的操作。下面是一些常用方法:

Deployment aDeployment = client.apps().deployments().load(new FileInputStream("test-deployments.yml")).get();

Deployment deploy = client.apps().deployments().inNamespace("default").withName("deploy-1").get();

Deployment deployment1 = new DeploymentBuilder()
   .withNewMetadata()
      .withName("deployment1")
      .addToLabels("test", "deployment")
   .endMetadata()
   .withNewSpec()
      .withReplicas(1)
      .withNewTemplate()
        .withNewMetadata()
        .addToLabels("app", "httpd")
        .endMetadata()
        .withNewSpec()
          .addNewContainer()
             .withName("busybox")
             .withImage("busybox")
             .withCommand("sleep","36000")
          .endContainer()
        .endSpec()
      .endTemplate()
      .withNewSelector()
        .addToMatchLabels("app","httpd")
      .endSelector()
   .endSpec()
 .build();

client.apps().deployments().inNamespace("default").create(deployment1);

Deployment createdDeployment = client.apps().deployments().inNamespace("default").createOrReplace(deployObj);

client.apps().deployments().inNamespace("default").createOrReplaceWithNew()
   .withNewMetadata()
      .withName("deployment1")
      .addToLabels("test", "deployment")
   .endMetadata()
   .withNewSpec()
      .withReplicas(1)
      .withNewTemplate()
        .withNewMetadata()
        .addToLabels("app", "httpd")
        .endMetadata()
        .withNewSpec()
          .addNewContainer()
             .withName("busybox")
             .withImage("busybox")
             .withCommand("sleep","36000")
          .endContainer()
        .endSpec()
      .endTemplate()
      .withNewSelector()
        .addToMatchLabels("app","httpd")
      .endSelector()
   .endSpec()
 .done();

DeploymentList aDeploymentList = client.apps().deployments().inNamespace("default").list();

DeploymentList aDeploymentList = client.apps().deployments().inAnyNamespace().list();

DeploymentList aDeployList = client.apps().deployments().inNamespace("default").withLabel("foo", "bar").list();

// Scales Deployment to 2 replicas
Deployment updatedDeploy = client.apps().deployments().inNamespace("default")
      .withName("deployment1").edit()
      .editSpec().withReplicas(2).endSpec().done();

Deployment updatedDeployment = client.apps().deployments().inNamespace("default").withName("ngix-controller")
            .rolling().updateImage("docker.io/nginx:latest");

Map<String, String> containerToImageMap = new HashMap<>();
containerToImageMap.put("nginx", "nginx:perl");
containerToImageMap.put("sidecar", "someImage:someVersion");
Deployment updatedDeployment = client.apps().deployments()
      .inNamespace("default")
      .withName("nginx-deployment")
      .rolling()
      .updateImage(containerToImageMap);

Deployment deployment = client.apps().deployments()
      .inNamespace("default")
      .withName("nginx-deployment")
      .rolling()
      .restart();

Deployment deployment = client.apps().deployments()
      .inNamespace("default")
      .withName("nginx-deployment")
      .rolling()
      .pause();

Deployment deployment = client.apps().deployments()
      .inNamespace("default")
      .withName("nginx-deployment")
      .rolling()
      .resume();

Deployment deployment = client.apps().deployments()
      .inNamespace("default")
      .withName("nginx-deployment")
      .rolling()
      .undo();

Boolean isDeleted = client.apps().deployments().inNamespace("default").withName("foo").delete();

client.apps().deployments().inNamespace("default").watch(new Watcher<Deployment>() {
  @Override
  public void eventReceived(Action action, Deployment resource) {
    // Do stuff depending upon action
  }

  @Override
  public void onClose(KubernetesClientException cause) {

  }
});

client.apps().deployments().inNamespace("default").withName("nginx-deployment").scale(1);

client.apps().deployments().inNamespace("default").withName("nginx").watchLog(System.out);

ReplicaSet

通过 client.apps().replicaSets() 可以实现对 ReplicaSet 的操作。下面是一些常用方法:

ReplicaSet replicaSet = client.apps().replicaSets().inNamespace("default")
  .load(new FileInputStream("test-replicaset.yml")).get();

ReplicaSet rs = client.apps().replicaSets().inNamespace("default").withName("rs1").get();

ReplicaSet replicaset1 = new ReplicaSetBuilder()
      .withNewMetadata()
      .withName("replicaset1")
      .addToLabels("app", "guestbook")
      .addToLabels("tier", "frontend")
      .endMetadata()
      .withNewSpec()
      .withReplicas(1)
      .withNewSelector()
      .withMatchLabels(Collections.singletonMap("tier", "frontend"))
      .endSelector()
      .withNewTemplate()
      .withNewMetadata()
      .addToLabels("app", "guestbook")
      .addToLabels("tier", "frontend")
      .endMetadata()
      .withNewSpec()
      .addNewContainer()
      .withName("busybox")
      .withImage("busybox")
      .withCommand("sleep","36000")
      .withNewResources()
      .withRequests(requests)
      .endResources()
      .withEnv(envVarList)
      .endContainer()
      .endSpec()
      .endTemplate()
      .endSpec()
      .build();

client.apps().replicaSets().inNamespace("default").create(replicaset1);

ReplicaSet rs = client.apps().replicaSets().inNamespace("default").createOrReplace(replicaSet);

ReplicaSet rs = client.apps().replicaSets().inNamespace("default").createOrReplaceWithNew()
        .withNewMetadata()
        .withName("replicaset1")
        .addToLabels("app", "guestbook")
        .addToLabels("tier", "frontend")
        .endMetadata()
        .withNewSpec()
        .withReplicas(1)
        .withNewSelector()
        .withMatchLabels(Collections.singletonMap("tier", "frontend"))
        .endSelector()
        .withNewTemplate()
        .withNewMetadata()
        .addToLabels("app", "guestbook")
        .addToLabels("tier", "frontend")
        .endMetadata()
        .withNewSpec()
        .addNewContainer()
        .withName("busybox")
        .withImage("busybox")
        .withCommand("sleep","36000")
        .withNewResources()
        .withRequests(requests)
        .endResources()
        .withEnv(envVarList)
        .endContainer()
        .endSpec()
        .endTemplate()
        .endSpec()
        .done();

ReplicaSetList rsList = client.apps().replicaSets().inNamespace("default").list();

ReplicaSetList rsList = client.apps().replicaSets().inAnyNamespace().list();

ReplicaSetList rsList = client.apps().replicaSets().inNamespace("default").withLabel("foo", "bar").list(); 

Boolean isDeleted = client.apps().replicaSets().inNamespace("default").withName("rs1").delete();

client.apps().replicaSets().inNamespace("default").watch(new Watcher<ReplicaSet>() {
   @Override
   public void eventReceived(Action action, ReplicaSet resource) {
     // Do some stuff depending upon action type
   }

   @Override
   public void onClose(KubernetesClientException cause) {

   }
});

// Scale to 3 replicas
client.apps().replicaSets().inNamespace("default").withName("nginx-rs").scale(3);

ReplicaSet replicaSet = client.apps().replicaSets()
            .inNamespace("default")
            .withName("soaktestrs")
            .rolling()
            .updateImage("nickchase/soaktest");

Map<String, String> containerToImageMap = new HashMap<>();
containerToImageMap.put("c1", "image1");
containerToImageMap.put("c2", "image2");
ReplicaSet replicaSet = client.apps().replicaSets()
            .inNamespace("default")
            .withName("soaktestrs")
            .rolling()
            .updateImage(containerToImageMap);

ReplicationController

通过 client.replicationControllers() 可以实现对 ReplicationController 的操作。下面是一些常用方法:

ReplicationController aReplicationController = client.replicationControllers().inNamespace("default")
      .load(new FileInputStream("/test-replicationcontroller.yml")).get();

ReplicationController rc = client.replicationControllers().inNamespace("default").withName("nginx-controller").get();

ReplicationController rc1 = new ReplicationControllerBuilder()
  .withNewMetadata().withName("nginx-controller").addToLabels("server", "nginx").endMetadata()
  .withNewSpec().withReplicas(3)
  .withNewTemplate()
  .withNewMetadata().addToLabels("server", "nginx").endMetadata()
  .withNewSpec()
  .addNewContainer().withName("nginx").withImage("nginx")
  .addNewPort().withContainerPort(80).endPort()
  .endContainer()
  .endSpec()
  .endTemplate()
  .endSpec().build();

ReplicationController rc = client.replicationControllers().inNamespace("default").create(rc1);

ReplicationController rc = client.replicationControllers().inNamespace("default").createOrReplace(rc1);

ReplicationController rc = client.replicationControllers().inNamespace("default").createOrReplaceWithNew()
  .withNewMetadata().withName("nginx-controller").addToLabels("server", "nginx").endMetadata()
  .withNewSpec().withReplicas(3)
  .withNewTemplate()
  .withNewMetadata().addToLabels("server", "nginx").endMetadata()
  .withNewSpec()
  .addNewContainer().withName("nginx").withImage("nginx")
  .addNewPort().withContainerPort(80).endPort()
  .endContainer()
  .endSpec()
  .endTemplate()
  .endSpec().done();

ReplicationControllerList rcList = client.replicationControllers().inNamespace("default").list();

ReplicationControllerList rcList = client.replicationControllers().inAnyNamespace("default").list();

ReplicationControllerList rcList = client.replicationControllers().inNamespace("default").withLabel("foo", "bar").list();

Boolean isDeleted = client.replicationControlers().inNamespace("default").withName("nginx-controller").delete();

client.replicationControllers().inNamespace(currentNamespace).watch(new Watcher<ReplicationController>() {
  @Override
  public void eventReceived(Action action, ReplicationController resource) {
    // Do something depending upon action type    
  }

  @Override
  public void onClose(KubernetesClientException cause) {

  }
});

ReplicationController rc = client.replicationControllers().inNamespace("default").withName("nginx-controller").scale(2);

ReplicationController rc = client.replicationControllers()
       .inNamespace("default")
       .withName("nginx")
       .rolling()
       .updateImage("nginx:latest");

Map<String, String> containerToImageMap = new HashMap<>();
containerToImageMap.put("c1", "image1");
containerToImageMap.put("c2", "image2");
ReplicationController rc = client.replicationControllers()
       .inNamespace("default")
       .withName("nginx")
       .rolling()
       .updateImage(controllerToImageMap);

ConfigMap

ConfigMap resource is available in Kubernetes Client api via the client.configMaps(). Here are some examples of common usage:

ConfigMap configMap = client.configMaps().load(new FileInputStream("configmap1.yml")).get();

ConfigMap configMap = client.configMaps().inNamespace("default").withName("configmap1").get();

ConfigMap configMap1 = new ConfigMapBuilder()
      .withNewMetadata().withName("configmap1").endMetadata()
      .addToData("1", "one")
      .addToData("2", "two")
      .addToData("3", "three")
      .build();
ConfigMap configMap = client.configMaps().inNamespace("default").create(configMap1);

ConfigMap configMap = client.configMaps().inNamespace("default").createOrReplace(configMap1);

ConfigMap configMap = client.configMaps().inNamespace("default").createOrReplaceWithNew()
      .withNewMetadata().withName("configmap1").endMetadata()
      .addToData("1", "one")
      .addToData("2", "two")
      .addToData("3", "three")
      .done();

ConfigMapList configMapList = client.configMaps().inNamespace("default").list();

ConfigMapList configMapList = client.configMaps().inAnyNamespace().list();

ConfigMapList configMapList = client.configMaps().inNamespace("default").withLabel("foo", "bar").list();

Boolean isDeleted = client.configMaps().inNamespace("default").withName("configmap1").delete();

client.configMaps().inNamespace("default").watch(new Watcher<ConfigMap>() {
  @Override
  public void eventReceived(Action action, ConfigMap resource) {
    // Do something depending upon action type    
  }

  @Override
  public void onClose(KubernetesClientException cause) {

  }
});

ConfigMap configMap1 = client.configMaps().inNamespace(currentNamespace).withName("configmap1").edit()
      .addToData("4", "four").done();

Secret

Secret resource is available in Kubernetes Client api via client.secrets(). Here are some of the examples of it's common usages:

Secret aSecret = client.secrets().inNamespace("default").load(new FileInputStream("test-secret.yml")).get();

Secret secret = client.secrets().inNamespace("default").withName("secret1").get()

Secret secret1 = new SecretBuilder()
      .withNewMetadata().withName("secret1").endMetadata()
      .addToData("username", "guccifer")
      .addToData("password", "shadowgovernment")
      .build();
Secret secretCreated = client.secrets().inNamespace("default").create(secret1);

Secret createdSecret = client.secrets().inNamespace("default").createOrReplace(secret1);

Secret createdSecret = client.secrets().inNamespace("default").createOrReplaceWithNew()
      .withNewMetadata().withName("secret1").endMetadata()
      .addToData("username", "guccifer")
      .addToData("password", "shadowgovernment")
      .done();

SecretList secretList = client.secrets().inNamespace("default").list();

SecretList secretList = client.secrets().inAnyNamespace().list();

SecretList secretList = client.secrets().inNamespace("default").withLabel("foo", "bar").list();

Secret secret1 = client.secrets().inNamespace(currentNamespace).withName("secret1").edit()
      .withType("Opaque")
      .done();

Boolean isDeleted = client.secrets().inNamespace("default").withName("secret1").delete();

    client.secrets().inNamespace("default").watch(new Watcher<Secret>() {
      @Override
      public void eventReceived(Action action, Secret resource) {
        // Do something depending upon action type
      }

      @Override
      public void onClose(KubernetesClientException cause) {

      }
    });

Job

Job resource is available in Kubernetes Client API via client.batch().jobs(). Here are some of the examples of common usage:

Job job = client.batch().jobs().load(new FileInputStream("sample-job.yml")).get();

Job job = client.batch().jobs().inNamespace("default").withName("pi").get();

final Job job = new JobBuilder()
    .withApiVersion("batch/v1")
    .withNewMetadata()
    .withName("pi")
    .withLabels(Collections.singletonMap("label1", "maximum-length-of-63-characters"))
    .withAnnotations(Collections.singletonMap("annotation1", "some-very-long-annotation"))
    .endMetadata()
    .withNewSpec()
    .withNewTemplate()
    .withNewSpec()
    .addNewContainer()
    .withName("pi")
    .withImage("perl")
    .withArgs("perl", "-Mbignum=bpi", "-wle", "print bpi(2000)")
    .endContainer()
    .withRestartPolicy("Never")
    .endSpec()
    .endTemplate()
    .endSpec()
    .build();

client.batch().jobs().inNamespace("default").create(job);

Job job = client.batch().jobs().inNamespace("default").createOrReplace(job);

Job job = client.batch().jobs().inNamespace("default").createOrReplaceWithNew()
    .withApiVersion("batch/v1")
    .withNewMetadata()
    .withName("pi")
    .withLabels(Collections.singletonMap("label1", "maximum-length-of-63-characters"))
    .withAnnotations(Collections.singletonMap("annotation1", "some-very-long-annotation"))
    .endMetadata()
    .withNewSpec()
    .withNewTemplate()
    .withNewSpec()
    .addNewContainer()
    .withName("pi")
    .withImage("perl")
    .withArgs("perl", "-Mbignum=bpi", "-wle", "print bpi(2000)")
    .endContainer()
    .withRestartPolicy("Never")
    .endSpec()
    .endTemplate()
    .endSpec()
    .done();

JobList jobList = client.batch().jobs().inNamespace("default").list();

JobList jobList = client.batch().jobs().inAnyNamespace().list();

JobList jobList = client.batch().jobs().inNamespace("default").withLabel("foo", "bar").list();

Boolean isDeleted = client.batch().jobs().inNamespace("default").withName("pi").delete();

  client.batch().jobs().inNamespace("default").watch(new Watcher<Job>() {
    @Override
    public void eventReceived(Action action, Job resource) {
      // Do something depending upon action 
    }

    @Override
    public void onClose(KubernetesClientException cause) {

    }
  })

CronJob

CronJob resource is available in Kubernetes Client api via client.batch().cronjobs(). Here are some of the examples of its usages:

CronJob cronJob = client.batch().cronjobs().load(new FileInputStream("cronjob.yml")).get();

CronJob aCronJob = client.batch().cronjobs().inNamespace("default").withName("some-cj").get();

CronJob cronJob1 = new CronJobBuilder()
    .withApiVersion("batch/v1beta1")
    .withNewMetadata()
    .withName("hello")
    .withLabels(Collections.singletonMap("foo", "bar"))
    .endMetadata()
    .withNewSpec()
    .withSchedule("*/1 * * * *")
    .withNewJobTemplate()
    .withNewSpec()
    .withNewTemplate()
    .withNewSpec()
    .addNewContainer()
    .withName("hello")
    .withImage("busybox")
    .withArgs("/bin/sh", "-c", "date; echo Hello from Kubernetes")
    .endContainer()
    .withRestartPolicy("OnFailure")
    .endSpec()
    .endTemplate()
    .endSpec()
    .endJobTemplate()
    .endSpec()
    .build();

cronJob1 = client.batch().cronjobs().inNamespace("default").create(cronJob1);

CronJob cronJob = client.batch().cronjobs().inNamespace("default").createOrReplace(cronJob1);

CronJob cronJob = client.batch().cronjobs().inNamespace("default").createOrReplaceWithNew()
    .withApiVersion("batch/v1beta1")
    .withNewMetadata()
    .withName("hello")
    .withLabels(Collections.singletonMap("foo", "bar"))
    .endMetadata()
    .withNewSpec()
    .withSchedule("*/1 * * * *")
    .withNewJobTemplate()
    .withNewSpec()
    .withNewTemplate()
    .withNewSpec()
    .addNewContainer()
    .withName("hello")
    .withImage("busybox")
    .withArgs("/bin/sh", "-c", "date; echo Hello from Kubernetes")
    .endContainer()
    .withRestartPolicy("OnFailure")
    .endSpec()
    .endTemplate()
    .endSpec()
    .endJobTemplate()
    .endSpec()
    .done();

CronJobList cronJobList = client.batch().cronjobs().inNamespace("default").list()

CronJobList cronJobList = client.batch().cronjobs().inAnyNamespace().list();

CronJobList cronJobList = client.batch().cronjobs().inNamespace("default").withLabel("foo", "bar").list();

CronJob cronJob1 = client.batch().cronjobs().inNamespace("default").withName(cronJob1.getMetadata().getName())
      .edit()
      .editSpec()
      .withSchedule("*/1 * * * *")
      .endSpec()
      .done();

Boolean isDeleted = client.batch().cronjobs().inNamespace("default").withName("pi").delete();

Namespace

Namespace is available in Kubernetes Client API via client.namespaces(). Here are some of the common usages:

Namespace namespace = client.namespaces().load(new FileInputStream("namespace-test.yml")).get();

Namespace namespace = client.namespaces().withName("namespace1").get();

NamespaceList namespaceList = client.namespaces().list();

NamespaceList namespaceList = client.namespaces().withLabel("key1", "value1").list();

Boolean isDeleted = client.namespaces().withName("ns1").delete();

ServiceAccount

ServiceAccount resource is available in Kubernetes Client API via client.serviceAccounts(). Here are some examples of it's usage:

ServiceAccount svcAccount = client.serviceAccounts().inNamespace("default")
  .load(new FileInputStream("sa.yml")).get();

ServiceAccount sa = client.serviceAccounts().inNamespace("default").withName("sa-ribbon").get();

ServiceAccount serviceAccount1 = new ServiceAccountBuilder()
  .withNewMetadata().withName("serviceaccount1").endMetadata()
  .withAutomountServiceAccountToken(false)
  .build();

client.serviceAccounts().inNamespace("default").create(serviceAccount1);

ServiceAccount serviceAccount = client.serviceAccounts().inNamespace("default").createOrReplace(serviceAccount1);

ServiceAccount serviceAccount = client.serviceAccounts().inNamespace("default").createOrReplaceWithNew()
  .withNewMetadata().withName("serviceaccount1").endMetadata()
  .withAutomountServiceAccountToken(false)
  .done();

ServiceAccountList svcAccountList = client.serviceAccounts().inNamespace("default").list();

ServiceAccountList saList = client.serviceAccounts().inNamespace("default").withLabel("foo", "bar").list();

ServiceAccount serviceAccount1 = client.serviceAccounts().inNamespace("default").withName("serviceaccount1").edit()
  .addNewSecret().withName("default-token-uudp").endSecret()
  .addNewImagePullSecret().withName("myregistrykey").endImagePullSecret()
  .done();

Boolean bDeleted = client.serviceAccounts().inNamespace("default").withName("serviceaccount1").delete();

Ingress

Ingress resource is available in Kubernetes Client API via client.network().ingress(). Here are some examples regarding its usage:

Ingress ingress = client.network().ingress().load(new FileInputStream("ingress.yml")).get();

Ingress ingress = client.network().ingress().inNamespace("default").withName("ingress1").get();

Ingress ingress = new IngressBuilder()
  .withNewMetadata().withName("test-ingress").addToAnnotations("nginx.ingress.kubernetes.io/rewrite-target", "/").endMetadata()
  .withNewSpec()
  .addNewRule()
  .withNewHttp()
  .addNewPath()
  .withPath("/testPath").withNewBackend().withServiceName("test").withServicePort(new IntOrString(80)).endBackend()
  .endPath()
  .endHttp()
  .endRule()
  .endSpec()
  .build();
client.network().ingress().inNamespace("default").create(ingress);

Ingress igx = client.network().ingress().inNamespace("default").createOrReplace(ingress);

Ingress igx = client.network().ingress().inNamespace("default").createOrReplaceWithNew()
  .withNewMetadata().withName("test-ingress").addToAnnotations("nginx.ingress.kubernetes.io/rewrite-target", "/").endMetadata()
  .withNewSpec()
  .addNewRule()
  .withNewHttp()
  .addNewPath()
  .withPath("/testPath").withNewBackend().withServiceName("test").withServicePort(new IntOrString(80)).endBackend()
  .endPath()
  .endHttp()
  .endRule()
  .endSpec()
  .done();

IngressList ingressList = client.network().ingress().inNamespace("default").list();

IngressList ingressList = client.network().ingress().inAnyNamespace().list();

IngressList ingressList = client.network().ingress().inNamespace("default").withLabel("foo", "bar").list();

Boolean isDeleted = client.network().ingress().inNamespace("default").withName("ingress1").delete();

StatefulSet

StatefulSet resource is available in Kubernetes API via client.apps().statefulsets(). Here are some examples of its common usages:

StatefulSet aStatefulSet = client.apps().statefulSets()
  .load(new FileInputStream("test-statefulset.yml")).get();

StatefulSet ss1 = client.apps().statefulSets().inNamespace("default").withName("ss1").get();

StatefulSet ss1 = new StatefulSetBuilder()
      .withNewMetadata().withName("ss1").endMetadata()
      .withNewSpec()
      .withReplicas(2)
      .withNewSelector().withMatchLabels(Collections.singletonMap("app", "nginx")).endSelector()
      .withNewTemplate()
      .withNewMetadata()
      .addToLabels("app", "nginx")
      .endMetadata()
      .withNewSpec()
      .addNewContainer()
      .withName("nginx")
      .withImage("nginx")
      .addNewPort()
      .withContainerPort(80)
      .withName("web")
      .endPort()
      .addNewVolumeMount()
      .withName("www")
      .withMountPath("/usr/share/nginx/html")
      .endVolumeMount()
      .endContainer()
      .endSpec()
      .endTemplate()
      .addNewVolumeClaimTemplate()
      .withNewMetadata()
      .withName("www")
      .endMetadata()
      .withNewSpec()
      .addToAccessModes("ReadWriteOnce")
      .withNewResources()
      .withRequests(Collections.singletonMap("storage", new Quantity("1Gi")))
      .endResources()
      .endSpec()
      .endVolumeClaimTemplate()
      .endSpec()
      .build();

StatefulSet ss = client.apps().statefulSets().inNamespace("default").create(ss1);

StatefulSet ss = client.apps().statefulSets().inNamespace("default").createOrReplace(ss1);

StatefulSetList statefulSetList = client.apps().statefulSets().inNamespace("default").list();

StatefulSetList statefulSetList = client.apps().statefulSets().inAnyNamespace().list();

StatefulSetList statefulSetList = client.apps().statefulSets().inNamespace("default").withLabel("foo", "bar").list();

Boolean bDeleted = client.apps().statefulSets().inNamespace("default").withName("ss1").delete();

client.apps().statefulSets().inNamespace("default").withName("ss1").scale(2);

client.apps().statefulSets().inNamespace("default").withName("ss1").watch(new Watcher<StatefulSet>() {
  @Override
  public void eventReceived(Action action, StatefulSet resource) {
    // Do something on action type
  }

  @Override
  public void onClose(KubernetesClientException cause) {

  }
})

StatefulSet statefulSet = client.apps().statefulSets()
      .inNamespace("default")
      .withName("web")
      .rolling()
      .updateImage("nginx:1.19");

Map<String, String> containerToImageMap = new HashMap<>();
containerToImageMap("container1", "nginx:1.9");
containerToImageMap("container2", "busybox:latest");
Statefulset statefulSet = client.apps().statefulSets()
      .inNamespace("default")
      .withName("web")
      .rolling()
      .updateImage(params);

StatefulSet ss = client.apps().statefulSets()
        .inNamespace("default")
        .withName("web")
        .rolling()
        .restart();

StatefulSet ss = client.apps().statefulSets()
         .inNamespace("default")
         .withName("web")
         .rolling()
         .pause();

StatefulSet ss = client.apps().statefulSets()
         .inNamespace("default")
         .withName("web")
         .rolling()
         .resume();

StatefulSet ss = client.apps().statefulSets()
     .inNamespace("default")
     .withName("web")
     .rolling()
     .undo();

DaemonSet

DaemonSet resource is available in Kubernetes Client API via client.apps().daemonSets(). Here are some examples of its common usage:

DaemonSet ds = client.apps().daemonSets().load(new FileInputStream("daemonset.yaml")).get();

DaemonSet ds = client.apps().daemonSets().inNamespace("default").withName("ds1").get();

DaemonSet ds = new DaemonSetBuilder()
  .withNewMetadata().withName("fluentd-elasticsearch").addToLabels("k8s-app", "fluentd-logging").endMetadata()
  .withNewSpec()
  .withNewSelector()
  .addToMatchLabels("name", "fluentd-elasticsearch")
  .endSelector()
  .withNewTemplate()
  .withNewSpec()
  .addNewToleration().withKey("node-role.kubernetes.io/master").withEffect("NoSchedule").endToleration()
  .addNewContainer()
  .withName("fluentd-elasticsearch").withImage("quay.io/fluentd_elasticsearch/fluentd:v2.5.2")
  .withNewResources()
  .addToLimits(Collections.singletonMap("memory", new Quantity("200Mi")))
  .addToRequests(Collections.singletonMap("cpu", new Quantity("100m")))
  .endResources()
  .addNewVolumeMount().withName("varlog").withMountPath("/var/log").endVolumeMount()
  .endContainer()
  .withTerminationGracePeriodSeconds(30l)
  .addNewVolume()
  .withName("varlog").withNewHostPath().withPath("/var/log").endHostPath()
  .endVolume()
  .endSpec()
  .endTemplate()
  .endSpec()
  .build();
ds = client.apps().daemonSets().inNamespace("default").create(ds);

DaemonSet ds = client.apps().daemonSets().inNamespace("default").createOrReplace(ds);

DaemonSetList dsList = client.apps().daemonSets().inNamespace("default").list();

DaemonSetList dsList = client.apps().daemonSets().inAnyNamespace().list();

DaemonSetList dsList = client.apps().daemonSets().inNamespace("default").withLabel("foo", "bar").list();

Boolean isDeleted = client.apps().daemonSets().inNamespace("default").withName("ds1").delete();

client.apps().daemonSets().inNamespace("default").watch(new Watcher<DaemonSet>() {
  @Override
  public void eventReceived(Action action, DaemonSet resource) {
    // Do something depending upon action type
  }

  @Override
  public void onClose(KubernetesClientException cause) {

  }
});

PersistentVolumeClaim

PersistentVolumeClaim is available in Kubernetes Client API via client.persistentVolumeClaims(). Here are some examples of it's common usage:

PersistentVolumeClaim pvc = client.persistentVolumeClaims().load(new FileInputStream("pvc.yaml")).get();

PersistentVolumeClaim pvc = client.persistentVolumeClaims().inNamespace("default").withName("test-pv-claim").get();

PersistentVolumeClaim persistentVolumeClaim = new PersistentVolumeClaimBuilder()
  .withNewMetadata().withName("test-pv-claim").endMetadata()
  .withNewSpec()
  .withStorageClassName("my-local-storage")
  .withAccessModes("ReadWriteOnce")
  .withNewResources()
  .addToRequests("storage", new Quantity("500Gi"))
  .endResources()
  .endSpec()
  .build();

client.persistentVolumeClaims().inNamespace("default").create(persistentVolumeClaim);

PersistentVolumeClaim pvc = client.persistentVolumeClaims().inNamespace("default").createOrReplace(pvcToCreate);

PersistentVolumeClaim pvc = client.persistentVolumeClaims().inNamespace("default").createOrReplaceWithNew()
  .withNewMetadata().withName("test-pv-claim").endMetadata()
  .withNewSpec()
  .withStorageClassName("my-local-storage")
  .withAccessModes("ReadWriteOnce")
  .withNewResources()
  .addToRequests("storage", new Quantity("500Gi"))
  .endResources()
  .endSpec()
  .done();

PersistentVolumeClaimList pvcList = client.persistentVolumeClaims().inNamespace("default").list();

PersistentVolumeClaimList pvcList = client.persistentVolumeClaims().inAnyNamespace().list();

PersistentVolumeClaimList pvcList = client.persistentVolumeClaims().inNamespace("default").withLabel("foo", "bar").list();

Boolean isDeleted = client.persistentVolumeClaims().inNamespace("default").withName("test-pv-claim").delete();

PersistentVolume

PersistentVolume resource is available in Kubernetes Client API via client.persistentVolumes(). Here are some of the examples of it's common usage:

PersistentVolume pv = client.persistentVolumes().load(new FileInputStream("pv.yaml")).get();

PersistentVolume pv = client.persistentVolumes().withName("test-local-pv").get();

PersistentVolume pv = new PersistentVolumeBuilder()
  .withNewMetadata().withName("test-local-pv").endMetadata()
  .withNewSpec()
  .addToCapacity(Collections.singletonMap("storage", new Quantity("500Gi")))
  .withAccessModes("ReadWriteOnce")
  .withPersistentVolumeReclaimPolicy("Retain")
  .withStorageClassName("my-local-storage")
  .withNewLocal()
  .withPath("/mnt/disks/vol1")
  .endLocal()
  .withNewNodeAffinity()
  .withNewRequired()
  .addNewNodeSelectorTerm()
  .withMatchExpressions(Arrays.asList(new NodeSelectorRequirementBuilder()
    .withKey("kubernetes.io/hostname")
    .withOperator("In")
    .withValues("my-node")
    .build()
  ))
  .endNodeSelectorTerm()
  .endRequired()
  .endNodeAffinity()
  .endSpec()
  .build();

PersistentVolume pvCreated = client.persistentVolumes().create(pv)

PersistentVolume pv = client.persistentVolumes().createOrReplace(pvToCreate);

PersistentVolumeList pvList = client.persistentVolumes().list();

PersistentVolumeList pvList = client.persistentVolumes().withLabel("foo", "bar").list();

Boolean isDeleted = client.persistentVolumes().withName("test-local-pv").delete();

NetworkPolicy

NetworkPolicy is available in Kubernetes Client API via client.network().networkPolicies(). Here are some examples of it's common usages:

NetworkPolicy loadedNetworkPolicy = client.network().networkPolicies()
  .load(new FileInputStream("/test-networkpolicy.yml")).get();

NetworkPolicy getNetworkPolicy = client.network().networkPolicies()
  .withName("networkpolicy").get();

NetworkPolicy networkPolicy = new NetworkPolicyBuilder()
      .withNewMetadata()
      .withName("networkpolicy")
      .addToLabels("foo","bar")
      .endMetadata()
      .withNewSpec()
      .withNewPodSelector()
      .addToMatchLabels("role","db")
      .endPodSelector()
      .addToIngress(0,
        new NetworkPolicyIngressRuleBuilder()
        .addToFrom(0, new NetworkPolicyPeerBuilder().withNewPodSelector()
          .addToMatchLabels("role","frontend").endPodSelector()
          .build()
        ).addToFrom(1, new NetworkPolicyPeerBuilder().withNewNamespaceSelector()
          .addToMatchLabels("project","myproject").endNamespaceSelector()
            .build()
        )
        .addToPorts(0,new NetworkPolicyPortBuilder().withPort(new IntOrString(6379))
          .withProtocol("TCP").build())
        .build()
      )
      .endSpec()
      .build();

NetworkPolicy npCreated = client.network().networkPolicies().create(networkPolicy);

NetworkPolicy npCreated = client.network().networkPolicies().createOrReplace(networkPolicy);

NetworkPolicyList networkPolicyList = client.network().networkPolicies().list();

NetworkPolicyList networkPolicyList = client.network().networkPolicies()
  .withLabels(Collections.singletonMap("foo","bar")).list();

Boolean deleted = client.network().networkPolicies().withName("np-test").delete();

PodDisruptionBudget

PodDisruptionBudget is available in Kubernetes Client API via client.policy().podDisruptionBudget(). Here are some of the examples of its usage:

PodDisruptionBudget pdb = client.policy().podDisruptionBudget().load(new FileInputStream("/test-pdb.yml")).get();

PodDisruptionBudget podDisruptionBudget = client.policy().podDisruptionBudget().inNamespace("default").withName("poddisruptionbudget1").get();

PodDisruptionBudget podDisruptionBudget = new PodDisruptionBudgetBuilder()
    .withNewMetadata().withName("zk-pkb").endMetadata()
    .withNewSpec()
    .withMaxUnavailable(new IntOrString("1%"))
    .withNewSelector()
    .withMatchLabels(Collections.singletonMap("app", "zookeeper"))
    .endSelector()
    .endSpec()
    .build();

client.policy().podDisruptionBudget().inNamespace("default").create(podDisruptionBudget);

PodDisruptionBudget pdb = client.policy().podDisruptionBudget().inNamespace("default").createOrReplace(podDisruptionBudgetObj);

PodDisruptionBudgetList podDisruptionBudgetList = client.policy().podDisruptionBudget().inNamespace("default").list();

PodDisruptionBudgetList pdbList = client.policy().podDisruptionBudget().inAnyNamespace().list();

PodDisruptionBudgetList pdbList = client.policy().podDisruptionBudget().inNamespace("default").withLabel("foo", "bar").list();

Boolean deleted = client.policy().podDisruptionBudget().inNamespace("default").withName("poddisruptionbudget1").delete();

SelfSubjectAccessReview

try (KubernetesClient client = new DefaultKubernetesClient()) {
    SelfSubjectAccessReview ssar = new SelfSubjectAccessReviewBuilder()
            .withNewSpec()
            .withNewResourceAttributes()
            .withGroup("apps")
            .withResource("deployments")
            .withVerb("create")
            .withNamespace("dev")
            .endResourceAttributes()
            .endSpec()
            .build();

    ssar = client.authorization().v1().selfSubjectAccessReview().create(ssar);

    System.out.println("Allowed: "+  ssar.getStatus().getAllowed());
}

SubjectAccessReview

try (KubernetesClient client = new DefaultKubernetesClient()) {
    SubjectAccessReview sar = new SubjectAccessReviewBuilder()
            .withNewSpec()
            .withNewResourceAttributes()
            .withGroup("apps")
            .withResource("deployments")
            .withVerb("create")
            .withNamespace("default")
            .endResourceAttributes()
            .withUser("kubeadmin")
            .endSpec()
            .build();

    sar = client.authorization().v1().subjectAccessReview().create(sar);

    System.out.println("Allowed: "+  sar.getStatus().getAllowed());
}

LocalSubjectAccessReview

try (KubernetesClient client = new DefaultKubernetesClient()) {
    LocalSubjectAccessReview lsar = new LocalSubjectAccessReviewBuilder()
            .withNewMetadata().withNamespace("default").endMetadata()
            .withNewSpec()
            .withUser("foo")
            .withNewResourceAttributes()
            .withNamespace("default")
            .withVerb("get")
            .withGroup("apps")
            .withResource("pods")
            .endResourceAttributes()
            .endSpec()
            .build();
     lsar = client.authorization().v1().localSubjectAccessReview().inNamespace("default").create(lsar);
     System.out.println(lsar.getStatus().getAllowed());
}

SelfSubjectRulesReview

try (KubernetesClient client = new DefaultKubernetesClient()) {
    SelfSubjectRulesReview selfSubjectRulesReview = new SelfSubjectRulesReviewBuilder()
            .withNewMetadata().withName("foo").endMetadata()
            .withNewSpec()
            .withNamespace("default")
            .endSpec()
            .build();

    selfSubjectRulesReview = client.authorization().v1().selfSubjectRulesReview().create(selfSubjectRulesReview);
    System.out.println(selfSubjectRulesReview.getStatus().getIncomplete());
    System.out.println("non resource rules: " + selfSubjectRulesReview.getStatus().getNonResourceRules().size());
    System.out.println("resource rules: " + selfSubjectRulesReview.getStatus().getResourceRules().size());
}

参考文档

Fabric8 Kubernetes Java Client Cheat Sheet

上一篇下一篇

猜你喜欢

热点阅读