CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-io-fabric8--kubernetes-client

Java client for Kubernetes and OpenShift providing access to the full Kubernetes & OpenShift REST APIs via a fluent DSL

Pending
Overview
Eval results
Files

utilities.mddocs/

Utilities

The Fabric8 Kubernetes Client provides various utility classes and methods for serialization, resource manipulation, and common operations. These utilities simplify working with Kubernetes resources and client functionality.

Serialization Utilities

KubernetesSerialization Class

Utilities for serializing and deserializing Kubernetes resources.

public class KubernetesSerialization {
    // ObjectMapper access
    public ObjectMapper jsonMapper();
    public ObjectMapper yamlMapper();
    
    // Unmarshaling (deserialization)
    public <T> T unmarshal(String str);
    public <T> T unmarshal(String str, Class<T> type);
    public <T> T unmarshal(String str, TypeReference<T> type);
    public <T> T unmarshal(InputStream is);
    public <T> T unmarshal(InputStream is, Class<T> type);
    public <T> T unmarshal(InputStream is, TypeReference<T> type);
    
    // Marshaling (serialization)
    public String asJson(Object object);
    public String asYaml(Object object);
    public void marshal(Object object, OutputStream os);
    
    // Clone operations
    public <T> T clone(T object);
    
    // Conversion
    public <T> T convertValue(Object fromValue, Class<T> toValueType);
    public <T> T convertValue(Object fromValue, TypeReference<T> toValueType);
}

// Access via client
public interface KubernetesClient {
    KubernetesSerialization getKubernetesSerialization();
}

Resource Utilities

KubernetesResourceUtil Class

Utilities for working with Kubernetes resources.

public class KubernetesResourceUtil {
    // Resource identification
    public static String getName(HasMetadata resource);
    public static String getNamespace(HasMetadata resource);  
    public static String getResourceVersion(HasMetadata resource);
    public static String getUid(HasMetadata resource);
    public static String getKind(HasMetadata resource);
    public static String getApiVersion(HasMetadata resource);
    
    // Resource status
    public static boolean isResourceReady(HasMetadata resource);
    public static String getResourceStatus(HasMetadata resource);
    
    // Owner references
    public static String getControllerUid(HasMetadata resource);
    public static List<OwnerReference> getOwnerReferences(HasMetadata resource);
    public static boolean isOwnedBy(HasMetadata resource, HasMetadata owner);
    
    // Labels and annotations
    public static Map<String, String> getLabels(HasMetadata resource);
    public static Map<String, String> getAnnotations(HasMetadata resource);
    public static String getLabel(HasMetadata resource, String key);
    public static String getAnnotation(HasMetadata resource, String key);
    
    // Utility methods
    public static boolean isNamespaced(HasMetadata resource);
    public static String getFullResourceName(HasMetadata resource);
    public static boolean hasOwnerReference(HasMetadata resource);
}

Utils Class

General utility methods for the client.

public class Utils {
    // String utilities
    public static boolean isNullOrEmpty(String str);
    public static boolean isNotNullOrEmpty(String str);
    public static String join(Collection<String> list, String separator);
    public static String join(String[] array, String separator);
    
    // Resource waiting
    public static boolean waitUntilReady(HasMetadata resource, long amount, TimeUnit timeUnit);
    public static boolean isResourceInFinalState(HasMetadata resource);
    
    // System utilities
    public static String getSystemPropertyOrEnvVar(String systemPropertyKey, String envVarKey);
    public static String getSystemPropertyOrEnvVar(String key);
    
    // Validation
    public static void checkNotNull(Object reference, String errorMessage);
    public static void checkArgument(boolean expression, String errorMessage);
    
    // File utilities
    public static String readFile(String path);
    public static Properties loadProperties(String path);
}

Usage Examples

JSON and YAML Serialization

KubernetesSerialization serialization = client.getKubernetesSerialization();

// Create a pod
Pod pod = new PodBuilder()
    .withNewMetadata()
        .withName("example-pod")
        .withLabels(Map.of("app", "example"))
    .endMetadata()
    .withNewSpec()
        .addNewContainer()
            .withName("app")
            .withImage("nginx:latest")
        .endContainer()
    .endSpec()
    .build();

// Serialize to JSON
String jsonString = serialization.asJson(pod);
System.out.println("Pod as JSON:\n" + jsonString);

// Serialize to YAML
String yamlString = serialization.asYaml(pod);
System.out.println("Pod as YAML:\n" + yamlString);

// Write to file
try (FileOutputStream fos = new FileOutputStream("pod.yaml")) {
    serialization.marshal(pod, fos);
}

Deserializing Resources

KubernetesSerialization serialization = client.getKubernetesSerialization();

// Deserialize from JSON string
String jsonPod = "{ \"apiVersion\": \"v1\", \"kind\": \"Pod\", ... }";
Pod podFromJson = serialization.unmarshal(jsonPod, Pod.class);

// Deserialize from YAML string
String yamlPod = """
    apiVersion: v1
    kind: Pod
    metadata:
      name: yaml-pod
    spec:
      containers:
      - name: app
        image: nginx:latest
    """;
