【问题标题】:How to create Job in Kubernetes using Java API如何使用 Java API 在 Kubernetes 中创建作业
【发布时间】:2021-05-23 01:05:33
【问题描述】:

能够使用 CLI 在 Kubernetes 集群中创建作业 (https://kubernetesbyexample.com/jobs/)

有没有办法使用 Java API 在集群内创建作业?

【问题讨论】:

    标签: kubernetes kubectl azure-aks


    【解决方案1】:

    您可以使用 Kubernetes Java Client 创建任何对象,例如 Job。参考例子here

    /*
     * Creates a simple run to complete job that computes π to 2000 places and prints it out.
     */
    public class JobExample {
        private static final Logger logger = LoggerFactory.getLogger(JobExample.class);
    
        public static void main(String[] args) {
            final ConfigBuilder configBuilder = new ConfigBuilder();
            if (args.length > 0) {
              configBuilder.withMasterUrl(args[0]);
            }
            try (KubernetesClient client = new DefaultKubernetesClient(configBuilder.build())) {
              final String namespace = "default";
              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();
    
              logger.info("Creating job pi.");
              client.batch().jobs().inNamespace(namespace).createOrReplace(job);
    
              // Get All pods created by the job
              PodList podList = client.pods().inNamespace(namespace).withLabel("job-name", job.getMetadata().getName()).list();
              // Wait for pod to complete
              client.pods().inNamespace(namespace).withName(podList.getItems().get(0).getMetadata().getName())
                .waitUntilCondition(pod -> pod.getStatus().getPhase().equals("Succeeded"), 1, TimeUnit.MINUTES);
    
              // Print Job's log
              String joblog = client.batch().jobs().inNamespace(namespace).withName("pi").getLog();
              logger.info(joblog);
    
            } catch (KubernetesClientException e) {
                logger.error("Unable to create job", e);
            } catch (InterruptedException interruptedException) {
              logger.warn("Thread interrupted!");
              Thread.currentThread().interrupt();
            }
        }
    }
    

    【讨论】:

    • fabric8 已弃用 ryt ?有没有其他方法,或者我们可以使用 kubernetes API
    • fabric8 没有被弃用..或者你可以使用官方的 kubernetes java 客户端github.com/kubernetes-client/java
    【解决方案2】:

    如果您想使用集群内部的静态清单 yaml 启动作业,使用官方库应该很容易。 这段代码对我有用。

    ApiClient client = ClientBuilder.cluster().build(); //create in-cluster client
    Configuration.setDefaultApiClient(client);
    BatchV1Api api = new BatchV1Api(client);
        
    V1Job job = new V1Job();
    job = (V1Job) Yaml.load(new File("/tmp/template.yaml")); //load static yaml file
            
    ApiResponse<V1Job> response = api.createNamespacedJobWithHttpInfo("default", job, "true", null, null);
    
    

    您还可以在启动作业之前使用getter和setter的组合修改作业的任何信息。

    // set metadata-name
    job.getMetadata().setName("newName");
        
    // set spec-template-metadata-name
    job.getSpec().getTemplate().getMetadata().setName("newName");
    

    【讨论】:

    • 请注意,此集群内客户端仅在具有相应 ServiceAccount 以创建 Job 的 Pod 内工作。
    猜你喜欢
    • 2018-11-03
    • 2022-10-13
    • 1970-01-01
    • 2021-10-24
    • 2018-08-24
    • 2021-07-13
    • 2021-06-02
    • 1970-01-01
    • 2019-06-05
    相关资源
    最近更新 更多