Search in sources :

Example 1 with Listener

use of io.fabric8.kubernetes.client.http.WebSocket.Listener in project titus-control-plane by Netflix.

the class DefaultFabric8IOConnector method kubeInformerEvents.

private Flux<PodEvent> kubeInformerEvents() {
    return Flux.create(sink -> {
        ResourceEventHandler<Pod> handler = new ResourceEventHandler<Pod>() {

            @Override
            public void onAdd(Pod pod) {
                Stopwatch stopwatch = Stopwatch.createStarted();
                try {
                    String taskId = pod.getMetadata().getName();
                    Pod old = pods.get(taskId);
                    pods = pods.plus(taskId, pod);
                    PodEvent podEvent;
                    if (old != null) {
                        podEvent = PodEvent.onUpdate(old, pod, findNode(pod));
                    // metrics.onUpdate(pod);
                    } else {
                        podEvent = PodEvent.onAdd(pod);
                    // metrics.onAdd(pod);
                    }
                    sink.next(podEvent);
                    logger.info("Pod Added: pod={}, sequenceNumber={}", formatPodEssentials(pod), podEvent.getSequenceNumber());
                    logger.debug("complete pod data: {}", pod);
                } finally {
                    logger.info("Pod informer onAdd: pod={}, elapsedMs={}", pod.getMetadata().getName(), stopwatch.elapsed().toMillis());
                }
            }

            @Override
            public void onUpdate(Pod oldPod, Pod newPod) {
                Stopwatch stopwatch = Stopwatch.createStarted();
                try {
                    String taskId = newPod.getMetadata().getName();
                    pods = pods.plus(taskId, newPod);
                    PodUpdatedEvent podEvent = PodEvent.onUpdate(oldPod, newPod, findNode(newPod));
                    sink.next(podEvent);
                    logger.info("Pod Updated: old={}, new={}, sequenceNumber={}", formatPodEssentials(oldPod), formatPodEssentials(newPod), podEvent.getSequenceNumber());
                    logger.debug("Complete pod data: old={}, new={}", oldPod, newPod);
                } finally {
                    logger.info("Pod informer onUpdate: pod={}, elapsedMs={}", newPod.getMetadata().getName(), stopwatch.elapsed().toMillis());
                }
            }

            @Override
            public void onDelete(Pod pod, boolean deletedFinalStateUnknown) {
                Stopwatch stopwatch = Stopwatch.createStarted();
                try {
                    String taskId = pod.getMetadata().getName();
                    pods = pods.minus(taskId);
                    PodDeletedEvent podEvent = PodEvent.onDelete(pod, deletedFinalStateUnknown, findNode(pod));
                    sink.next(podEvent);
                    logger.info("Pod Deleted: {}, deletedFinalStateUnknown={}, sequenceNumber={}", formatPodEssentials(pod), deletedFinalStateUnknown, podEvent.getSequenceNumber());
                    logger.debug("complete pod data: {}", pod);
                } finally {
                    logger.info("Pod informer onDelete: pod={}, elapsedMs={}", pod.getMetadata().getName(), stopwatch.elapsed().toMillis());
                }
            }
        };
        this.getPodInformer().addEventHandler(handler);
    // A listener cannot be removed from shared informer.
    // sink.onCancel(() -> ???);
    });
}
Also used : ResourceEventHandler(io.fabric8.kubernetes.client.informers.ResourceEventHandler) PodDeletedEvent(com.netflix.titus.runtime.connector.kubernetes.fabric8io.model.PodDeletedEvent) Pod(io.fabric8.kubernetes.api.model.Pod) Stopwatch(com.google.common.base.Stopwatch) PodEvent(com.netflix.titus.runtime.connector.kubernetes.fabric8io.model.PodEvent) PodUpdatedEvent(com.netflix.titus.runtime.connector.kubernetes.fabric8io.model.PodUpdatedEvent)

Example 2 with Listener

use of io.fabric8.kubernetes.client.http.WebSocket.Listener in project entando-k8s-controller-coordinator by entando-k8s.

the class ConfigListenerTest method shouldKillTheOperator.

@Test
void shouldKillTheOperator() {
    System.setProperty(EntandoOperatorSpiConfigProperty.ENTANDO_CONTROLLER_POD_NAME.getJvmSystemProperty(), "my-pod");
    // Given the operator is alive and listening to K8S resource events
    final File file = Paths.get("/tmp/EntandoControllerCoordinator.ready").toFile();
    Liveness.alive();
    assertTrue(file.exists());
    final ConfigListener configListener = new ConfigListener(new SimpleKubernetesClientDouble());
    // When the Operator loses the connection to the ConfigMap listener
    configListener.onClose(new WatcherException("Something went wrong"));
    // Then the operator has been killed
    assertFalse(file.exists());
}
Also used : SimpleKubernetesClientDouble(org.entando.kubernetes.controller.coordinator.common.SimpleKubernetesClientDouble) File(java.io.File) WatcherException(io.fabric8.kubernetes.client.WatcherException) Test(org.junit.jupiter.api.Test)

