io.fabric8.kubernetes.client.dsl.base.OperationSupport Java Examples

The following examples show how to use io.fabric8.kubernetes.client.dsl.base.OperationSupport. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KafkaCrdOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateStatusAsync(VertxTestContext context) throws IOException {
    KubernetesClient mockClient = mock(KubernetesClient.class);

    OkHttpClient mockOkHttp = mock(OkHttpClient.class);
    when(mockClient.adapt(eq(OkHttpClient.class))).thenReturn(mockOkHttp);
    URL fakeUrl = new URL("http", "my-host", 9443, "/");
    when(mockClient.getMasterUrl()).thenReturn(fakeUrl);
    Call mockCall = mock(Call.class);
    when(mockOkHttp.newCall(any(Request.class))).thenReturn(mockCall);
    ResponseBody body = ResponseBody.create(OperationSupport.JSON, "{ }");
    Response response = new Response.Builder().code(200).request(new Request.Builder().url(fakeUrl).build()).body(body).message("Created").protocol(Protocol.HTTP_1_1).build();
    when(mockCall.execute()).thenReturn(response);

    Checkpoint async = context.checkpoint();

    createResourceOperations(vertx, mockClient)
        .updateStatusAsync(resource())
        .onComplete(context.succeeding(kafka -> async.flag()));
}
 
Example #2
Source File: KafkaCrdOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateStatusWorksAfterUpgradeWithHttp422ResponseAboutApiVersionField(VertxTestContext context) throws IOException {
    KubernetesClient mockClient = mock(KubernetesClient.class);

    OkHttpClient mockOkHttp = mock(OkHttpClient.class);
    when(mockClient.adapt(eq(OkHttpClient.class))).thenReturn(mockOkHttp);
    URL fakeUrl = new URL("http", "my-host", 9443, "/");
    when(mockClient.getMasterUrl()).thenReturn(fakeUrl);
    Call mockCall = mock(Call.class);
    when(mockOkHttp.newCall(any(Request.class))).thenReturn(mockCall);
    ResponseBody body = ResponseBody.create(OperationSupport.JSON, "{\"kind\":\"Status\",\"apiVersion\":\"v1\",\"metadata\":{},\"status\":\"Failure\",\"message\":\"Kafka." + Constants.RESOURCE_GROUP_NAME + " \\\"my-cluster\\\" is invalid: apiVersion: Invalid value: \\\"" + Constants.RESOURCE_GROUP_NAME + "/" + Constants.V1ALPHA1 + "\\\": must be " + Constants.RESOURCE_GROUP_NAME + "/" + Constants.V1BETA1 + "\",\"reason\":\"Invalid\",\"details\":{\"name\":\"my-cluster\",\"group\":\"" + Constants.RESOURCE_GROUP_NAME + "\",\"kind\":\"Kafka\",\"causes\":[{\"reason\":\"FieldValueInvalid\",\"message\":\"Invalid value: \\\"" + Constants.RESOURCE_GROUP_NAME + "/" + Constants.V1ALPHA1 + "\\\": must be " + Constants.RESOURCE_GROUP_NAME + "/" + Constants.V1BETA1 + "\",\"field\":\"apiVersion\"}]},\"code\":422}");
    Response response = new Response.Builder().code(422).request(new Request.Builder().url(fakeUrl).build()).body(body).message("Unprocessable Entity").protocol(Protocol.HTTP_1_1).build();
    when(mockCall.execute()).thenReturn(response);

    Checkpoint async = context.checkpoint();
    createResourceOperations(vertx, mockClient)
        .updateStatusAsync(resource())
        .onComplete(context.succeeding(kafka -> async.flag()));

}
 
