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");
}
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);
}
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;
}
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;
}
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 })));
}
Aggregations