Search in sources :

Example 11 with CallGeneratorParams

use of io.kubernetes.client.util.CallGeneratorParams in project java by kubernetes-client.

the class ControllerExample method main.

public static void main(String[] args) throws IOException {
    CoreV1Api coreV1Api = new CoreV1Api();
    ApiClient apiClient = coreV1Api.getApiClient();
    OkHttpClient httpClient = apiClient.getHttpClient().newBuilder().readTimeout(0, TimeUnit.SECONDS).build();
    apiClient.setHttpClient(httpClient);
    // instantiating an informer-factory, and there should be only one informer-factory
    // globally.
    SharedInformerFactory informerFactory = new SharedInformerFactory();
    // registering node-informer into the informer-factory.
    SharedIndexInformer<V1Node> nodeInformer = informerFactory.sharedIndexInformerFor((CallGeneratorParams params) -> {
        return coreV1Api.listNodeCall(null, null, null, null, null, null, params.resourceVersion, null, params.timeoutSeconds, params.watch, null);
    }, V1Node.class, V1NodeList.class);
    informerFactory.startAllRegisteredInformers();
    EventBroadcaster eventBroadcaster = new LegacyEventBroadcaster(coreV1Api);
    // nodeReconciler prints node information on events
    NodePrintingReconciler nodeReconciler = new NodePrintingReconciler(nodeInformer, eventBroadcaster.newRecorder(new V1EventSource().host("localhost").component("node-printer")));
    // Use builder library to construct a default controller.
    Controller controller = ControllerBuilder.defaultBuilder(informerFactory).watch((workQueue) -> ControllerBuilder.controllerWatchBuilder(V1Node.class, workQueue).withWorkQueueKeyFunc((V1Node node) -> new Request(node.getMetadata().getName())).withOnAddFilter((V1Node createdNode) -> createdNode.getMetadata().getName().startsWith(// optional, set onAdd filter
    "docker-")).withOnUpdateFilter((V1Node oldNode, V1Node newNode) -> newNode.getMetadata().getName().startsWith(// optional, set onUpdate filter
    "docker-")).withOnDeleteFilter((V1Node deletedNode, Boolean stateUnknown) -> deletedNode.getMetadata().getName().startsWith(// optional, set onDelete filter
    "docker-")).build()).withReconciler(// required, set the actual reconciler
    nodeReconciler).withName(// optional, set name for controller
    "node-printing-controller").withWorkerCount(// optional, set worker thread count
    4).withReadyFunc(// optional, only starts controller when the
    nodeInformer::hasSynced).build();
    // Use builder library to manage one or multiple controllers.
    ControllerManager controllerManager = ControllerBuilder.controllerManagerBuilder(informerFactory).addController(controller).build();
    LeaderElectingController leaderElectingController = new LeaderElectingController(new LeaderElector(new LeaderElectionConfig(new EndpointsLock("kube-system", "leader-election", "foo"), Duration.ofMillis(10000), Duration.ofMillis(8000), Duration.ofMillis(5000))), controllerManager);
    leaderElectingController.run();
}
Also used : EventBroadcaster(io.kubernetes.client.extended.event.legacy.EventBroadcaster) LegacyEventBroadcaster(io.kubernetes.client.extended.event.legacy.LegacyEventBroadcaster) V1NodeList(io.kubernetes.client.openapi.models.V1NodeList) LeaderElector(io.kubernetes.client.extended.leaderelection.LeaderElector) Result(io.kubernetes.client.extended.controller.reconciler.Result) LeaderElectionConfig(io.kubernetes.client.extended.leaderelection.LeaderElectionConfig) V1Node(io.kubernetes.client.openapi.models.V1Node) Reconciler(io.kubernetes.client.extended.controller.reconciler.Reconciler) SharedInformerFactory(io.kubernetes.client.informer.SharedInformerFactory) ApiClient(io.kubernetes.client.openapi.ApiClient) Request(io.kubernetes.client.extended.controller.reconciler.Request) Lister(io.kubernetes.client.informer.cache.Lister) ControllerManager(io.kubernetes.client.extended.controller.ControllerManager) SharedIndexInformer(io.kubernetes.client.informer.SharedIndexInformer) Duration(java.time.Duration) EventRecorder(io.kubernetes.client.extended.event.legacy.EventRecorder) EventBroadcaster(io.kubernetes.client.extended.event.legacy.EventBroadcaster) LeaderElectingController(io.kubernetes.client.extended.controller.LeaderElectingController) EventType(io.kubernetes.client.extended.event.EventType) EndpointsLock(io.kubernetes.client.extended.leaderelection.resourcelock.EndpointsLock) Controller(io.kubernetes.client.extended.controller.Controller) ControllerBuilder(io.kubernetes.client.extended.controller.builder.ControllerBuilder) V1EventSource(io.kubernetes.client.openapi.models.V1EventSource) IOException(java.io.IOException) CoreV1Api(io.kubernetes.client.openapi.apis.CoreV1Api) TimeUnit(java.util.concurrent.TimeUnit) OkHttpClient(okhttp3.OkHttpClient) LegacyEventBroadcaster(io.kubernetes.client.extended.event.legacy.LegacyEventBroadcaster) CallGeneratorParams(io.kubernetes.client.util.CallGeneratorParams) OkHttpClient(okhttp3.OkHttpClient) V1Node(io.kubernetes.client.openapi.models.V1Node) Request(io.kubernetes.client.extended.controller.reconciler.Request) ControllerManager(io.kubernetes.client.extended.controller.ControllerManager) ApiClient(io.kubernetes.client.openapi.ApiClient) LeaderElectingController(io.kubernetes.client.extended.controller.LeaderElectingController) Controller(io.kubernetes.client.extended.controller.Controller) CallGeneratorParams(io.kubernetes.client.util.CallGeneratorParams) LeaderElectingController(io.kubernetes.client.extended.controller.LeaderElectingController) LeaderElectionConfig(io.kubernetes.client.extended.leaderelection.LeaderElectionConfig) SharedInformerFactory(io.kubernetes.client.informer.SharedInformerFactory) EndpointsLock(io.kubernetes.client.extended.leaderelection.resourcelock.EndpointsLock) V1EventSource(io.kubernetes.client.openapi.models.V1EventSource) LeaderElector(io.kubernetes.client.extended.leaderelection.LeaderElector) LegacyEventBroadcaster(io.kubernetes.client.extended.event.legacy.LegacyEventBroadcaster) CoreV1Api(io.kubernetes.client.openapi.apis.CoreV1Api)

