Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

schedule reconnect in case of HTTP_GONE #1800

Merged
merged 6 commits into from
Oct 9, 2019
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -255,17 +255,13 @@ public void onMessage(WebSocket webSocket, String message) {
} else if (object instanceof Status) {
Status status = (Status) object;

// The resource version no longer exists - this has to be handled by the caller.
if (status.getCode() == HTTP_GONE) {
webSocketRef.set(null); // lose the ref: closing in close() would only generate a Broken pipe
// exception
// shut down executor, etc.
closeEvent(new KubernetesClientException(status));
close();
return;
logger.info("The resource version {} no longer exists. Scheduling a reconnect.", resourceVersion.get());
resourceVersion.set(null);
scheduleReconnect();
} else {
logger.error("Error received: {}", status.toString());
}

logger.error("Error received: {}", status.toString());
} else {
logger.error("Unknown message received: {}", message);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

package io.fabric8.kubernetes.client.dsl.internal;

import static java.net.HttpURLConnection.HTTP_GONE;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.KubernetesResource;
Expand All @@ -28,22 +30,28 @@
import io.fabric8.kubernetes.client.dsl.base.BaseOperation;
import io.fabric8.kubernetes.client.dsl.base.OperationSupport;
import io.fabric8.kubernetes.client.utils.Utils;
import okhttp3.*;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.BufferedSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import static java.net.HttpURLConnection.HTTP_GONE;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.BufferedSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WatchHTTPManager<T extends HasMetadata, L extends KubernetesResourceList<T>> implements
Watch {
Expand Down Expand Up @@ -265,16 +273,14 @@ public void onMessage(String messageSource) throws IOException {
}
} else if (object instanceof Status) {
Status status = (Status) object;
// The resource version no longer exists - this has to be handled by the caller.

if (status.getCode() == HTTP_GONE) {
// exception
// shut down executor, etc.
close();
watcher.onClose(new KubernetesClientException(status));
return;
logger.info("The resource version {} no longer exists. Scheduling a reconnect.", resourceVersion.get());
resourceVersion.set(null);
scheduleReconnect();
} else {
logger.error("Error received: {}", status.toString());
}

logger.error("Error received: {}", status.toString());
} else {
logger.error("Unknown message received: {}", messageSource);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@

import static org.junit.Assert.assertTrue;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodBuilder;
import io.fabric8.kubernetes.api.model.Status;
Expand All @@ -29,12 +31,10 @@
import io.fabric8.kubernetes.client.Watch;
import io.fabric8.kubernetes.client.Watcher;
import io.fabric8.kubernetes.client.server.mock.KubernetesServer;
import junit.framework.AssertionFailedError;

import java.net.HttpURLConnection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import junit.framework.AssertionFailedError;
import org.junit.Rule;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
Expand All @@ -58,38 +58,92 @@ public class WatchTest {
.build();
static final WatchEvent outdatedEvent = new WatchEventBuilder().withStatusObject(outdatedStatus).build();

private static final ObjectMapper mapper = new ObjectMapper();

@Test
public void testDeletedAndOutdated() throws InterruptedException {
public void testDeletedOutdatedAndAdded() throws InterruptedException {
logger.info("testDeletedAndOutdated");
KubernetesClient client = server.getClient().inNamespace("test");

final String path = "/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&resourceVersion=1&watch=true";
final String pathWithoutResourceVersion = "/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&watch=true";

// DELETED event, then history outdated
server.expect()
.withPath("/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&resourceVersion=1&watch=true")
.withPath(path)
.andUpgradeToWebSocket().open().waitFor(2000).andEmit(new WatchEvent(pod1, "DELETED")).waitFor(2000)
.andEmit(outdatedEvent).done().once();

// ADDED event
server.expect()
.withPath(pathWithoutResourceVersion)
.andUpgradeToWebSocket().open().waitFor(2000).andEmit(new WatchEvent(pod1, "ADDED")).done().once();

final CountDownLatch deleteLatch = new CountDownLatch(1);
final CountDownLatch closeLatch = new CountDownLatch(1);
final CountDownLatch addLatch = new CountDownLatch(1);
final boolean[] onCloseCalled = {false};
try (Watch watch = client.pods().withName("pod1").withResourceVersion("1").watch(new Watcher<Pod>() {
@Override
public void eventReceived(Action action, Pod resource) {
switch (action) {
case DELETED:
deleteLatch.countDown();
break;
case ADDED:
addLatch.countDown();
break;
default:
throw new AssertionFailedError();
}
}

@Override
public void onClose(KubernetesClientException cause) {
closeLatch.countDown();
onCloseCalled[0] =true;
}
})) /* autoclose */ {
assertTrue(deleteLatch.await(10, TimeUnit.SECONDS));
assertTrue(closeLatch.await(10, TimeUnit.SECONDS));
assertTrue(addLatch.await(10, TimeUnit.SECONDS));
}
assertTrue(onCloseCalled[0]);
}

@Test
public void testHttpOutdatedAndModified() throws InterruptedException,
JsonProcessingException {
KubernetesClient client = server.getClient().inNamespace("test");

final String path = "/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&resourceVersion=1&watch=true";
final String pathWithoutResourceVersion = "/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&watch=true";

server.expect()
.withPath(path)
.andReturn(200, new StatusBuilder().withCode(200).build()).once();
server.expect()
.withPath(path)
.andReturn(200, mapper.writeValueAsString(outdatedEvent) + '\n').once();
honnix marked this conversation as resolved.
Show resolved Hide resolved
server.expect()
.withPath(pathWithoutResourceVersion)
.andReturn(201, mapper.writeValueAsString(pod1) + '\n').once();

final CountDownLatch modifyLatch = new CountDownLatch(1);
try (Watch watch = client.pods().withName("pod1").withResourceVersion("1").watch(new Watcher<Pod>() {
@Override
public void eventReceived(Action action, Pod resource) {
switch (action) {
case MODIFIED:
modifyLatch.countDown();
break;
default:
throw new AssertionFailedError();
}
}

@Override
public void onClose(KubernetesClientException cause) {
}
})) /* autoclose */ {
assertTrue(modifyLatch.await(10, TimeUnit.SECONDS));
}
}

Expand Down Expand Up @@ -129,24 +183,27 @@ public void testHttpErrorReconnect() throws InterruptedException {
server.expect().withPath(path).andUpgradeToWebSocket().open().done().once();
// refuse reconnect attempts 6 times
server.expect().withPath(path).andReturn(503, new StatusBuilder().withCode(503).build()).times(6);
// accept next reconnect and send outdated event to stop the watch
server.expect().withPath(path).andUpgradeToWebSocket().open(outdatedEvent).done().once();
// accept next reconnect and send ADDED event
server.expect().withPath(path)
.andUpgradeToWebSocket().open(new WatchEvent(pod1, "ADDED")).done().once();

final CountDownLatch closeLatch = new CountDownLatch(1);
final CountDownLatch addLatch = new CountDownLatch(1);
final boolean[] onCloseCalled = {false};
try (Watch watch = client.pods().withName("pod1").withResourceVersion("1").watch(new Watcher<Pod>() {
@Override
public void eventReceived(Action action, Pod resource) {
throw new AssertionFailedError();
addLatch.countDown();
}

@Override
public void onClose(KubernetesClientException cause) {
logger.debug("onClose", cause);
closeLatch.countDown();
onCloseCalled[0] =true;
}
})) /* autoclose */ {
assertTrue(closeLatch.await(3, TimeUnit.MINUTES));
assertTrue(addLatch.await(3, TimeUnit.MINUTES));
}
assertTrue(onCloseCalled[0]);
}

@Test
Expand Down