Pod podFromYaml = serialization.unmarshal(yamlPod, Pod.class);

// Deserialize from file
try (FileInputStream fis = new FileInputStream("pod.yaml")) {
    Pod podFromFile = serialization.unmarshal(fis, Pod.class);
    System.out.println("Loaded pod: " + podFromFile.getMetadata().getName());
}

// Generic deserialization (auto-detect type)
HasMetadata genericResource = serialization.unmarshal(yamlPod);
System.out.println("Resource type: " + genericResource.getKind());

// Deserialize list of resources
String yamlList = """
    apiVersion: v1
    kind: List
    items:
    - apiVersion: v1
      kind: Pod
      metadata:
        name: pod1
    - apiVersion: v1
      kind: Service
      metadata:
        name: service1
    """;

KubernetesList resourceList = serialization.unmarshal(yamlList, KubernetesList.class);
for (HasMetadata item : resourceList.getItems()) {
    System.out.println("Item: " + item.getKind() + "/" + item.getMetadata().getName());
}

Resource Manipulation Utilities

// Get resource information
Pod pod = client.pods().withName("my-pod").get();

if (pod != null) {
    // Basic information
    String name = KubernetesResourceUtil.getName(pod);
    String namespace = KubernetesResourceUtil.getNamespace(pod);
    String uid = KubernetesResourceUtil.getUid(pod);
    String resourceVersion = KubernetesResourceUtil.getResourceVersion(pod);
    
    System.out.println("Pod: " + name + " in namespace: " + namespace);
    System.out.println("UID: " + uid);
    System.out.println("Resource Version: " + resourceVersion);
    
    // Check if ready
    boolean isReady = KubernetesResourceUtil.isResourceReady(pod);
    System.out.println("Pod ready: " + isReady);
    
    // Get full resource name
    String fullName = KubernetesResourceUtil.getFullResourceName(pod);
    System.out.println("Full name: " + fullName); // namespace/name
    
    // Labels and annotations
    Map<String, String> labels = KubernetesResourceUtil.getLabels(pod);
    Map<String, String> annotations = KubernetesResourceUtil.getAnnotations(pod);
    
    System.out.println("Labels: " + labels);
    System.out.println("Annotations: " + annotations);
    
    // Specific label/annotation
    String appLabel = KubernetesResourceUtil.getLabel(pod, "app");
    String createdByAnnotation = KubernetesResourceUtil.getAnnotation(pod, "created-by");
    
    // Owner references
    List<OwnerReference> owners = KubernetesResourceUtil.getOwnerReferences(pod);
    if (!owners.isEmpty()) {
        for (OwnerReference owner : owners) {
            System.out.println("Owned by: " + owner.getKind() + "/" + owner.getName());
        }
        
        String controllerUid = KubernetesResourceUtil.getControllerUid(pod);
        System.out.println("Controller UID: " + controllerUid);
    }
}

Resource Cloning and Conversion

KubernetesSerialization serialization = client.getKubernetesSerialization();

// Clone a resource
Pod originalPod = client.pods().withName("original-pod").get();
Pod clonedPod = serialization.clone(originalPod);

// Modify the clone
clonedPod.getMetadata().setName("cloned-pod");
clonedPod.getMetadata().setResourceVersion(null); // Clear resource version
clonedPod.getMetadata().setUid(null); // Clear UID

// Create the cloned resource
Pod createdClone = client.pods().create(clonedPod);

// Convert between resource types (if compatible)
GenericKubernetesResource generic = serialization.convertValue(originalPod, GenericKubernetesResource.class);
System.out.println("Converted to generic: " + generic.getKind());

// Convert back
Pod convertedBack = serialization.convertValue(generic, Pod.class);

String and Collection Utilities

// String utilities
String value = Utils.getSystemPropertyOrEnvVar("MY_CONFIG", "DEFAULT_VALUE");
System.out.println("Config value: " + value);

// Check for null or empty
if (Utils.isNotNullOrEmpty(value)) {
    System.out.println("Value is valid: " + value);
}

// Join collections
List<String> podNames = Arrays.asList("pod1", "pod2", "pod3");
String joinedNames = Utils.join(podNames, ", ");
System.out.println("Pod names: " + joinedNames);

// Join arrays
String[] containerNames = {"app", "sidecar", "init"};
String joinedContainers = Utils.join(containerNames, " | ");
System.out.println("Containers: " + joinedContainers);

// Validation utilities
Utils.checkNotNull(client, "Kubernetes client cannot be null");
Utils.checkArgument(podNames.size() > 0, "Pod list cannot be empty");

Resource Waiting Utilities

// Wait for resource to be ready
Pod pod = client.pods().withName("slow-starting-pod").get();

if (pod != null) {
    boolean becameReady = Utils.waitUntilReady(pod, 2, TimeUnit.MINUTES);
    
    if (becameReady) {
        System.out.println("Pod became ready");
    } else {
        System.out.println("Pod did not become ready within timeout");
    }
    
    // Check if resource is in final state
    boolean inFinalState = Utils.isResourceInFinalState(pod);
    System.out.println("Pod in final state: " + inFinalState);
}