Example #3
Source File: KafkaCrdOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateStatusThrowsWhenHttp422ResponseWithOtherField(VertxTestContext context) throws IOException {
    KubernetesClient mockClient = mock(KubernetesClient.class);

    OkHttpClient mockOkHttp = mock(OkHttpClient.class);
    when(mockClient.adapt(eq(OkHttpClient.class))).thenReturn(mockOkHttp);
    URL fakeUrl = new URL("http", "my-host", 9443, "/");
    when(mockClient.getMasterUrl()).thenReturn(fakeUrl);
    Call mockCall = mock(Call.class);
    when(mockOkHttp.newCall(any(Request.class))).thenReturn(mockCall);
    ResponseBody body = ResponseBody.create(OperationSupport.JSON, "{\"kind\":\"Status\",\"apiVersion\":\"v1\",\"metadata\":{},\"status\":\"Failure\",\"message\":\"Kafka." + Constants.RESOURCE_GROUP_NAME + " \\\"my-cluster\\\" is invalid: apiVersion: Invalid value: \\\"" + Constants.RESOURCE_GROUP_NAME + "/" + Constants.V1ALPHA1 + "\\\": must be " + Constants.RESOURCE_GROUP_NAME + "/" + Constants.V1BETA1 + "\",\"reason\":\"Invalid\",\"details\":{\"name\":\"my-cluster\",\"group\":\"" + Constants.RESOURCE_GROUP_NAME + "\",\"kind\":\"Kafka\",\"causes\":[{\"reason\":\"FieldValueInvalid\",\"message\":\"Invalid value: \\\"" + Constants.RESOURCE_GROUP_NAME + "/" + Constants.V1ALPHA1 + "\\\": must be " + Constants.RESOURCE_GROUP_NAME + "/" + Constants.V1BETA1 + "\",\"field\":\"someOtherField\"}]},\"code\":422}");
    Response response = new Response.Builder().code(422).request(new Request.Builder().url(fakeUrl).build()).body(body).message("Unprocessable Entity").protocol(Protocol.HTTP_1_1).build();
    when(mockCall.execute()).thenReturn(response);

    Checkpoint async = context.checkpoint();
    createResourceOperations(vertx, mockClient)
        .updateStatusAsync(resource())
        .onComplete(context.failing(e -> context.verify(() -> {
            assertThat(e, instanceOf(KubernetesClientException.class));
            async.flag();
        })));

}
 
Example #4
Source File: KafkaCrdOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateStatusThrowsWhenHttp422ResponseWithNoBody(VertxTestContext context) throws IOException {
    KubernetesClient mockClient = mock(KubernetesClient.class);

    OkHttpClient mockOkHttp = mock(OkHttpClient.class);
    when(mockClient.adapt(eq(OkHttpClient.class))).thenReturn(mockOkHttp);
    URL fakeUrl = new URL("http", "my-host", 9443, "/");
    when(mockClient.getMasterUrl()).thenReturn(fakeUrl);
    Call mockCall = mock(Call.class);
    when(mockOkHttp.newCall(any(Request.class))).thenReturn(mockCall);
    ResponseBody body = ResponseBody.create(OperationSupport.JSON, "{ }");
    Response response = new Response.Builder().code(422).request(new Request.Builder().url(fakeUrl).build()).message("Unprocessable Entity").protocol(Protocol.HTTP_1_1).build();
    when(mockCall.execute()).thenReturn(response);

    Checkpoint async = context.checkpoint();
    createResourceOperations(vertx, mockClient)
        .updateStatusAsync(resource())
        .onComplete(context.failing(e -> context.verify(() -> {
            assertThat(e, instanceOf(KubernetesClientException.class));
            async.flag();
        })));
}
 
Example #5
Source File: KafkaCrdOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateStatusThrowsWhenHttp409Response(VertxTestContext context) throws IOException {
    KubernetesClient mockClient = mock(KubernetesClient.class);

    OkHttpClient mockOkHttp = mock(OkHttpClient.class);
    when(mockClient.adapt(eq(OkHttpClient.class))).thenReturn(mockOkHttp);
    URL fakeUrl = new URL("http", "my-host", 9443, "/");
    when(mockClient.getMasterUrl()).thenReturn(fakeUrl);
    Call mockCall = mock(Call.class);
    when(mockOkHttp.newCall(any(Request.class))).thenReturn(mockCall);
    ResponseBody body = ResponseBody.create(OperationSupport.JSON, "{ }");
    Response response = new Response.Builder().code(409).request(new Request.Builder().url(fakeUrl).build()).body(body).message("Conflict").protocol(Protocol.HTTP_1_1).build();
    when(mockCall.execute()).thenReturn(response);

    Checkpoint async = context.checkpoint();
    createResourceOperations(vertx, mockClient)
        .updateStatusAsync(resource())
        .onComplete(context.failing(e -> context.verify(() -> {
            assertThat(e, instanceOf(KubernetesClientException.class));
            async.flag();
        })));
}
 