Example 3 with Listener

use of io.fabric8.kubernetes.client.http.WebSocket.Listener in project opscloud4 by ixrjog.

the class RemoteInvokeHandler method openKubernetesTerminal.

public static void openKubernetesTerminal(String sessionId, String instanceId, KubernetesConfig.Kubernetes kubernetes, KubernetesResource.Pod pod, KubernetesResource.Container container) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    KubernetesPodDriver.SimpleListener listener = new KubernetesPodDriver.SimpleListener();
    ExecWatch execWatch = KubernetesPodDriver.loginPodContainer(kubernetes, pod.getNamespace(), pod.getName(), container.getName(), listener, out);
    SessionOutput sessionOutput = new SessionOutput(sessionId, instanceId);
    // 启动线程处理会话
    WatchKubernetesTerminalOutputTask run = new WatchKubernetesTerminalOutputTask(sessionOutput, out);
    Thread thread = new Thread(run);
    thread.start();
    KubernetesSession kubernetesSession = KubernetesSession.builder().sessionId(sessionId).instanceId(instanceId).execWatch(execWatch).watchKubernetesTerminalOutputTask(run).build();
    kubernetesSession.setSessionOutput(sessionOutput);
    KubernetesSessionContainer.addSession(kubernetesSession);
}
Also used : WatchKubernetesTerminalOutputTask(com.baiyi.opscloud.sshcore.task.kubernetes.WatchKubernetesTerminalOutputTask) ExecWatch(io.fabric8.kubernetes.client.dsl.ExecWatch) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) KubernetesPodDriver(com.baiyi.opscloud.datasource.kubernetes.driver.KubernetesPodDriver)

Example 4 with Listener

use of io.fabric8.kubernetes.client.http.WebSocket.Listener in project kubernetes-client by fabric8io.

the class JdkHttpClientImpl method buildAsync.

public CompletableFuture<WebSocket> buildAsync(JdkWebSocketImpl.BuilderImpl webSocketBuilder, Listener listener) {
    JdkWebSocketImpl.BuilderImpl copy = webSocketBuilder.copy();
    for (Interceptor interceptor : builder.interceptors.values()) {
        interceptor.before(copy, new JdkHttpRequestImpl(null, copy.asRequest()));
    }
    CompletableFuture<WebSocket> result = new CompletableFuture<>();
    CompletableFuture<WebSocketResponse> cf = internalBuildAsync(copy, listener);
    for (Interceptor interceptor : builder.interceptors.values()) {
        cf = cf.thenCompose(response -> {
            if (response.wshse != null && response.wshse.getResponse() != null && interceptor.afterFailure(copy, new JdkHttpResponseImpl<>(response.wshse.getResponse()))) {
                return this.internalBuildAsync(copy, listener);
            }
            return CompletableFuture.completedFuture(response);
        });
    }
    // map back to the expected convention with the future completed by the response exception
    cf.whenComplete((r, t) -> {
        if (t != null) {
            result.completeExceptionally(t);
        } else if (r != null) {
            if (r.wshse != null) {
                result.completeExceptionally(new io.fabric8.kubernetes.client.http.WebSocketHandshakeException(new JdkHttpResponseImpl<>(r.wshse.getResponse())).initCause(r.wshse));
            } else {
                result.complete(r.webSocket);
            }
        } else {
            // shouldn't happen
            result.complete(null);
        }
    });
    return result;
}
Also used : BodyHandlers(java.net.http.HttpResponse.BodyHandlers) Listener(io.fabric8.kubernetes.client.http.WebSocket.Listener) HttpRequest(io.fabric8.kubernetes.client.http.HttpRequest) BodySubscribers(java.net.http.HttpResponse.BodySubscribers) BodyHandler(java.net.http.HttpResponse.BodyHandler) BodySubscriber(java.net.http.HttpResponse.BodySubscriber) IOException(java.io.IOException) CompletableFuture(java.util.concurrent.CompletableFuture) CompletionException(java.util.concurrent.CompletionException) HttpResponse(io.fabric8.kubernetes.client.http.HttpResponse) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) InterruptedIOException(java.io.InterruptedIOException) StandardCharsets(java.nio.charset.StandardCharsets) ExecutionException(java.util.concurrent.ExecutionException) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) Interceptor(io.fabric8.kubernetes.client.http.Interceptor) WebSocketHandshakeException(java.net.http.WebSocketHandshakeException) Optional(java.util.Optional) WebSocket(io.fabric8.kubernetes.client.http.WebSocket) URI(java.net.URI) HttpClient(io.fabric8.kubernetes.client.http.HttpClient) InputStream(java.io.InputStream) WebSocket(io.fabric8.kubernetes.client.http.WebSocket) CompletableFuture(java.util.concurrent.CompletableFuture) Interceptor(io.fabric8.kubernetes.client.http.Interceptor)

Example 5 with Listener

use of io.fabric8.kubernetes.client.http.WebSocket.Listener in project kubernetes-client by fabric8io.

