0
# Fabric8 Kubernetes Client
1
2
A 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.
3
4
## Package Information
5
6
- **Package Name**: kubernetes-client
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Installation**:
10
```xml
11
<dependency>
12
<groupId>io.fabric8</groupId>
13
<artifactId>kubernetes-client</artifactId>
14
<version>7.3.1</version>
15
</dependency>
16
```
17
18
## Core Imports
19
20
```java
21
import io.fabric8.kubernetes.client.KubernetesClient;
22
import io.fabric8.kubernetes.client.KubernetesClientBuilder;
23
import io.fabric8.kubernetes.client.Config;
24
import io.fabric8.kubernetes.client.ConfigBuilder;
25
```
26
27
## Basic Usage
28
29
```java
30
import io.fabric8.kubernetes.client.KubernetesClient;
31
import io.fabric8.kubernetes.client.KubernetesClientBuilder;
32
import io.fabric8.kubernetes.api.model.Pod;
33
import io.fabric8.kubernetes.api.model.PodList;
34
35
// Create client with default configuration
36
try (KubernetesClient client = new KubernetesClientBuilder().build()) {
37
// List all pods in default namespace
38
PodList podList = client.pods().list();
39
System.out.println("Found " + podList.getItems().size() + " pods");
40
41
// Get a specific pod
42
Pod pod = client.pods().withName("my-pod").get();
43
if (pod != null) {
44
System.out.println("Pod status: " + pod.getStatus().getPhase());
45
}
46
47
// Create a new pod
48
Pod newPod = client.pods().create(new PodBuilder()
49
.withNewMetadata()
50
.withName("example-pod")
51
.withNamespace("default")
52
.endMetadata()
53
.withNewSpec()
54
.addNewContainer()
55
.withName("app")
56
.withImage("nginx:latest")
57
.endContainer()
58
.endSpec()
59
.build());
60
}
61
```
62
63
## Architecture
64
65
The Fabric8 Kubernetes Client is built around several key architectural components:
66
67
- **Client Interface**: `KubernetesClient` provides the main entry point with fluent DSL methods for all Kubernetes operations
68
- **Configuration System**: `Config` class handles authentication, connection settings, and cluster configuration with auto-discovery
69
- **DSL Operations**: Hierarchical DSL interfaces (`MixedOperation`, `Resource`, etc.) provide type-safe, fluent API operations
70
- **API Group Support**: Dedicated DSL interfaces for each Kubernetes API group (apps, batch, networking, etc.)
71
- **Resource Model**: Strongly typed Java classes for all Kubernetes resources with builder patterns
72
- **HTTP Abstraction**: Pluggable HTTP client layer supporting multiple implementations (OkHttp, Jetty, Vert.x, JDK)
73
- **Watch & Informers**: Real-time resource monitoring with caching and event handling
74
- **Extension Framework**: Adapter pattern for custom resource types and client extensions
75
76
## Capabilities
77
78
### Client Configuration and Initialization
79
80
Configuration options for connecting to Kubernetes clusters, including authentication, timeouts, and connection settings. Supports auto-discovery from kubeconfig files and environment variables.
81
82
```java { .api }
83
public interface KubernetesClient extends Client {
84
// Configuration and lifecycle
85
Config getConfiguration();
86
String getMasterUrl();
87
void close();
88
89
// Core resource operations (core/v1)
90
MixedOperation<Pod, PodList, PodResource> pods();
91
MixedOperation<Service, ServiceList, ServiceResource<Service>> services();
92
NonNamespaceOperation<Namespace, NamespaceList, Resource<Namespace>> namespaces();
93
NonNamespaceOperation<Node, NodeList, Resource<Node>> nodes();
94
MixedOperation<ConfigMap, ConfigMapList, Resource<ConfigMap>> configMaps();
95
MixedOperation<Secret, SecretList, Resource<Secret>> secrets();
96
97
// API groups
98
AppsAPIGroupDSL apps();
99
BatchAPIGroupDSL batch();
100
RbacAPIGroupDSL rbac();
101
NetworkAPIGroupDSL network();
102
StorageAPIGroupDSL storage();
103
ApiextensionsAPIGroupDSL apiextensions();
104
105
// Generic resource operations
106
<T extends HasMetadata> MixedOperation<T, KubernetesResourceList<T>, Resource<T>> resources(Class<T> resourceType);
107
MixedOperation<GenericKubernetesResource, GenericKubernetesResourceList, Resource<GenericKubernetesResource>>
108
genericKubernetesResources(String apiVersion, String kind);
109
110
// Resource loading and management
111
NamespaceListVisitFromServerGetDeleteRecreateWaitApplicable<HasMetadata> load(InputStream is);
112
<T extends HasMetadata> NamespaceableResource<T> resource(T resource);
113
114
// Informers and watching
115
SharedInformerFactory informers();
116
117
// Version information
118
VersionInfo getKubernetesVersion();
119
}
120
121
public class KubernetesClientBuilder {
122
public KubernetesClientBuilder withConfig(Config config);
123
public KubernetesClient build();
124
}
125
126
public class Config {
127
// Factory methods
128
public static Config empty();
129
public static Config autoConfigure(String context);
130
public static Config fromKubeconfig(String kubeconfigContents);
131
public static Config fromKubeconfig(File kubeconfigFile);
132
public static Config fromKubeconfig(String context, File kubeconfig);
133
public static ConfigBuilder builder();
134
135
// Core configuration access
136
public String getMasterUrl();
137
public String getNamespace();
138
public String getOauthToken();
139
140
// Configuration management
141
public Config refresh();
142
public File getFile();
143
public List<NamedContext> getContexts();
144
public NamedContext getCurrentContext();
145
}
146
```
147
148
[Client Configuration](./client-configuration.md)
149
150
### Core Resource Operations
151
152
Fundamental CRUD operations for standard Kubernetes resources like Pods, Services, ConfigMaps, and Secrets. Provides fluent DSL for creating, reading, updating, and deleting resources.
153
154
```java { .api }
155
public interface MixedOperation<T extends HasMetadata, L extends KubernetesResourceList<T>, R extends Resource<T>>
156
extends NonNamespaceOperation<T, L, R> {
157
158
// Namespace scoping
159
NonNamespaceOperation<T, L, R> inNamespace(String namespace);
160
NonNamespaceOperation<T, L, R> inAnyNamespace();
161
}
162
163
public interface NonNamespaceOperation<T extends HasMetadata, L extends KubernetesResourceList<T>, R extends Resource<T>> {
164
// Resource selection
165
R withName(String name);
166
167
// Filtering and querying
168
FilterWatchListDeletable<T, L, R> withLabels(Map<String, String> labels);
169
FilterWatchListDeletable<T, L, R> withLabel(String key, String value);
170
FilterWatchListDeletable<T, L, R> withLabelSelector(LabelSelector selector);
171
FilterWatchListDeletable<T, L, R> withField(String key, String value);
172
173
// List operations
174
L list();
175
L list(ListOptions listOptions);
176
177
// Watch operations
178
Watch watch(Watcher<T> watcher);
179
Watch watch(ListOptions options, Watcher<T> watcher);
180
181
// Wait operations
182
T waitUntilReady(long amount, TimeUnit timeUnit);
183
T waitUntilCondition(Predicate<T> condition, long amount, TimeUnit timeUnit);
184
185
// Delete operations
186
List<StatusDetails> delete();
187
188
// Informer operations
189
SharedIndexInformer<T> inform();
190
SharedIndexInformer<T> inform(ResourceEventHandler<? super T> handler);
191
}
192
193
public interface Resource<T extends HasMetadata> {
194
// Get operations
195
T get();
196
197
// CRUD operations
198
T create();
199
T update();
200
T patch(String patch);
201
T patch(PatchContext patchContext, String patch);
202
List<StatusDetails> delete();
203
204
// Edit and modify operations
205
T edit(UnaryOperator<T> function);
206
T accept(Consumer<T> function);
207
T updateStatus();
208
T patchStatus();
209
210
// Server-side apply
211
T serverSideApply();
212
ServerSideApplicable<T> fieldManager(String manager);
213
214
// Watch operations
215
Watch watch(Watcher<T> watcher);
216
217
// Wait operations
218
T waitUntilReady(long amount, TimeUnit timeUnit);
219
T waitUntilCondition(Predicate<T> condition, long amount, TimeUnit timeUnit);
220
221
// Scale operations (for scalable resources)
222
T scale(int count);
223
Scale scale();
224
225
// Status and utility
226
boolean isReady();
227
T require() throws ResourceNotFoundException;
228
ReplaceDeletable<T> lockResourceVersion();
229
T item();
230
231
// Informer operations
232
SharedIndexInformer<T> inform();
233
SharedIndexInformer<T> inform(ResourceEventHandler<? super T> handler);
234
}
235
```
236
237
[Core Resources](./core-resources.md)
238
239
### API Groups and Workloads
240
241
Access to specialized Kubernetes API groups including Apps (Deployments, StatefulSets), Batch (Jobs, CronJobs), Networking, Storage, and RBAC resources.
242
243
```java { .api }
244
public interface AppsAPIGroupDSL {
245
MixedOperation<Deployment, DeploymentList, RollableScalableResource<Deployment>> deployments();
246
MixedOperation<StatefulSet, StatefulSetList, RollableScalableResource<StatefulSet>> statefulSets();
247
MixedOperation<DaemonSet, DaemonSetList, Resource<DaemonSet>> daemonSets();
248
MixedOperation<ReplicaSet, ReplicaSetList, RollableScalableResource<ReplicaSet>> replicaSets();
249
}
250
251
public interface BatchAPIGroupDSL {
252
MixedOperation<Job, JobList, ScalableResource<Job>> jobs();
253
MixedOperation<CronJob, CronJobList, Resource<CronJob>> cronJobs();
254
}
255
```
256
257
[API Groups](./api-groups.md)
258
259
### Custom Resources and Dynamic API
260
261
Support for Custom Resource Definitions (CRDs) and dynamic resource operations. Enables type-safe operations on custom resources and generic resource manipulation.
262
263
```java { .api }
264
public interface KubernetesClient {
265
<T extends HasMetadata> MixedOperation<T, KubernetesResourceList<T>, Resource<T>>
266
resources(Class<T> resourceType);
267
268
MixedOperation<GenericKubernetesResource, GenericKubernetesResourceList, Resource<GenericKubernetesResource>>
269
genericKubernetesResources(String apiVersion, String kind);
270
271
MixedOperation<GenericKubernetesResource, GenericKubernetesResourceList, Resource<GenericKubernetesResource>>
272
genericKubernetesResources(ResourceDefinitionContext context);
273
}
274
275
public class CustomResource<T, S> implements HasMetadata {
276
public T getSpec();
277
public void setSpec(T spec);
278
public S getStatus();
279
public void setStatus(S status);
280
}
281
```
282
283
[Custom Resources](./custom-resources.md)
284
285
### Watch and Informers
286
287
Real-time monitoring of Kubernetes resources with watch operations and informer patterns. Provides efficient caching and event-driven resource updates.
288
289
```java { .api }
290
public interface SharedInformerFactory {
291
<T extends HasMetadata> SharedIndexInformer<T> sharedIndexInformerFor(
292
Class<T> apiTypeClass, long resyncPeriodInMillis);
293
294
void startAllRegisteredInformers();
295
void stopAllRegisteredInformers();
296
}
297
298
public interface SharedIndexInformer<T> {
299
void addEventHandler(ResourceEventHandler<T> handler);
300
Indexer<T> getIndexer();
301
void run();
302
void stop();
303
boolean hasSynced();
304
}
305
306
public interface ResourceEventHandler<T> {
307
void onAdd(T obj);
308
void onUpdate(T oldObj, T newObj);
309
void onDelete(T obj, boolean deletedFinalStateUnknown);
310
}
311
```
312
313
[Watch and Informers](./watch-informers.md)
314
315
### Pod Operations and Utilities
316
317
Specialized operations for Pods including log streaming, command execution, port forwarding, and file operations.
318
319
```java { .api }
320
public interface PodResource extends Resource<Pod> {
321
String log();
322
String log(PodLogOptions options);
323
ExecWatch exec(String... command);
324
LocalPortForward portForward(int port);
325
Boolean upload(Path pathToUpload);
326
Boolean copy(Path source, Path destination);
327
Pod attach();
328
}
329
330
public interface ExecWatch extends Closeable {
331
OutputStream getInput();
332
InputStream getOutput();
333
InputStream getError();
334
void resize(int cols, int rows);
335
}
336
```
337
338
[Pod Operations](./pod-operations.md)
339
340
### Exception Handling and Error Management
341
342
Comprehensive exception hierarchy for handling Kubernetes API errors, timeouts, and resource-specific exceptions.
343
344
```java { .api }
345
public class KubernetesClientException extends RuntimeException {
346
public Status getStatus();
347
public int getCode();
348
public String getFullResourceName();
349
public static KubernetesClientException launderThrowable(Throwable cause);
350
}
351
352
public class ResourceNotFoundException extends KubernetesClientException {
353
public ResourceNotFoundException(String message);
354
}
355
356
public class KubernetesClientTimeoutException extends KubernetesClientException {
357
public KubernetesClientTimeoutException(String message, long timeout, TimeUnit timeUnit);
358
}
359
```
360
361
[Exception Handling](./exception-handling.md)
362
363
### Serialization and Utilities
364
365
Utilities for serializing and deserializing Kubernetes resources, resource manipulation, and common operations.
366
367
```java { .api }
368
public class KubernetesSerialization {
369
public ObjectMapper jsonMapper();
370
public ObjectMapper yamlMapper();
371
public <T> T unmarshal(String str);
372
public <T> T unmarshal(String str, Class<T> type);
373
public <T> T unmarshal(InputStream is);
374
}
375
376
public class KubernetesResourceUtil {
377
public static String getName(HasMetadata resource);
378
public static String getNamespace(HasMetadata resource);
379
public static String getResourceVersion(HasMetadata resource);
380
public static boolean isResourceReady(HasMetadata resource);
381
}
382
```
383
384
[Utilities](./utilities.md)