Example 12 with CallGeneratorParams

use of io.kubernetes.client.util.CallGeneratorParams in project java by kubernetes-client.

the class ReflectorRunnable method run.

/**
 * run first lists all items and get the resource version at the moment of call, and then use the
 * resource version to watch.
 */
public void run() {
    log.info("{}#Start listing and watching...", apiTypeClass);
    try {
        ApiListType list = listerWatcher.list(new CallGeneratorParams(Boolean.FALSE, getRelistResourceVersion(), null));
        V1ListMeta listMeta = list.getMetadata();
        String resourceVersion = listMeta.getResourceVersion();
        List<? extends KubernetesObject> items = list.getItems();
        if (log.isDebugEnabled()) {
            log.debug("{}#Extract resourceVersion {} list meta", apiTypeClass, resourceVersion);
        }
        this.syncWith(items, resourceVersion);
        this.lastSyncResourceVersion = resourceVersion;
        this.isLastSyncResourceVersionUnavailable = false;
        if (log.isDebugEnabled()) {
            log.debug("{}#Start watching with {}...", apiTypeClass, lastSyncResourceVersion);
        }
        while (true) {
            if (!isActive.get()) {
                closeWatch();
                return;
            }
            try {
                if (log.isDebugEnabled()) {
                    log.debug("{}#Start watch with resource version {}", apiTypeClass, lastSyncResourceVersion);
                }
                long jitteredWatchTimeoutSeconds = Double.valueOf(REFLECTOR_WATCH_CLIENTSIDE_TIMEOUT.getSeconds() * (1 + Math.random())).longValue();
                Watchable<ApiType> newWatch = listerWatcher.watch(new CallGeneratorParams(Boolean.TRUE, lastSyncResourceVersion, Long.valueOf(jitteredWatchTimeoutSeconds).intValue()));
                synchronized (this) {
                    if (!isActive.get()) {
                        newWatch.close();
                        continue;
                    }
                    watch = newWatch;
                }
                watchHandler(newWatch);
            } catch (WatchExpiredException e) {
                // Watch calls were failed due to expired resource-version. Returning
                // to unwind the list-watch loops so that we can respawn a new round
                // of list-watching.
                log.info("{}#Watch expired, will re-list-watch soon", this.apiTypeClass);
                return;
            } catch (Throwable t) {
                if (isConnectException(t)) {
                    // If this is "connection refused" error, it means that most likely
                    // apiserver is not responsive. It doesn't make sense to re-list all
                    // objects because most likely we will be able to restart watch where
                    // we ended. If that's the case wait and resend watch request.
                    log.info("{}#Watch get connect exception, retry watch", this.apiTypeClass);
                    try {
                        Thread.sleep(1000L);
                    } catch (InterruptedException e) {
                    // no-op
                    }
                    continue;
                }
                if ((t instanceof RuntimeException) && t.getMessage() != null && t.getMessage().contains("IO Exception during hasNext")) {
                    log.info("{}#Read timeout retry list and watch", this.apiTypeClass);
                    // IO timeout should be taken as a normal case
                    return;
                }
                this.exceptionHandler.accept(apiTypeClass, t);
                return;
            } finally {
                closeWatch();
            }
        }
    } catch (ApiException e) {
        if (e.getCode() == HttpURLConnection.HTTP_GONE) {
            log.info("ResourceVersion {} expired, will retry w/o resourceVersion at the next time", getRelistResourceVersion());
            isLastSyncResourceVersionUnavailable = true;
        } else {
            this.exceptionHandler.accept(apiTypeClass, e);
        }
    } catch (Throwable t) {
        this.exceptionHandler.accept(apiTypeClass, t);
    }
}
Also used : CallGeneratorParams(io.kubernetes.client.util.CallGeneratorParams) V1ListMeta(io.kubernetes.client.openapi.models.V1ListMeta) WatchExpiredException(io.kubernetes.client.informer.exception.WatchExpiredException) ApiException(io.kubernetes.client.openapi.ApiException)