the class JdkHttpClientImpl method internalBuildAsync.

/**
 * Convert the invocation of a JDK build async into a holder of both the exception and the response
 */
public CompletableFuture<WebSocketResponse> internalBuildAsync(JdkWebSocketImpl.BuilderImpl webSocketBuilder, Listener listener) {
    java.net.http.HttpRequest request = webSocketBuilder.asRequest();
    java.net.http.WebSocket.Builder newBuilder = this.httpClient.newWebSocketBuilder();
    request.headers().map().forEach((k, v) -> v.forEach(s -> newBuilder.header(k, s)));
    if (webSocketBuilder.subprotocol != null) {
        newBuilder.subprotocols(webSocketBuilder.subprotocol);
    }
    // TODO: this should probably be made clearer in the docs
    if (this.builder.readTimeout != null) {
        newBuilder.connectTimeout(this.builder.readTimeout);
    }
    AtomicLong queueSize = new AtomicLong();
    // use a responseholder to convey both the exception and the websocket
    CompletableFuture<WebSocketResponse> response = new CompletableFuture<>();
    URI uri = request.uri();
    if (uri.getScheme().startsWith("http")) {
        // the jdk logic expects a ws uri
        // after the https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8245245 it just does the reverse of this
        // to convert back to http(s) ...
        uri = URI.create("ws" + uri.toString().substring(4));
    }
    newBuilder.buildAsync(uri, new JdkWebSocketImpl.ListenerAdapter(listener, queueSize)).whenComplete((w, t) -> {
        if (t instanceof CompletionException && t.getCause() != null) {
            t = t.getCause();
        }
        if (t instanceof java.net.http.WebSocketHandshakeException) {
            response.complete(new WebSocketResponse(new JdkWebSocketImpl(queueSize, w), (WebSocketHandshakeException) t));
        } else if (t != null) {
            response.completeExceptionally(t);
        } else {
            response.complete(new WebSocketResponse(new JdkWebSocketImpl(queueSize, w), null));
        }
    });
    return response;
}
Also used : BodyHandlers(java.net.http.HttpResponse.BodyHandlers) Listener(io.fabric8.kubernetes.client.http.WebSocket.Listener) HttpRequest(io.fabric8.kubernetes.client.http.HttpRequest) BodySubscribers(java.net.http.HttpResponse.BodySubscribers) BodyHandler(java.net.http.HttpResponse.BodyHandler) BodySubscriber(java.net.http.HttpResponse.BodySubscriber) IOException(java.io.IOException) CompletableFuture(java.util.concurrent.CompletableFuture) CompletionException(java.util.concurrent.CompletionException) HttpResponse(io.fabric8.kubernetes.client.http.HttpResponse) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) InterruptedIOException(java.io.InterruptedIOException) StandardCharsets(java.nio.charset.StandardCharsets) ExecutionException(java.util.concurrent.ExecutionException) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) Interceptor(io.fabric8.kubernetes.client.http.Interceptor) WebSocketHandshakeException(java.net.http.WebSocketHandshakeException) Optional(java.util.Optional) WebSocket(io.fabric8.kubernetes.client.http.WebSocket) URI(java.net.URI) HttpClient(io.fabric8.kubernetes.client.http.HttpClient) InputStream(java.io.InputStream) URI(java.net.URI) WebSocket(io.fabric8.kubernetes.client.http.WebSocket) AtomicLong(java.util.concurrent.atomic.AtomicLong) CompletableFuture(java.util.concurrent.CompletableFuture) CompletionException(java.util.concurrent.CompletionException) WebSocketHandshakeException(java.net.http.WebSocketHandshakeException)

Aggregations

ArrayList (java.util.ArrayList)77 GenericKafkaListener (io.strimzi.api.kafka.model.listener.arraylistener.GenericKafkaListener)61 GenericKafkaListenerBuilder (io.strimzi.api.kafka.model.listener.arraylistener.GenericKafkaListenerBuilder)43 List (java.util.List)43 Secret (io.fabric8.kubernetes.api.model.Secret)42 Map (java.util.Map)41 KafkaResources (io.strimzi.api.kafka.model.KafkaResources)40 HashMap (java.util.HashMap)39 Reconciliation (io.strimzi.operator.common.Reconciliation)36 Service (io.fabric8.kubernetes.api.model.Service)34 Collectors (java.util.stream.Collectors)31 SecretOperator (io.strimzi.operator.common.operator.resource.SecretOperator)30 Pod (io.fabric8.kubernetes.api.model.Pod)27 Kafka (io.strimzi.api.kafka.model.Kafka)25 Ingress (io.fabric8.kubernetes.api.model.networking.v1.Ingress)24 HashSet (java.util.HashSet)24 Tag (org.junit.jupiter.api.Tag)24 Route (io.fabric8.openshift.api.model.Route)22 PlatformFeaturesAvailability (io.strimzi.operator.PlatformFeaturesAvailability)22 KafkaCluster (io.strimzi.operator.cluster.model.KafkaCluster)22