Search in sources :

Example 1 with WebSocket

use of io.fabric8.kubernetes.client.http.WebSocket in project devspaces-images by redhat-developer.

the class IngressServerExposerTest method shouldReplaceServerNamePlaceholders.

@Test
public void shouldReplaceServerNamePlaceholders() {
    // given
    Map<String, String> annotations = new HashMap<>();
    annotations.put("ssl", "true");
    annotations.put("websocket-service", SERVICE_NAME_PLACEHOLDER);
    IngressServerExposer<KubernetesEnvironment> exposer = new IngressServerExposer<>(serviceExposureStrategy, annotations, null, "");
    KubernetesEnvironment env = KubernetesEnvironment.builder().build();
    Map<String, ServerConfig> externalServers = new HashMap<>();
    externalServers.put("ide", new ServerConfigImpl("6543", "http", "/", emptyMap()));
    // when
    exposer.expose(env, "editor", "ide", "server123", new ServicePort(), externalServers);
    // then
    Collection<Ingress> ingresses = env.getIngresses().values();
    assertEquals(ingresses.size(), 1);
    Ingress ingress = ingresses.iterator().next();
    assertEquals(ingress.getMetadata().getAnnotations().get("ssl"), "true");
    assertEquals(ingress.getMetadata().getAnnotations().get("websocket-service"), "ide");
}
Also used : ServerConfig(org.eclipse.che.api.core.model.workspace.config.ServerConfig) ServicePort(io.fabric8.kubernetes.api.model.ServicePort) HashMap(java.util.HashMap) KubernetesEnvironment(org.eclipse.che.workspace.infrastructure.kubernetes.environment.KubernetesEnvironment) Ingress(io.fabric8.kubernetes.api.model.networking.v1.Ingress) ServerConfigImpl(org.eclipse.che.api.workspace.server.model.impl.ServerConfigImpl) Test(org.testng.annotations.Test)

Example 2 with WebSocket

use of io.fabric8.kubernetes.client.http.WebSocket in project devspaces-images by redhat-developer.

the class KubernetesDeployments method watchEvents.

/**
 * Registers a specified handler for handling events about changes in pods containers. Registering
 * several handlers doesn't create multiple websocket connections, so it is efficient to call this
 * method several times instead of using composite handler to combine other handlers.
 *
 * @param handler pod container events handler
 * @throws InfrastructureException if any error occurs while watcher starting
 */