File and Configuration Utilities

// Read configuration file
String configContent = Utils.readFile("/path/to/config.yaml");
System.out.println("Config content:\n" + configContent);

// Load properties
Properties props = Utils.loadProperties("application.properties");
String dbUrl = props.getProperty("database.url");

// Environment variable handling
String kubeconfig = Utils.getSystemPropertyOrEnvVar("kubeconfig", "KUBECONFIG");
if (Utils.isNotNullOrEmpty(kubeconfig)) {
    System.out.println("Using kubeconfig: " + kubeconfig);
}

// System property with fallback to environment variable
String logLevel = Utils.getSystemPropertyOrEnvVar("log.level", "LOG_LEVEL", "INFO");
System.out.println("Log level: " + logLevel);

Owner Reference Utilities

// Check ownership relationships
Deployment deployment = client.apps().deployments().withName("my-app").get();
ReplicaSet replicaSet = client.apps().replicaSets().withName("my-app-12345").get();

if (deployment != null && replicaSet != null) {
    // Check if ReplicaSet is owned by Deployment
    boolean isOwned = KubernetesResourceUtil.isOwnedBy(replicaSet, deployment);
    System.out.println("ReplicaSet owned by Deployment: " + isOwned);
    
    // Get all owner references
    List<OwnerReference> owners = KubernetesResourceUtil.getOwnerReferences(replicaSet);
    for (OwnerReference owner : owners) {
        System.out.println("Owner: " + owner.getKind() + "/" + owner.getName() + 
                          " (Controller: " + owner.getController() + ")");
    }
}

// Find resources owned by a specific resource
String deploymentUid = deployment.getMetadata().getUid();
List<ReplicaSet> ownedReplicaSets = client.apps().replicaSets().list().getItems().stream()
    .filter(rs -> KubernetesResourceUtil.getOwnerReferences(rs).stream()
        .anyMatch(owner -> deploymentUid.equals(owner.getUid())))
    .collect(Collectors.toList());

System.out.println("ReplicaSets owned by deployment: " + ownedReplicaSets.size());

Custom Resource Utilities

// Working with custom resources using utilities
HasMetadata customResource = client.genericKubernetesResources("example.com/v1", "Database")
    .withName("my-database").get();

if (customResource != null) {
    // All utilities work with custom resources too
    String name = KubernetesResourceUtil.getName(customResource);
    String namespace = KubernetesResourceUtil.getNamespace(customResource);
    boolean isReady = KubernetesResourceUtil.isResourceReady(customResource);
    
    System.out.println("Custom resource: " + name);
    System.out.println("Namespace: " + namespace);
    System.out.println("Ready: " + isReady);
    
    // Serialize custom resource
    KubernetesSerialization serialization = client.getKubernetesSerialization();
    String yaml = serialization.asYaml(customResource);
    System.out.println("Custom resource YAML:\n" + yaml);
}

Resource Template Processing

public class ResourceTemplateProcessor {
    
    private final KubernetesSerialization serialization;
    
    public ResourceTemplateProcessor(KubernetesClient client) {
        this.serialization = client.getKubernetesSerialization();
    }
    
    public HasMetadata processTemplate(String template, Map<String, String> variables) {
        // Replace variables in template
        String processedTemplate = template;
        for (Map.Entry<String, String> var : variables.entrySet()) {
            processedTemplate = processedTemplate.replace("${" + var.getKey() + "}", var.getValue());
        }
        
        // Deserialize the processed template
        return serialization.unmarshal(processedTemplate);
    }
    
    public List<HasMetadata> processMultiResourceTemplate(String template, Map<String, String> variables) {
        String processedTemplate = template;
        for (Map.Entry<String, String> var : variables.entrySet()) {
            processedTemplate = processedTemplate.replace("${" + var.getKey() + "}", var.getValue());
        }
        
        // Handle both single resources and lists
        try {
            KubernetesList list = serialization.unmarshal(processedTemplate, KubernetesList.class);
            return list.getItems();
        } catch (Exception e) {
            // Single resource
            HasMetadata single = serialization.unmarshal(processedTemplate);
            return Collections.singletonList(single);
        }
    }
}

// Usage
ResourceTemplateProcessor processor = new ResourceTemplateProcessor(client);

String podTemplate = """
    apiVersion: v1
    kind: Pod
    metadata:
      name: ${POD_NAME}
      labels:
        app: ${APP_NAME}
    spec:
      containers:
      - name: ${CONTAINER_NAME}
        image: ${IMAGE}
    """;

Map<String, String> variables = Map.of(
    "POD_NAME", "generated-pod",
    "APP_NAME", "my-app",
    "CONTAINER_NAME", "main",
    "IMAGE", "nginx:latest"
);

HasMetadata processedPod = processor.processTemplate(podTemplate, variables);
Pod createdPod = client.resource(processedPod).create();

Install with Tessl CLI

npx tessl i tessl/maven-io-fabric8--kubernetes-client

docs

api-groups.md

client-configuration.md

core-resources.md

custom-resources.md

exception-handling.md

index.md

pod-operations.md

utilities.md

watch-informers.md

tile.json