Java client for Kubernetes and OpenShift providing access to the full Kubernetes & OpenShift REST APIs via a fluent DSL
npx @tessl/cli install tessl/maven-io-fabric8--kubernetes-client@7.3.0A comprehensive Java client library for Kubernetes and OpenShift that provides fluent DSL access to the full Kubernetes & OpenShift REST APIs. The library offers type-safe operations for all standard Kubernetes resources, custom resource support, informer patterns for real-time monitoring, and extensible architecture for additional functionality.
<dependency>
<groupId>io.fabric8</groupId>
<artifactId>kubernetes-client</artifactId>
<version>7.3.1</version>
</dependency>import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientBuilder;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.ConfigBuilder;import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientBuilder;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodList;
// Create client with default configuration
try (KubernetesClient client = new KubernetesClientBuilder().build()) {
// List all pods in default namespace
PodList podList = client.pods().list();
System.out.println("Found " + podList.getItems().size() + " pods");
// Get a specific pod
Pod pod = client.pods().withName("my-pod").get();
if (pod != null) {
System.out.println("Pod status: " + pod.getStatus().getPhase());
}
// Create a new pod
Pod newPod = client.pods().create(new PodBuilder()
.withNewMetadata()
.withName("example-pod")
.withNamespace("default")
.endMetadata()
.withNewSpec()
.addNewContainer()
.withName("app")
.withImage("nginx:latest")
.endContainer()
.endSpec()
.build());
}The Fabric8 Kubernetes Client is built around several key architectural components:
KubernetesClient provides the main entry point with fluent DSL methods for all Kubernetes operationsConfig class handles authentication, connection settings, and cluster configuration with auto-discoveryMixedOperation, Resource, etc.) provide type-safe, fluent API operationsConfiguration options for connecting to Kubernetes clusters, including authentication, timeouts, and connection settings. Supports auto-discovery from kubeconfig files and environment variables.
public interface KubernetesClient extends Client {
// Configuration and lifecycle
Config getConfiguration();
String getMasterUrl();
void close();
// Core resource operations (core/v1)
MixedOperation<Pod, PodList, PodResource> pods();
MixedOperation<Service, ServiceList, ServiceResource<Service>> services();
NonNamespaceOperation<Namespace, NamespaceList, Resource<Namespace>> namespaces();
NonNamespaceOperation<Node, NodeList, Resource<Node>> nodes();
MixedOperation<ConfigMap, ConfigMapList, Resource<ConfigMap>> configMaps();
MixedOperation<Secret, SecretList, Resource<Secret>> secrets();
// API groups
AppsAPIGroupDSL apps();
BatchAPIGroupDSL batch();
RbacAPIGroupDSL rbac();
NetworkAPIGroupDSL network();
StorageAPIGroupDSL storage();
ApiextensionsAPIGroupDSL apiextensions();
// Generic resource operations
<T extends HasMetadata> MixedOperation<T, KubernetesResourceList<T>, Resource<T>> resources(Class<T> resourceType);
MixedOperation<GenericKubernetesResource, GenericKubernetesResourceList, Resource<GenericKubernetesResource>>
genericKubernetesResources(String apiVersion, String kind);
// Resource loading and management
NamespaceListVisitFromServerGetDeleteRecreateWaitApplicable<HasMetadata> load(InputStream is);
<T extends HasMetadata> NamespaceableResource<T> resource(T resource);
// Informers and watching
SharedInformerFactory informers();
// Version information
VersionInfo getKubernetesVersion();
}
public class KubernetesClientBuilder {
public KubernetesClientBuilder withConfig(Config config);
public KubernetesClient build();
}
public class Config {
// Factory methods
public static Config empty();
public static Config autoConfigure(String context);
public static Config fromKubeconfig(String kubeconfigContents);
public static Config fromKubeconfig(File kubeconfigFile);
public static Config fromKubeconfig(String context, File kubeconfig);
public static ConfigBuilder builder();
// Core configuration access
public String getMasterUrl();
public String getNamespace();
public String getOauthToken();
// Configuration management
public Config refresh();
public File getFile();
public List<NamedContext> getContexts();
public NamedContext getCurrentContext();
}Fundamental CRUD operations for standard Kubernetes resources like Pods, Services, ConfigMaps, and Secrets. Provides fluent DSL for creating, reading, updating, and deleting resources.
public interface MixedOperation<T extends HasMetadata, L extends KubernetesResourceList<T>, R extends Resource<T>>
extends NonNamespaceOperation<T, L, R> {
// Namespace scoping
NonNamespaceOperation<T, L, R> inNamespace(String namespace);
NonNamespaceOperation<T, L, R> inAnyNamespace();
}
public interface NonNamespaceOperation<T extends HasMetadata, L extends KubernetesResourceList<T>, R extends Resource<T>> {
// Resource selection
R withName(String name);
// Filtering and querying
FilterWatchListDeletable<T, L, R> withLabels(Map<String, String> labels);
FilterWatchListDeletable<T, L, R> withLabel(String key, String value);
FilterWatchListDeletable<T, L, R> withLabelSelector(LabelSelector selector);
FilterWatchListDeletable<T, L, R> withField(String key, String value);
// List operations
L list();
L list(ListOptions listOptions);
// Watch operations
Watch watch(Watcher<T> watcher);
Watch watch(ListOptions options, Watcher<T> watcher);
// Wait operations
T waitUntilReady(long amount, TimeUnit timeUnit);
T waitUntilCondition(Predicate<T> condition, long amount, TimeUnit timeUnit);
// Delete operations
List<StatusDetails> delete();
// Informer operations
SharedIndexInformer<T> inform();
SharedIndexInformer<T> inform(ResourceEventHandler<? super T> handler);
}
public interface Resource<T extends HasMetadata> {
// Get operations
T get();
// CRUD operations
T create();
T update();
T patch(String patch);
T patch(PatchContext patchContext, String patch);
List<StatusDetails> delete();
// Edit and modify operations
T edit(UnaryOperator<T> function);
T accept(Consumer<T> function);
T updateStatus();
T patchStatus();
// Server-side apply
T serverSideApply();
ServerSideApplicable<T> fieldManager(String manager);
// Watch operations
Watch watch(Watcher<T> watcher);
// Wait operations
T waitUntilReady(long amount, TimeUnit timeUnit);
T waitUntilCondition(Predicate<T> condition, long amount, TimeUnit timeUnit);
// Scale operations (for scalable resources)
T scale(int count);
Scale scale();
// Status and utility
boolean isReady();
T require() throws ResourceNotFoundException;
ReplaceDeletable<T> lockResourceVersion();
T item();
// Informer operations
SharedIndexInformer<T> inform();
SharedIndexInformer<T> inform(ResourceEventHandler<? super T> handler);
}Access to specialized Kubernetes API groups including Apps (Deployments, StatefulSets), Batch (Jobs, CronJobs), Networking, Storage, and RBAC resources.
public interface AppsAPIGroupDSL {
MixedOperation<Deployment, DeploymentList, RollableScalableResource<Deployment>> deployments();
MixedOperation<StatefulSet, StatefulSetList, RollableScalableResource<StatefulSet>> statefulSets();
MixedOperation<DaemonSet, DaemonSetList, Resource<DaemonSet>> daemonSets();
MixedOperation<ReplicaSet, ReplicaSetList, RollableScalableResource<ReplicaSet>> replicaSets();
}
public interface BatchAPIGroupDSL {
MixedOperation<Job, JobList, ScalableResource<Job>> jobs();
MixedOperation<CronJob, CronJobList, Resource<CronJob>> cronJobs();
}Support for Custom Resource Definitions (CRDs) and dynamic resource operations. Enables type-safe operations on custom resources and generic resource manipulation.
public interface KubernetesClient {
<T extends HasMetadata> MixedOperation<T, KubernetesResourceList<T>, Resource<T>>
resources(Class<T> resourceType);
MixedOperation<GenericKubernetesResource, GenericKubernetesResourceList, Resource<GenericKubernetesResource>>
genericKubernetesResources(String apiVersion, String kind);
MixedOperation<GenericKubernetesResource, GenericKubernetesResourceList, Resource<GenericKubernetesResource>>
genericKubernetesResources(ResourceDefinitionContext context);
}
public class CustomResource<T, S> implements HasMetadata {
public T getSpec();
public void setSpec(T spec);
public S getStatus();
public void setStatus(S status);
}Real-time monitoring of Kubernetes resources with watch operations and informer patterns. Provides efficient caching and event-driven resource updates.
public interface SharedInformerFactory {
<T extends HasMetadata> SharedIndexInformer<T> sharedIndexInformerFor(
Class<T> apiTypeClass, long resyncPeriodInMillis);
void startAllRegisteredInformers();
void stopAllRegisteredInformers();
}
public interface SharedIndexInformer<T> {
void addEventHandler(ResourceEventHandler<T> handler);
Indexer<T> getIndexer();
void run();
void stop();
boolean hasSynced();
}
public interface ResourceEventHandler<T> {
void onAdd(T obj);
void onUpdate(T oldObj, T newObj);
void onDelete(T obj, boolean deletedFinalStateUnknown);
}Specialized operations for Pods including log streaming, command execution, port forwarding, and file operations.
public interface PodResource extends Resource<Pod> {
String log();
String log(PodLogOptions options);
ExecWatch exec(String... command);
LocalPortForward portForward(int port);
Boolean upload(Path pathToUpload);
Boolean copy(Path source, Path destination);
Pod attach();
}
public interface ExecWatch extends Closeable {
OutputStream getInput();
InputStream getOutput();
InputStream getError();
void resize(int cols, int rows);
}Comprehensive exception hierarchy for handling Kubernetes API errors, timeouts, and resource-specific exceptions.
public class KubernetesClientException extends RuntimeException {
public Status getStatus();
public int getCode();
public String getFullResourceName();
public static KubernetesClientException launderThrowable(Throwable cause);
}
public class ResourceNotFoundException extends KubernetesClientException {
public ResourceNotFoundException(String message);
}
public class KubernetesClientTimeoutException extends KubernetesClientException {
public KubernetesClientTimeoutException(String message, long timeout, TimeUnit timeUnit);
}Utilities for serializing and deserializing Kubernetes resources, resource manipulation, and common operations.
public class KubernetesSerialization {
public ObjectMapper jsonMapper();
public ObjectMapper yamlMapper();
public <T> T unmarshal(String str);
public <T> T unmarshal(String str, Class<T> type);
public <T> T unmarshal(InputStream is);
}
public class KubernetesResourceUtil {
public static String getName(HasMetadata resource);
public static String getNamespace(HasMetadata resource);
public static String getResourceVersion(HasMetadata resource);
public static boolean isResourceReady(HasMetadata resource);
}