Example #6
Source File: PodUpload.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
private static boolean uploadFile(OkHttpClient client, PodOperationContext context,
  OperationSupport operationSupport, Path pathToUpload)
  throws IOException, InterruptedException {

  final String file = context.getFile();
  final String directory = file.substring(0, file.lastIndexOf('/'));
  final String command = String.format(
    "mkdir -p %s && base64 -d - > %s", directory, file);
  final PodUploadWebSocketListener podUploadWebSocketListener = initWebSocket(
    buildCommandUrl(command, context, operationSupport), client);
  try (
    final FileInputStream fis = new FileInputStream(pathToUpload.toFile());
    final Base64InputStream b64In = new Base64InputStream(fis, true, 0, new byte[]{'\r', '\n'})
  ) {
    podUploadWebSocketListener.waitUntilReady(DEFAULT_CONNECTION_TIMEOUT_SECONDS);
    copy(b64In, podUploadWebSocketListener::send);
    podUploadWebSocketListener.waitUntilComplete(DEFAULT_COMPLETE_REQUEST_TIMEOUT_SECONDS);
    return true;
  }
}
 
Example #7
Source File: PodUpload.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
private static URL buildCommandUrl(String command, PodOperationContext context, OperationSupport operationSupport)
  throws UnsupportedEncodingException, MalformedURLException {

  final StringBuilder commandBuilder = new StringBuilder();
  commandBuilder.append("exec?");
  commandBuilder.append("command=sh&command=-c");
  commandBuilder.append("&command=");
  commandBuilder.append(URLUtils.encodeToUTF(command));
  if (context.getContainerId() != null && !context.getContainerId().isEmpty()) {
    commandBuilder.append("&container=").append(context.getContainerId());
  }
  commandBuilder.append("&stdin=true");
  commandBuilder.append("&stderr=true");
  return new URL(
    URLUtils.join(operationSupport.getResourceUrl().toString(), commandBuilder.toString()));
}
 
Example #8
Source File: BackwardsCompatibilityInterceptor.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
private static Response handleNewRequestAndProceed(Request request, String newUrl, ResourceKey target, Chain chain) throws IOException {
  Request.Builder newRequest = request.newBuilder()
    .url(newUrl);

  if (request.body() != null && !request.method().equalsIgnoreCase(PATCH)) {
    try (Buffer buffer = new Buffer()) {
      request.body().writeTo(buffer);

      Object object = Serialization.unmarshal(buffer.inputStream());
      if (object instanceof HasMetadata) {
        HasMetadata h = (HasMetadata) object;
        if (target != null) {
          h.setApiVersion(target.group + "/" + target.version);
        }
        newRequest = newRequest.method(request.method(), RequestBody.create(OperationSupport.JSON, Serialization.asJson(h)));
      }
    }
  }

  return chain.proceed(newRequest.build());
}
 
Example #9
Source File: ExecWebSocketListener.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public void onOpen(WebSocket webSocket, Response response) {
    try {
        if (in instanceof PipedInputStream && input != null) {
            input.connect((PipedInputStream) in);
        }
        if (out instanceof PipedOutputStream && output != null) {
            output.connect((PipedOutputStream) out);
        }
        if (err instanceof PipedOutputStream && error != null) {
            error.connect((PipedOutputStream) err);
        }
        if (errChannel instanceof PipedOutputStream && errorChannel != null) {
            errorChannel.connect((PipedOutputStream) errChannel);
        }

        webSocketRef.set(webSocket);
        executorService.submit(pumper);
        started.set(true);
        queue.add(true);
    } catch (IOException e) {
        queue.add(new KubernetesClientException(OperationSupport.createStatus(response)));
    } finally {
        if (listener != null) {
            listener.onOpen(response);
        }
    }
}
 
Example #10
Source File: ExecWebSocketListener.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {

    //If we already called onClosed() or onFailed() before, we need to abort.
    if (explicitlyClosed.get() || closed.get() || !failed.compareAndSet(false, true) ) {
      //We are not going to notify the listener, sicne we've already called onClose(), so let's log a debug/warning.
      if (LOGGER.isDebugEnabled()) {
        LOGGER.warn("Received [" + t.getClass().getCanonicalName() + "], with message:[" + t.getMessage() + "] after ExecWebSocketListener is closed, Ignoring.");
      }
      return;
    }

    try {
      Status status = OperationSupport.createStatus(response);
      LOGGER.error("Exec Failure: HTTP:" + status.getCode() + ". Message:" + status.getMessage(), t);
      //We only need to queue startup failures.
      if (!started.get()) {
        queue.add(new KubernetesClientException(status));
      }

      cleanUpOnce();
    } finally {
      if (listener != null) {
        listener.onFailure(t, response);
      }
    }
  }
 
