Kubernetes Java Client

repository·master·Indexed 26 days ago

https://github.com/kubernetes-client/java

A Java client library for interacting with Kubernetes clusters. It provides tools for managing Kubernetes resources, including strongly-typed Java models for Prometheus Operator and cert-manager CRDs. The library includes utilities for generating Java models from CustomResourceDefinitions (CRDs) via Docker or GitHub Actions, tools for rebuilding fluents using fluent-gen, and scripts for manual protocol buffer file generation.

Tokens
486.8K
Snippets
221
Records
399
Agent score
87%

What's inside kubernetes-client-java

  1. Understand the V1CSINode object

    master

    The V1CSINode object holds information about all Container Storage Interface (CSI) drivers installed on a specific node.

    Key behaviors:

    • Automatic Population: CSI drivers do not create this object directly. If a driver uses the node-driver-registrar sidecar container, the kubelet automatically populates the V1CSINode object during plugin registration.
    • Naming: The V1CSINode object shares the same name as its corresponding node.
    • Ownership: The object contains an OwnerReference pointing to the corresponding node object.
    • Missing Objects: If the object is missing, it indicates either that no CSI drivers are available on the node or that the kubelet version is too old to support this object creation.
  2. Add Prometheus Operator model classes to Maven project

    master

    To use the strongly-typed Java model classes for Prometheus Operator Custom Resources (CRDs) in your application, include the client-java-prometheus-operator-models dependency in your pom.xml. This allows you to perform CRUD operations on resources like Prometheus instances and Prometheus rules.

    <dependency>
        <groupId>io.kubernetes</groupId>
        <artifactId>client-java-prometheus-operator-models</artifactId>
        <version>0.38.1-SNAPSHOT</version>
    </dependency>
  3. Generate proto files using the kubernetes-client/gen repository

    master

    You can bypass the local scripts and use the dedicated kubernetes-client/gen repository to generate proto files directly into your Java client project. This requires cloning the gen repository and running its generation scripts, pointing the output to your local Java client's proto source directory.

    git clone https://github.com/kubernetes-client/gen
    cd gen/proto
    bash dependencies.sh master  # or specify a different branch
    bash generate.sh java ${PATH_TO_JAVA_CLIENT_ROOT}/proto/src/main/java/
  4. Configure Maven for Spring Boot Kubernetes Controller

    master

    When creating a new Maven project for a Kubernetes controller, include the following plugins in your pom.xml:

    1. Maven Compiler Plugin: Set the language level to 8.
    2. Spring Boot Maven Plugin: Used for building optimized Docker images.

    Additionally, add the client-java-spring-integration dependency (version 11.0.0 or higher is recommended) to enable auto-configuration for informer and reconciler beans.

    <!-- Maven Compiler Plugin -->
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <source>8</source>
            <target>8</target>
        </configuration>
    </plugin>
    
    <!-- Spring Boot Maven Plugin -->
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>2.3.4.RELEASE</version>
    </plugin>
    
    <!-- Spring Integration Dependency -->
    <dependency>
    	<groupId>io.kubernetes</groupId>
    	<artifactId>client-java-spring-integration</artifactId>
    	<version>${ >= 11.0.0 recommended}</version>
    </dependency>
  5. Generate Java models via GitHub Action

    master

    To use the remote generation method:

    1. Fork the repository: Fork kubernetes-client/java to your own account. This allows you to run the CRD Java Model Generate workflow.
    2. Execute the Action: In your forked repository, navigate to the Actions tab, find the "CRD Java Model Generate" workflow, and run it.
    3. Download Sources: Once the workflow completes, go to the execution Summary page and download the zip-archived Java sources from the bottom of the page.
  6. Register custom models for API discovery

    master

    To allow the Java client to recognize Custom Resource Definitions (CRDs) or extended API servers, you must manually map the Kubernetes API group, version, and kind to your custom Java model using ModelMapper.addModelMap.

    ModelMapper.addModelMap(
      "example.io",  // api-group
      "v1",          // api-version
      "Foo",         // kind name -- camel-case'd singular resource name.
      "foos",        // resource name -- lowercase plural resource name
      true,          // is namespace-scoped
      Foo.class);    // java model class
  7. Generate Prometheus Operator model classes

    master

    If you need to regenerate the model classes from CRDs, use the provided update.sh utility script.

    Prerequisites:

    • Docker must be installed on the host.

    Steps:

    1. Navigate to the prometheus-operator directory.
    2. Execute the update script:
    ./update.sh

    The script generates classes from the CRDs at the URL specified by the -u option within the script. To target a different version of the CRDs, update the -u option in update.sh before running it.

  8. Run a Kubernetes Reconciler

    master

    To start your controller, you must stitch the SharedInformerFactory and the Reconciler together. For versions >= 11.0.0, you should create a KubernetesControllerFactory bean.

    Then, use one of the following patterns to trigger execution (typically within an InitializingBean or CommandLineRunner):

    1. Immediate Run: Call sharedInformerFactory.startAllRegisteredInformers() and submit the controller to an executor.
    2. ControllerManager: Wrap the factory and reconciler in a ControllerManager and submit it to an executor.
    3. High Availability (HA): Use a LeaderElector with an EndpointsLock to run the ControllerManager only when the instance holds the leader lock.
    // Example: Creating the Controller Factory (Required for >= 11.0.0)
    @Configuration
    public class MyConfiguration {
        @Bean
        public KubernetesControllerFactory replicasetController(
            SharedInformerFactory sharedInformerFactory,
            Reconciler reconciler) {
          return new KubernetesControllerFactory(sharedInformerFactory, reconciler);
        }
    }
    
    // Example: Running the controller via ControllerManager
    @Component
    public class ControllerStarter implements InitializingBean {
        @Resource
        private SharedInformerFactory sharedInformerFactory;
    
        @Resource(name = "replicaset-reconciler")
        private Controller replicasetController;
    
        @Override
        public void afterPropertiesSet() throws Exception {
            ControllerManager controllerManager = new ControllerManager(sharedInformerFactory, replicasetController);
            Executors.newSingleThreadExecutor().submit(controllerManager);
        }
    }
  9. Rebuild fluents using the fluent-gen tool

    master

    To rebuild the fluents in a clean environment, follow these steps sequentially:

    1. Clean Environment: Start from a completely clean environment (e.g., a fresh VM) and clone the repository.
    2. Install fluent-gen: Run the Maven command with the fluent-gen profile to install the generator.
    3. Generate Fluents: Navigate to the fluent-gen directory and execute the generation script.
    4. Restore POM: Comment the generator modules back into the pom.xml file.
    5. Install Project: Run a standard Maven install to complete the process.
  10. Trigger automated proto and OpenAPI generation via GitHub Actions

    master

    Protocol buffer files, OpenAPI client code, and fluent APIs are automatically generated during new Kubernetes releases via GitHub Actions. You can manually trigger this full generation workflow (which includes applying patches and creating a pull request) by following these steps:

    1. Navigate to the Generate workflow in GitHub Actions.
    2. Click "Run workflow".
    3. Specify the desired Kubernetes branch (e.g., release-1.30 or master).