-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
WatchConnectionManager.java
156 lines (138 loc) · 5.97 KB
/
WatchConnectionManager.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
/**
* Copyright (C) 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.fabric8.kubernetes.client.dsl.internal;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.KubernetesResourceList;
import io.fabric8.kubernetes.api.model.ListOptions;
import io.fabric8.kubernetes.api.model.Status;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.Watcher;
import io.fabric8.kubernetes.client.http.HttpClient;
import io.fabric8.kubernetes.client.http.HttpResponse;
import io.fabric8.kubernetes.client.http.WebSocket;
import io.fabric8.kubernetes.client.http.WebSocket.Builder;
import io.fabric8.kubernetes.client.http.WebSocketHandshakeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.HttpURLConnection.HTTP_UNAVAILABLE;
/**
* Manages a WebSocket and listener per request
*/
public class WatchConnectionManager<T extends HasMetadata, L extends KubernetesResourceList<T>>
extends AbstractWatchManager<T> {
public static final int BACKOFF_MAX_EXPONENT = 5;
private static final Logger logger = LoggerFactory.getLogger(WatchConnectionManager.class);
protected WatcherWebSocketListener<T> listener;
private volatile CompletableFuture<WebSocket> websocketFuture;
private WebSocket websocket;
private volatile boolean ready;
static void closeWebSocket(WebSocket webSocket) {
if (webSocket != null) {
logger.debug("Closing websocket {}", webSocket);
try {
if (!webSocket.sendClose(1000, null)) {
logger.debug("Websocket already closed {}", webSocket);
}
} catch (IllegalStateException e) {
logger.error("invalid code for websocket: {} {}", e.getClass(), e.getMessage());
}
}
}
public WatchConnectionManager(final HttpClient client, final BaseOperation<T, L, ?> baseOperation,
final ListOptions listOptions, final Watcher<T> watcher, final int reconnectInterval, final int reconnectLimit,
long websocketTimeout, int maxIntervalExponent) throws MalformedURLException {
super(watcher, baseOperation, listOptions, reconnectLimit, reconnectInterval, maxIntervalExponent, () -> client.newBuilder()
.readTimeout(websocketTimeout, TimeUnit.MILLISECONDS)
.build());
}
public WatchConnectionManager(final HttpClient client, final BaseOperation<T, L, ?> baseOperation,
final ListOptions listOptions, final Watcher<T> watcher, final int reconnectInterval, final int reconnectLimit,
long websocketTimeout) throws MalformedURLException {
// Default max 32x slowdown from base interval
this(client, baseOperation, listOptions, watcher, reconnectInterval, reconnectLimit, websocketTimeout,
BACKOFF_MAX_EXPONENT);
}
@Override
protected synchronized void closeRequest() {
closeWebSocket(websocket);
Optional.ofNullable(this.websocketFuture).ifPresent(theFuture -> {
this.websocketFuture = null;
theFuture.whenComplete((w, t) -> {
if (w != null) {
closeWebSocket(w);
}
});
});
}
synchronized WatcherWebSocketListener<T> getListener() {
return listener;
}
public CompletableFuture<WebSocket> getWebsocketFuture() {
return websocketFuture;
}
@Override
protected void onMessage(String message) {
// for consistency we only want to process the message when we're open
if (this.websocketFuture != null) {
super.onMessage(message);
}
}
@Override
protected void start(URL url, Map<String, String> headers) {
this.listener = new WatcherWebSocketListener<>(this);
Builder builder = client.newWebSocketBuilder();
headers.forEach(builder::header);
builder.uri(URI.create(url.toString()));
this.websocketFuture = builder.buildAsync(this.listener).handle((w, t) -> {
if (t != null) {
if (t instanceof WebSocketHandshakeException) {
WebSocketHandshakeException wshe = (WebSocketHandshakeException) t;
HttpResponse<?> response = wshe.getResponse();
final int code = response.code();
// We do not expect a 200 in response to the websocket connection. If it occurs, we throw
// an exception and try the watch via a persistent HTTP Get.
// Newer Kubernetes might also return 503 Service Unavailable in case WebSockets are not supported
Status status = OperationSupport.createStatus(response);
if (HTTP_OK == code || HTTP_UNAVAILABLE == code) {
throw OperationSupport.requestFailure(client.newHttpRequestBuilder().url(url).build(), status,
"Received " + code + " on websocket");
}
logger.warn("Exec Failure: HTTP {}, Status: {} - {}", code, status.getCode(), status.getMessage());
t = OperationSupport.requestFailure(client.newHttpRequestBuilder().url(url).build(), status);
}
if (ready) {
// if we're not ready yet, that means we're waiting on the future and there's
// no need to invoke the reconnect logic
listener.onError(w, t);
}
throw KubernetesClientException.launderThrowable(t);
}
if (w != null) {
this.ready = true;
this.websocket = w;
}
return w;
});
}
}