public void watchEvents(PodEventHandler handler) throws InfrastructureException {
    if (containerWatch == null) {
        final Watcher<Event> watcher = new Watcher<>() {

            @Override
            public void eventReceived(Action action, Event event) {
                ObjectReference involvedObject = event.getInvolvedObject();
                if (POD_OBJECT_KIND.equals(involvedObject.getKind()) || REPLICASET_OBJECT_KIND.equals(involvedObject.getKind()) || DEPLOYMENT_OBJECT_KIND.equals(involvedObject.getKind())) {
                    String podName = involvedObject.getName();
                    String lastTimestamp = event.getLastTimestamp();
                    if (lastTimestamp == null) {
                        String firstTimestamp = event.getFirstTimestamp();
                        if (firstTimestamp != null) {
                            // Done in the same way like it made in
                            // https://github.com/kubernetes/kubernetes/pull/86557
                            lastTimestamp = firstTimestamp;
                        } else {
                            LOG.debug("lastTimestamp and firstTimestamp are undefined. Event: {}.  Fallback to the current time.", event);
                            lastTimestamp = PodEvents.convertDateToEventTimestamp(new Date());
                        }
                    }
                    PodEvent podEvent = new PodEvent(podName, getContainerName(involvedObject.getFieldPath()), event.getReason(), event.getMessage(), event.getMetadata().getCreationTimestamp(), lastTimestamp);
                    try {
                        if (happenedAfterWatcherInitialization(podEvent)) {
                            containerEventsHandlers.forEach(h -> h.handle(podEvent));
                        }
                    } catch (ParseException e) {
                        LOG.error("Failed to parse last timestamp of the event. Cause: {}. Event: {}", e.getMessage(), podEvent, e);
                    }
                }
            }

            @Override
            public void onClose(WatcherException ignored) {
            }

            /**
             * Returns the container name if the event is related to container. When the event is
             * related to container `fieldPath` field contain information in the following format:
             * `spec.container{web}`, where `web` is container name
             */
            private String getContainerName(String fieldPath) {
                String containerName = null;
                if (fieldPath != null) {
                    Matcher containerFieldMatcher = CONTAINER_FIELD_PATH_PATTERN.matcher(fieldPath);
                    if (containerFieldMatcher.matches()) {
                        containerName = containerFieldMatcher.group(CONTAINER_NAME_GROUP);
                    }
                }
                return containerName;
            }

            /**
             * Returns true if 'lastTimestamp' of the event is *after* the time of the watcher
             * initialization
             */
            private boolean happenedAfterWatcherInitialization(PodEvent event) throws ParseException {
                String eventLastTimestamp = event.getLastTimestamp();
                Date eventLastTimestampDate = PodEvents.convertEventTimestampToDate(eventLastTimestamp);
                return eventLastTimestampDate.after(watcherInitializationDate);
            }
        };
        try {
            watcherInitializationDate = new Date();
            containerWatch = clientFactory.create(workspaceId).v1().events().inNamespace(namespace).watch(watcher);
        } catch (KubernetesClientException ex) {
            throw new KubernetesInfrastructureException(ex);
        }
    }
    containerEventsHandlers.add(handler);
}
Also used : Matcher(java.util.regex.Matcher) Watcher(io.fabric8.kubernetes.client.Watcher) LogWatcher(org.eclipse.che.workspace.infrastructure.kubernetes.namespace.log.LogWatcher) PodEvent(org.eclipse.che.workspace.infrastructure.kubernetes.namespace.event.PodEvent) KubernetesInfrastructureException(org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesInfrastructureException) Date(java.util.Date) WatcherException(io.fabric8.kubernetes.client.WatcherException) LocalObjectReference(io.fabric8.kubernetes.api.model.LocalObjectReference) ObjectReference(io.fabric8.kubernetes.api.model.ObjectReference) Event(io.fabric8.kubernetes.api.model.Event) PodEvent(org.eclipse.che.workspace.infrastructure.kubernetes.namespace.event.PodEvent) ParseException(java.text.ParseException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 3 with WebSocket

use of io.fabric8.kubernetes.client.http.WebSocket 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 4 with WebSocket

use of io.fabric8.kubernetes.client.http.WebSocket 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)

Example 5 with WebSocket

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

the class PodUploadWebSocketListenerTest method testSendShouldTruncateAndSendFlaggedWebSocketData.

@Test
void testSendShouldTruncateAndSendFlaggedWebSocketData() {
    final WebSocket mockedWebSocket = Mockito.mock(WebSocket.class);
    podUploadWebSocketListener.onOpen(mockedWebSocket);
    final byte[] toSend = new byte[] { 1, 3, 3, 7, 0 };
    podUploadWebSocketListener.send(toSend, 0, 4);
    verify(mockedWebSocket, times(1)).send(eq(ByteBuffer.wrap(new byte[] { (byte) 0, (byte) 1, (byte) 3, (byte) 3, (byte) 7 })));
}
Also used : WebSocket(io.fabric8.kubernetes.client.http.WebSocket) Test(org.junit.jupiter.api.Test)

Aggregations

WebSocket (io.fabric8.kubernetes.client.http.WebSocket)9 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)6 HttpClient (io.fabric8.kubernetes.client.http.HttpClient)5 Status (io.fabric8.kubernetes.api.model.Status)4 IOException (java.io.IOException)4 Watcher (io.fabric8.kubernetes.client.Watcher)3 HttpResponse (io.fabric8.kubernetes.client.http.HttpResponse)3 Matcher (java.util.regex.Matcher)3 Event (io.fabric8.kubernetes.api.model.Event)2 LocalObjectReference (io.fabric8.kubernetes.api.model.LocalObjectReference)2 ObjectReference (io.fabric8.kubernetes.api.model.ObjectReference)2 ServicePort (io.fabric8.kubernetes.api.model.ServicePort)2 Ingress (io.fabric8.kubernetes.api.model.networking.v1.Ingress)2 WatcherException (io.fabric8.kubernetes.client.WatcherException)2 ExecListener (io.fabric8.kubernetes.client.dsl.ExecListener)2 HttpRequest (io.fabric8.kubernetes.client.http.HttpRequest)2 Interceptor (io.fabric8.kubernetes.client.http.Interceptor)2 Listener (io.fabric8.kubernetes.client.http.WebSocket.Listener)2 WebSocketHandshakeException (io.fabric8.kubernetes.client.http.WebSocketHandshakeException)2 InputStream (java.io.InputStream)2