Example #11
Source File: PodUpload.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public static boolean upload(OkHttpClient client, PodOperationContext context,
  OperationSupport operationSupport, Path pathToUpload)
  throws IOException, InterruptedException {

  if (Utils.isNotNullOrEmpty(context.getFile()) && pathToUpload.toFile().isFile()) {
    return uploadFile(client, context, operationSupport, pathToUpload);
  } else if (Utils.isNotNullOrEmpty(context.getDir()) && pathToUpload.toFile().isDirectory()) {
    return uploadDirectory(client, context, operationSupport, pathToUpload);
  }
  throw new IllegalArgumentException("Provided arguments are not valid (file, directory, path)");
}
 
Example #12
Source File: PodUploadTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() throws IOException {
  mockClient = Mockito.mock(OkHttpClient.class, Mockito.RETURNS_DEEP_STUBS);
  mockContext = Mockito.mock(PodOperationContext.class, Mockito.RETURNS_DEEP_STUBS);
  operationSupport = Mockito.mock(OperationSupport.class, Mockito.RETURNS_DEEP_STUBS);
  mockPathToUpload = Mockito.mock(Path.class, Mockito.RETURNS_DEEP_STUBS);
  mockWebSocket = Mockito.mock(WebSocket.class, Mockito.RETURNS_DEEP_STUBS);

  when(mockClient.newBuilder().readTimeout(anyLong(), any(TimeUnit.class)).build()).thenReturn(mockClient);
  when(operationSupport.getResourceUrl())
    .thenReturn(new URL("https://openshift.com:8443/api/v1/namespaces/default/pods/mock-pod/"));
}
 
Example #13
Source File: KogitoKubeConfig.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public URL getServiceOperationURL(final String namespace) throws MalformedURLException {
    final OperationSupport services = ((OperationSupport) this.kubernetesClient.services());
    return services.getNamespacedUrl(namespace);
}
 
Example #14
Source File: PodUpload.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
private static boolean uploadDirectory(OkHttpClient client, PodOperationContext context,
  OperationSupport operationSupport, Path pathToUpload)
  throws IOException, InterruptedException {

  final String command = String.format(
    "mkdir -p %1$s && base64 -d - | tar -C %1$s -xzf -", context.getDir());
  final PodUploadWebSocketListener podUploadWebSocketListener = initWebSocket(
    buildCommandUrl(command, context, operationSupport), client);
  try (
    final PipedOutputStream pos = new PipedOutputStream();
    final PipedInputStream pis = new PipedInputStream(pos);
    final Base64OutputStream b64Out = new Base64OutputStream(pos, true, 0, new byte[]{'\r', '\n'});
    final GZIPOutputStream gzip = new GZIPOutputStream(b64Out)

  ) {
    final CountDownLatch done = new CountDownLatch(1);
    final AtomicReference<IOException> readFileException = new AtomicReference<>(null);
    podUploadWebSocketListener.waitUntilReady(DEFAULT_CONNECTION_TIMEOUT_SECONDS);
    final Runnable readFiles = () -> {
      try (final TarArchiveOutputStream tar = new TarArchiveOutputStream(gzip)) {
        for (File file : pathToUpload.toFile().listFiles()) {
          addFileToTar(null, file, tar);
        }
        tar.flush();
      } catch (IOException ex) {
        readFileException.set(ex);
      } finally {
        done.countDown();
      }
    };
    final ExecutorService es = Executors.newSingleThreadExecutor();
    es.submit(readFiles);
    copy(pis, podUploadWebSocketListener::send);
    podUploadWebSocketListener.waitUntilComplete(DEFAULT_COMPLETE_REQUEST_TIMEOUT_SECONDS);
    final boolean doneGracefully = done.await(100, TimeUnit.SECONDS);
    es.shutdown();
    if (readFileException.get() != null) {
      throw readFileException.get();
    }
    return doneGracefully;
  }
}