Example 13 with CallGeneratorParams

use of io.kubernetes.client.util.CallGeneratorParams in project java by kubernetes-client.

the class SharedInformerFactory method listerWatcherFor.

private <ApiType extends KubernetesObject, ApiListType extends KubernetesListObject> ListerWatcher<ApiType, ApiListType> listerWatcherFor(CallGenerator callGenerator, Class<ApiType> apiTypeClass, Class<ApiListType> apiListTypeClass) {
    if (apiClient.getReadTimeout() > 0) {
        // set read timeout zero to ensure client doesn't time out
        apiClient.setReadTimeout(0);
    }
    return new ListerWatcher<ApiType, ApiListType>() {

        @Override
        public ApiListType list(CallGeneratorParams params) throws ApiException {
            Call call = callGenerator.generate(params);
            return (ApiListType) apiClient.execute(call, apiListTypeClass).getData();
        }

        @Override
        public Watch<ApiType> watch(CallGeneratorParams params) throws ApiException {
            Call call = callGenerator.generate(params);
            // bind call with private http client to make sure read timeout is zero.
            call = apiClient.getHttpClient().newCall(call.request());
            return Watch.createWatch(apiClient, call, TypeToken.getParameterized(Watch.Response.class, apiTypeClass).getType());
        }
    };
}
Also used : Call(okhttp3.Call) Watch(io.kubernetes.client.util.Watch) CallGeneratorParams(io.kubernetes.client.util.CallGeneratorParams)

Aggregations

CallGeneratorParams (io.kubernetes.client.util.CallGeneratorParams)13 CoreV1Api (io.kubernetes.client.openapi.apis.CoreV1Api)9 Test (org.junit.Test)9 SharedInformerFactory (io.kubernetes.client.informer.SharedInformerFactory)8 ApiException (io.kubernetes.client.openapi.ApiException)8 V1ListMeta (io.kubernetes.client.openapi.models.V1ListMeta)8 V1Pod (io.kubernetes.client.openapi.models.V1Pod)8 V1PodList (io.kubernetes.client.openapi.models.V1PodList)7 JSON (io.kubernetes.client.openapi.JSON)6 Watch (io.kubernetes.client.util.Watch)6 V1ObjectMeta (io.kubernetes.client.openapi.models.V1ObjectMeta)5 WireMock.aResponse (com.github.tomakehurst.wiremock.client.WireMock.aResponse)4 Reconciler (io.kubernetes.client.extended.controller.reconciler.Reconciler)3 Request (io.kubernetes.client.extended.controller.reconciler.Request)3 Result (io.kubernetes.client.extended.controller.reconciler.Result)3 ApiClient (io.kubernetes.client.openapi.ApiClient)3 V1Status (io.kubernetes.client.openapi.models.V1Status)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3 Controller (io.kubernetes.client.extended.controller.Controller)2 SharedIndexInformer (io.kubernetes.client.informer.SharedIndexInformer)2