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 all 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

#### Improvements
* Add support for filtering labels by EXISTS/NOT_EXISTS via the single argument versions of `.withLabel` and `.withoutLabel`
* Schedule reconnect in case of HTTP_GONE when watching; the rescheduled connect will start from beginning of history by not specifying resourceVersion
#### Dependency Upgrade
* Updated Knative Serving to v0.9.90
* Update Tekton to v0.7.0
Expand Down
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 @@ -16,6 +16,8 @@

package io.fabric8.kubernetes.client.mock;

import static org.junit.jupiter.api.Assertions.assertTrue;

import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodBuilder;
import io.fabric8.kubernetes.api.model.Status;
Expand All @@ -27,19 +29,16 @@
import io.fabric8.kubernetes.client.Watch;
import io.fabric8.kubernetes.client.Watcher;
import io.fabric8.kubernetes.client.server.mock.KubernetesServer;
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.Test;
import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

import static org.junit.jupiter.api.Assertions.assertTrue;

@EnableRuleMigrationSupport
public class WatchOverHTTP {
static final Pod pod1 = new PodBuilder().withNewMetadata().withNamespace("test").withName("pod1")
Expand All @@ -50,6 +49,7 @@ public class WatchOverHTTP {
.build();
static final WatchEvent outdatedEvent = new WatchEventBuilder().withStatusObject(outdatedStatus).build();
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";
@Rule
public KubernetesServer server = new KubernetesServer(false);
Logger logger = LoggerFactory.getLogger(WatchTest.class);
Expand Down Expand Up @@ -92,55 +92,38 @@ public void onClose(KubernetesClientException cause) {}
}

@Test
public void testOutdated() throws InterruptedException {
logger.info("testOutdated");
public void testHttpErrorReconnectOutdatedAndModified() throws InterruptedException {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This file is not named properly and doesn't seem to be picked up by junit.

KubernetesClient client = server.getClient().inNamespace("test");

server.expect()
.withPath(path)
.andReturn(200, "Failed WebSocket Connection").once();
server.expect().withPath(path).andReturnChunked(200, outdatedEvent, "\n").once();

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();
}

@Override
public void onClose(KubernetesClientException cause) {
onCloseCalled[0] = true;
}
})){};
assertTrue(onCloseCalled[0]);
}

@Test
public void testHttpErrorReconnect() throws InterruptedException {
logger.info("testHttpErrorReconnect");
KubernetesClient client = server.getClient().inNamespace("test");
.withPath(path)
.andReturn(200, "Failed WebSocket Connection").once();

server.expect()
.withPath(path)
.andReturn(200, "Failed WebSocket Connection").once();
server.expect().withPath(path).andReturnChunked(503, new StatusBuilder().withCode(503).build()).times(6);
server.expect().withPath(path).andReturnChunked(200, outdatedEvent, "\n").once();
.withPath(path)
.andReturnChunked(200, outdatedEvent, "\n").once();
server.expect()
.withPath(pathWithoutResourceVersion)
.andReturnChunked(200, pod1, "\n").once();

final CountDownLatch closeLatch = new CountDownLatch(1);
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) {
throw new AssertionFailedError();
switch (action) {
case MODIFIED:
modifyLatch.countDown();
break;
default:
throw new AssertionFailedError();
}
}

@Override
public void onClose(KubernetesClientException cause) {
logger.debug("onClose", cause);
closeLatch.countDown();
}
})) /* autoclose */ {
assertTrue(closeLatch.await(3, TimeUnit.MINUTES));
assertTrue(modifyLatch.await(10, TimeUnit.SECONDS));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import static org.junit.Assert.assertTrue;

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 +30,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,39 +57,54 @@ 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
Expand Down Expand Up @@ -128,25 +142,28 @@ public void testHttpErrorReconnect() throws InterruptedException {
// accept watch and disconnect
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();
server.expect().withPath(path).andReturn(503, new StatusBuilder().withCode(503).build()).times(1);
// 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