io.kubernetes.client.util.Watch Java Examples

The following examples show how to use io.kubernetes.client.util.Watch. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WatchExample.java    From java with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException, ApiException {
  ApiClient client = Config.defaultClient();
  // infinite timeout
  OkHttpClient httpClient =
      client.getHttpClient().newBuilder().readTimeout(0, TimeUnit.SECONDS).build();
  client.setHttpClient(httpClient);
  Configuration.setDefaultApiClient(client);

  CoreV1Api api = new CoreV1Api();

  Watch<V1Namespace> watch =
      Watch.createWatch(
          client,
          api.listNamespaceCall(null, null, null, null, null, 5, null, null, Boolean.TRUE, null),
          new TypeToken<Watch.Response<V1Namespace>>() {}.getType());

  try {
    for (Watch.Response<V1Namespace> item : watch) {
      System.out.printf("%s : %s%n", item.type, item.object.getMetadata().getName());
    }
  } finally {
    watch.close();
  }
}
 
Example #2
Source File: GenericKubernetesApi.java    From java with Apache License 2.0 6 votes vote down vote up
/**
 * Watch watchable.
 *
 * @param listOptions the list options
 * @return the watchable
 * @throws ApiException the api exception
 */
public Watchable<ApiType> watch(final ListOptions listOptions) throws ApiException {
  Call call =
      customObjectsApi.listClusterCustomObjectCall(
          this.apiGroup,
          this.apiVersion,
          this.resourcePlural,
          null,
          listOptions.getContinue(),
          listOptions.getFieldSelector(),
          listOptions.getLabelSelector(),
          listOptions.getLimit(),
          listOptions.getResourceVersion(),
          listOptions.getTimeoutSeconds(),
          true,
          null);

  call = tweakCallForCoreV1Group(call);
  return Watch.createWatch(
      customObjectsApi.getApiClient(),
      call,
      TypeToken.getParameterized(Watch.Response.class, apiTypeClass).getType());
}
 
Example #3
Source File: GenericKubernetesApi.java    From java with Apache License 2.0 6 votes vote down vote up
/**
 * Watch watchable.
 *
 * @param namespace the namespace
 * @param listOptions the list options
 * @return the watchable
 * @throws ApiException the api exception
 */
public Watchable<ApiType> watch(String namespace, final ListOptions listOptions)
    throws ApiException {
  if (Strings.isNullOrEmpty(namespace)) {
    throw new IllegalArgumentException("invalid namespace");
  }
  Call call =
      customObjectsApi.listClusterCustomObjectCall(
          this.apiGroup,
          this.apiVersion,
          this.resourcePlural,
          null,
          listOptions.getContinue(),
          listOptions.getFieldSelector(),
          listOptions.getLabelSelector(),
          listOptions.getLimit(),
          listOptions.getResourceVersion(),
          listOptions.getTimeoutSeconds(),
          true,
          null);

  return Watch.createWatch(
      customObjectsApi.getApiClient(),
      call,
      TypeToken.getParameterized(Watch.Response.class, apiTypeClass).getType());
}
 
Example #4
Source File: KubeOpt.java    From dew with Apache License 2.0 5 votes vote down vote up
/**
 * Stop watch.
 *
 * @param watchId the watch id
 */
public void stopWatch(String watchId) {
    Watch watch = watchMap.get(watchId);
    watchMap.remove(watchId);
    try {
        watch.close();
    } catch (Exception ignore) {
        log.warn("Stop watch error.", ignore);
    }
}
 
Example #5
Source File: K8sClient.java    From pravega with Apache License 2.0 5 votes vote down vote up
@SneakyThrows({ApiException.class, IOException.class})
private Optional<V1ContainerStateTerminated> createAWatchAndReturnOnTermination(String namespace, String podName) {
    log.debug("Creating a watch for pod {}/{}", namespace, podName);
    CoreV1Api api = new CoreV1Api();
    K8AsyncCallback<V1ServiceAccount> callback = new K8AsyncCallback<>("createAWatchAndReturnOnTermination");
    @Cleanup
    Watch<V1Pod> watch = Watch.createWatch(
            client,
            api.listNamespacedPodCall(namespace, PRETTY_PRINT, ALLOW_WATCH_BOOKMARKS, null, null, "POD_NAME=" + podName, null,
                                      null, null, Boolean.TRUE, callback),
            new TypeToken<Watch.Response<V1Pod>>() {
            }.getType());

    for (Watch.Response<V1Pod> v1PodResponse : watch) {

        List<V1ContainerStatus> containerStatuses = v1PodResponse.object.getStatus().getContainerStatuses();
        log.debug("Container status for the pod {} is {}", podName, containerStatuses);
        if (containerStatuses == null || containerStatuses.size() == 0) {
            log.debug("Container status is not part of the pod {}/{}, wait for the next update from KUBERNETES Cluster", namespace, podName);
            continue;
        }
        // We check only the first container as there is only one container in the pod.
        V1ContainerState containerStatus = containerStatuses.get(0).getState();
        log.debug("Current container status is {}", containerStatus);
        if (containerStatus.getTerminated() != null) {
            log.info("Pod {}/{} has terminated", namespace, podName);
            return Optional.of(containerStatus.getTerminated());
        }
    }
    return Optional.empty();
}
 
