在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:fabric8io/kubernetes-client开源软件地址:https://github.com/fabric8io/kubernetes-client开源编程语言:Java 98.2%开源软件介绍:Kubernetes & OpenShift Java ClientThis client provides access to the full Kubernetes & OpenShift REST APIs via a fluent DSL.
Contents
UsageCreating a clientThe easiest way to create a client is: KubernetesClient client = new KubernetesClientBuilder().build();
OpenShiftClient osClient = new KubernetesClientBuilder().build().adapt(OpenShiftClient.class); Configuring the clientThis will use settings from different sources in the following order of priority:
System properties are preferred over environment variables. The following system properties & environment variables can be used for configuration:
Alternatively you can use the Config config = new ConfigBuilder().withMasterUrl("https://mymaster.com").build();
KubernetesClient client = new KubernetesClientBuilder().withConfig(config).build(); Using the DSL is the same for all resources. List resources: NamespaceList myNs = client.namespaces().list();
ServiceList myServices = client.services().list();
ServiceList myNsServices = client.services().inNamespace("default").list(); Get a resource: Namespace myns = client.namespaces().withName("myns").get();
Service myservice = client.services().inNamespace("default").withName("myservice").get(); Delete: Namespace myns = client.namespaces().withName("myns").delete();
Service myservice = client.services().inNamespace("default").withName("myservice").delete(); Editing resources uses the inline builders from the Kubernetes Model: Namespace myns = client.namespaces().withName("myns").edit(n -> new NamespaceBuilder(n)
.editMetadata()
.addToLabels("a", "label")
.endMetadata()
.build());
Service myservice = client.services().inNamespace("default").withName("myservice").edit(s -> new ServiceBuilder(s)
.editMetadata()
.addToLabels("another", "label")
.endMetadata()
.build()); In the same spirit you can inline builders to create: Namespace myns = client.namespaces().create(new NamespaceBuilder()
.withNewMetadata()
.withName("myns")
.addToLabels("a", "label")
.endMetadata()
.build());
Service myservice = client.services().inNamespace("default").create(new ServiceBuilder()
.withNewMetadata()
.withName("myservice")
.addToLabels("another", "label")
.endMetadata()
.build()); You can also set the apiVersion of the resource like in the case of SecurityContextConstraints : SecurityContextConstraints scc = new SecurityContextConstraintsBuilder()
.withApiVersion("v1")
.withNewMetadata().withName("scc").endMetadata()
.withAllowPrivilegedContainer(true)
.withNewRunAsUser()
.withType("RunAsAny")
.endRunAsUser()
.build(); Following eventsUse client.events().inAnyNamespace().watch(new Watcher<Event>() {
@Override
public void eventReceived(Action action, Event resource) {
System.out.println("event " + action.name() + " " + resource.toString());
}
@Override
public void onClose(KubernetesClientException cause) {
System.out.println("Watcher close due to " + cause);
}
}); Working with extensionsThe kubernetes API defines a bunch of extensions like e.g. to list the jobs...
Loading resources from external sourcesThere are cases where you want to read a resource from an external source, rather than defining it using the clients DSL. For those cases the client allows you to load the resource from:
Once the resource is loaded, you can treat it as you would, had you created it yourself. For example lets read a pod, from a yml file and work with it:
Passing a reference of a resource to the clientIn the same spirit you can use an object created externally (either a reference or using its string representation). For example:
Adapting the clientThe client supports plug-able adapters. An example adapter is the OpenShift Adapter which allows adapting an existing KubernetesClient instance to an OpenShiftClient one. For example: KubernetesClient client = new KubernetesClientBuilder().build();
OpenShiftClient oClient = client.adapt(OpenShiftClient.class); The client also support the isAdaptable() method which checks if the adaptation is possible and returns true if it does. KubernetesClient client = new KubernetesClientBuilder().build();
if (client.isAdaptable(OpenShiftClient.class)) {
OpenShiftClient oClient = client.adapt(OpenShiftClient.class);
} else {
throw new Exception("Adapting to OpenShiftClient not support. Check if adapter is present, and that env provides /oapi root path.");
} Adapting and closeNote that when using adapt() both the adaptee and the target will share the same resources (underlying http client, thread pools etc). This means that close() is not required to be used on every single instance created via adapt. Calling close() on any of the adapt() managed instances or the original instance, will properly clean up all the resources and thus none of the instances will be usable any longer. Mocking KubernetesAlong with the client this project also provides a kubernetes mock server that you can use for testing purposes.
The mock server is based on The Mock Web Server has two modes of operation:
Expectations modeIt's the typical mode where you first set which are the expected http requests and which should be the responses for each request. More details on usage can be found at: https://github.com/fabric8io/mockwebserver This mode has been extensively used for testing the client itself. Make sure you check kubernetes-test. To add a Kubernetes server to your test: @Rule
public KubernetesServer server = new KubernetesServer(); CRUD modeDefining every single request and response can become tiresome. Given that in most cases the mock webserver is used to perform simple crud based operations, a crud mode has been added. When using the crud mode, the mock web server will store, read, update and delete kubernetes resources using an in memory map and will appear as a real api server. To add a Kubernetes Server in crud mode to your test: @Rule
public KubernetesServer server = new KubernetesServer(true, true); Then you can use the server like: @Test
public void testInCrudMode() {
KubernetesClient client = server.getClient();
final CountDownLatch deleteLatch = new CountDownLatch(1);
final CountDownLatch closeLatch = new CountDownLatch(1);
//CREATE
client.pods().inNamespace("ns1").create(new PodBuilder().withNewMetadata().withName("pod1").endMetadata().build());
//READ
podList = client.pods().inNamespace("ns1").list();
assertNotNull(podList);
assertEquals(1, podList.getItems().size());
//WATCH
Watch watch = client.pods().inNamespace("ns1").withName("pod1").watch(new Watcher<Pod>() {
@Override
public void eventReceived(Action action, Pod resource) {
switch (action) {
case DELETED:
deleteLatch.countDown();
break;
default:
throw new AssertionFailedError(action.toString().concat(" isn't recognised."));
}
}
@Override
public void onClose(KubernetesClientException cause) {
closeLatch.countDown();
}
});
//DELETE
client.pods().inNamespace("ns1").withName("pod1").delete();
//READ AGAIN
podList = client.pods().inNamespace("ns1").list();
assertNotNull(podList);
assertEquals(0, podList.getItems().size());
assertTrue(deleteLatch.await(1, TimeUnit.MINUTES));
watch.close();
assertTrue(closeLatch.await(1, TimeUnit.MINUTES));
} JUnit5 support through extensionYou can use KubernetesClient mocking mechanism with JUnit5. Since it doesn't support @EnableKubernetesMockClient
class ExampleTest {
KubernetesClient client;
@Test
public void testInStandardMode() {
...
}
} In case you would like to define static instance of mocked server per all the test (JUnit4 @EnableKubernetesMockClient(crud = true)
class ExampleTest {
static KubernetesClient client;
@Test
public void testInCrudMode() {
...
}
} Compatibility Matrix |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论