use of io.fabric8.kubernetes.client.Watcher.Action in project kubernetes-client by fabric8io.
the class WatchTest method testTryWithResourcesConnectsThenReceivesEvent.
@Test
@DisplayName("TryWithResources, connects and receives event then receives GONE, should receive first event and then close")
void testTryWithResourcesConnectsThenReceivesEvent() throws InterruptedException {
// Given
server.expect().withPath("/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&resourceVersion=1&allowWatchBookmarks=true&watch=true").andUpgradeToWebSocket().open().waitFor(EVENT_WAIT_PERIOD_MS).andEmit(new WatchEvent(pod1, "DELETED")).waitFor(EVENT_WAIT_PERIOD_MS).andEmit(outdatedEvent()).done().once();
final CountDownLatch deleteLatch = new CountDownLatch(1);
final CountDownLatch closeLatch = new CountDownLatch(1);
final Watcher<Pod> watcher = new Watcher<Pod>() {
@Override
public void eventReceived(Action action, Pod resource) {
if (action != DELETED) {
fail();
}
deleteLatch.countDown();
}
@Override
public void onClose(WatcherException cause) {
assertTrue(cause.isHttpGone());
closeLatch.countDown();
}
};
// When
try (Watch watch = client.pods().withName("pod1").withResourceVersion("1").watch(watcher)) {
// Then
assertNotNull(watch);
assertTrue(deleteLatch.await(10, TimeUnit.SECONDS));
assertTrue(closeLatch.await(10, TimeUnit.SECONDS));
}
}
use of io.fabric8.kubernetes.client.Watcher.Action in project kubernetes-client by fabric8io.
the class AuthorizationPolicyTest method testCreate.
@Test
@DisplayName("Should Create a AuthorizationPolicy Entry")
void testCreate() throws InterruptedException {
AuthorizationPolicy service = new AuthorizationPolicyBuilder().withNewMetadata().withName("httpbin").endMetadata().withNewSpec().withSelector(new WorkloadSelectorBuilder().withMatchLabels(Collections.singletonMap("app", "httpbin")).build()).withAction(AuthorizationPolicyAction.DENY).withRules(new RuleBuilder().withFrom(new RuleFromBuilder().withSource(new SourceBuilder().withPrincipals("cluster.local/ns/default/sa/sleep").build()).build(), new RuleFromBuilder().withSource(new SourceBuilder().withNamespaces("dev").build()).build()).withTo(new RuleToBuilder().withOperation(new OperationBuilder().withMethods("GET").build()).build()).withWhen(new ConditionBuilder().withKey("request.auth.claims[iss]").withValues("https://accounts.google.com").build()).build()).endSpec().build();
server.expect().post().withPath("/apis/security.istio.io/v1beta1/namespaces/ns2/authorizationpolicies").andReturn(HttpURLConnection.HTTP_OK, service).once();
service = client.v1beta1().authorizationPolicies().inNamespace("ns2").create(service);
assertNotNull(service);
RecordedRequest recordedRequest = server.takeRequest();
assertEquals("{\"apiVersion\":\"security.istio.io/v1beta1\"," + "\"kind\":\"AuthorizationPolicy\"," + "\"metadata\":{\"name\":\"httpbin\"}," + "\"spec\":{" + "\"action\":\"DENY\"," + "\"rules\":[" + "{\"from\":[{\"source\":{\"principals\":[\"cluster.local/ns/default/sa/sleep\"]}}," + "{\"source\":{\"namespaces\":[\"dev\"]}}]," + "\"to\":[{\"operation\":{\"methods\":[\"GET\"]}}]," + "\"when\":[{\"key\":\"request.auth.claims[iss]\",\"values\":[\"https://accounts.google.com\"]}]}]," + "\"selector\":{\"matchLabels\":{\"app\":\"httpbin\"}}}}", recordedRequest.getBody().readUtf8());
}
use of io.fabric8.kubernetes.client.Watcher.Action in project kubernetes-client by fabric8io.
the class AbstractWatchManager method onMessage.
protected void onMessage(String message) {
try {
WatchEvent event = readWatchEvent(message);
Object object = event.getObject();
if (object instanceof Status) {
Status status = (Status) object;
onStatus(status);
} else if (object instanceof KubernetesResourceList) {
// Dirty cast - should always be valid though
KubernetesResourceList list = (KubernetesResourceList) object;
updateResourceVersion(list.getMetadata().getResourceVersion());
Action action = Action.valueOf(event.getType());
List<HasMetadata> items = list.getItems();
if (items != null) {
for (HasMetadata item : items) {
eventReceived(action, item);
}
}
} else if (object instanceof HasMetadata) {
@SuppressWarnings("unchecked") T obj = (T) object;
updateResourceVersion(obj.getMetadata().getResourceVersion());
Action action = Action.valueOf(event.getType());
eventReceived(action, obj);
} else {
logger.error("Unknown message received: {}", message);
}
} catch (ClassCastException e) {
logger.error("Received wrong type of object for watch", e);
} catch (IllegalArgumentException e) {
logger.error("Invalid event type", e);
} catch (Exception e) {
logger.error("Unhandled exception encountered in watcher event handler", e);
}
}
use of io.fabric8.kubernetes.client.Watcher.Action in project kubernetes-client by fabric8io.
the class GenericKubernetesResourceExample method main.
public static void main(String[] args) throws Exception {
final ConfigBuilder configBuilder = new ConfigBuilder();
configBuilder.withWatchReconnectInterval(500);
configBuilder.withWatchReconnectLimit(5);
try (KubernetesClient client = new KubernetesClientBuilder().withConfig(configBuilder.build()).build()) {
String namespace = "default";
CustomResourceDefinition prometheousRuleCrd = client.apiextensions().v1beta1().customResourceDefinitions().load(GenericKubernetesResourceExample.class.getResourceAsStream("/prometheous-rule-crd.yml")).get();
client.apiextensions().v1beta1().customResourceDefinitions().createOrReplace(prometheousRuleCrd);
logger.info("Successfully created Prometheous custom resource definition");
// Creating Custom Resources Now:
ResourceDefinitionContext crdContext = CustomResourceDefinitionContext.fromCrd(prometheousRuleCrd);
client.load(GenericKubernetesResourceExample.class.getResourceAsStream("/prometheous-rule-cr.yml")).inNamespace(namespace).createOrReplace();
logger.info("Created Custom Resource successfully too");
// Listing all custom resources in given namespace:
NonNamespaceOperation<GenericKubernetesResource, GenericKubernetesResourceList, Resource<GenericKubernetesResource>> resourcesInNamespace = client.genericKubernetesResources(crdContext).inNamespace(namespace);
GenericKubernetesResourceList list = resourcesInNamespace.list();
List<GenericKubernetesResource> items = list.getItems();
logger.info("Custom Resources :- ");
for (GenericKubernetesResource customResource : items) {
ObjectMeta metadata = customResource.getMetadata();
final String name = metadata.getName();
logger.info(name);
}
// Watching custom resources now
logger.info("Watching custom resources now");
final CountDownLatch closeLatch = new CountDownLatch(1);
resourcesInNamespace.watch(new Watcher<GenericKubernetesResource>() {
@Override
public void eventReceived(Action action, GenericKubernetesResource resource) {
logger.info("{}: {}", action, resource);
}
@Override
public void onClose(WatcherException e) {
logger.debug("Watcher onClose");
closeLatch.countDown();
if (e != null) {
logger.error(e.getMessage(), e);
}
}
});
closeLatch.await(10, TimeUnit.MINUTES);
// Cleanup
logger.info("Deleting custom resources...");
resourcesInNamespace.withName("prometheus-example-rules").delete();
client.apiextensions().v1beta1().customResourceDefinitions().withName(prometheousRuleCrd.getMetadata().getName()).delete();
} catch (KubernetesClientException e) {
logger.error("Could not create resource: {}", e.getMessage(), e);
}
}
use of io.fabric8.kubernetes.client.Watcher.Action in project helm-charts by hivemq.
the class HelmChartDeploymentIT method getWaitForClusterToBeReadyLatch.
/**
* Return a count-down latch that will be decreased when the hivemq cluster is running.
* The helm chart makes sure it is installed, and the operator makes sure the state is
* update to running, we listen for this status change.
*
* @param kubeConfigYaml k3s yaml configuration for the container that is running and waiting for the Kubernetes artifacts to be ready
*/
private CountDownLatch getWaitForClusterToBeReadyLatch(@NotNull final String kubeConfigYaml) {
Config config = Config.fromKubeconfig(kubeConfigYaml);
DefaultKubernetesClient client = new DefaultKubernetesClient(config);
final CountDownLatch closeLatch = new CountDownLatch(1);
client.customResources(HiveMQInfo.class).watch(new Watcher<>() {
@Override
public void eventReceived(@NotNull Action action, @NotNull HiveMQInfo resource) {
if (resource.getStatus() != null && resource.getStatus().getState() != null && resource.getStatus().getState() == HivemqClusterStatus.State.RUNNING) {
closeLatch.countDown();
}
}
@Override
public void onClose(@NotNull WatcherException cause) {
System.out.println("onClose");
}
});
return closeLatch;
}
Aggregations