Example #6
Source File: MockRunOnceListerWatcher.java    From java with Apache License 2.0 4 votes vote down vote up
public MockRunOnceListerWatcher(ApiListType list, Watch.Response<ApiType>... events) {
  this.list = list;
  this.events = events;
}
 
Example #7
Source File: ControllerTest.java    From java with Apache License 2.0 4 votes vote down vote up
@Test
public void testControllerProcessDeltas() throws InterruptedException {

  AtomicInteger receivingDeltasCount = new AtomicInteger(0);
  V1Pod foo1 = new V1Pod().metadata(new V1ObjectMeta().name("foo1").namespace("default"));
  V1Pod foo2 = new V1Pod().metadata(new V1ObjectMeta().name("foo2").namespace("default"));
  V1Pod foo3 = new V1Pod().metadata(new V1ObjectMeta().name("foo3").namespace("default"));

  V1PodList podList =
      new V1PodList().metadata(new V1ListMeta()).items(Arrays.asList(foo1, foo2, foo3));
  DeltaFIFO deltaFIFO = new DeltaFIFO(Caches::deletionHandlingMetaNamespaceKeyFunc, new Cache());

  AtomicBoolean runOnce = new AtomicBoolean(false);

  ListerWatcher<V1Pod, V1PodList> listerWatcher =
      new MockRunOnceListerWatcher<V1Pod, V1PodList>(
          podList, new Watch.Response<V1Pod>(EventType.MODIFIED.name(), foo3));

  Controller<V1Pod, V1PodList> controller =
      new Controller<>(
          V1Pod.class,
          deltaFIFO,
          listerWatcher,
          (deltas) -> {
            receivingDeltasCount.incrementAndGet();
          });
  Thread controllerThread = new Thread(controller::run);
  controllerThread.setDaemon(true);
  controllerThread.start();

  // sleep 1s for processing all the deltas
  Thread.sleep(1000);

  try {
    assertEquals(4, receivingDeltasCount.get());

  } catch (Throwable t) {
    throw new RuntimeException(t);
  } finally {
    controller.stop();
  }
}
 
Example #8
Source File: MockWatch.java    From java with Apache License 2.0 4 votes vote down vote up
public MockWatch(Watch.Response<ApiType>... events) {
  this.events = new ArrayList<>(Arrays.asList(events));
}
 
Example #9
Source File: MockWatch.java    From java with Apache License 2.0 4 votes vote down vote up
@Override
public Iterator<Watch.Response<ApiType>> iterator() {
  // not implemented
  return null;
}
 
Example #10
Source File: MockWatch.java    From java with Apache License 2.0 4 votes vote down vote up
@Override
public Watch.Response<ApiType> next() {
  Watch.Response<ApiType> event = events.get(0);
  this.events.remove(0);
  return event;
}
 
Example #11
Source File: DefaultSharedIndexInformerTest.java    From java with Apache License 2.0 4 votes vote down vote up
@Test
public void testInformerReListWatchOnWatchConflict() throws InterruptedException {

  CoreV1Api coreV1Api = new CoreV1Api(client);

  String startRV = "1000";
  V1PodList podList =
      new V1PodList().metadata(new V1ListMeta().resourceVersion(startRV)).items(Arrays.asList());

  stubFor(
      get(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods"))
          .withQueryParam("watch", equalTo("false"))
          .willReturn(
              aResponse()
                  .withStatus(200)
                  .withHeader("Content-Type", "application/json")
                  .withBody(new JSON().serialize(podList))));

  Watch.Response<V1Pod> watchResponse =
      new Watch.Response<>(
          EventType.ERROR.name(), new V1Status().apiVersion("v1").kind("Status").code(409));
  stubFor(
      get(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods"))
          .withQueryParam("watch", equalTo("true"))
          .withQueryParam("resourceVersion", equalTo(startRV))
          .willReturn(
              aResponse()
                  .withStatus(200)
                  .withHeader("Content-Type", "application/json")
                  .withBody(new JSON().serialize(watchResponse))));

  SharedInformerFactory factory = new SharedInformerFactory();
  SharedIndexInformer<V1Pod> podInformer =
      factory.sharedIndexInformerFor(
          (CallGeneratorParams params) -> {
            try {
              return coreV1Api.listNamespacedPodCall(
                  namespace,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  params.resourceVersion,
                  params.timeoutSeconds,
                  params.watch,
                  null);
            } catch (ApiException e) {
              throw new RuntimeException(e);
            }
          },
          V1Pod.class,
          V1PodList.class);

  factory.startAllRegisteredInformers();

  // Sleep mroe than 1s so that informer can perform multiple rounds of list-watch
  Thread.sleep(3000);

  verify(
      moreThan(1),
      getRequestedFor(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods"))
          .withQueryParam("watch", equalTo("false")));
  verify(
      moreThan(1),
      getRequestedFor(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods"))
          .withQueryParam("watch", equalTo("true")));
  factory.stopAllRegisteredInformers();
}