io.fabric8.kubernetes.api.model.StatusBuilder Java Examples

The following examples show how to use io.fabric8.kubernetes.api.model.StatusBuilder. 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: TemplateTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateWithHandler() {
  Template template = new TemplateBuilder()
    .editOrNewMetadata()
    .withName("tmpl3")
    .withNamespace("test")
    .endMetadata()
    .build();

  server.expect().withPath("/apis/template.openshift.io/v1/namespaces/test/templates").andReturn(200, template).once();
  server.expect().withPath("/apis/template.openshift.io/v1/namespaces/test/templates/tmpl3").andReturn(404, new StatusBuilder().withCode(404).build()).once();

  OpenShiftClient client = server.getOpenshiftClient();

  Template created = client.resource(template).createOrReplace();
  assertNotNull(created);
}
 
Example #2
Source File: CreateOrReplaceResourceTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testResourceCreateFromLoad() throws Exception {
  server.expect().get().withPath("/api/v1/namespaces/test/pods/nginx").andReturn(404, new StatusBuilder().build()).always();

  server.expect().post().withPath("/api/v1/namespaces/test/pods").andReturn(201, new PodBuilder()
    .withNewMetadata().withResourceVersion("12345").and().build()).once();

  KubernetesClient client = server.getClient();
  List<HasMetadata> result = client.load(getClass().getResourceAsStream("/test-pod-create-from-load.yml")).createOrReplace();
  assertNotNull(result);
  assertEquals(1, result.size());
  Pod pod = (Pod) result.get(0);
  assertEquals("12345", pod.getMetadata().getResourceVersion());

  RecordedRequest request = server.getMockServer().takeRequest();
  assertEquals("/api/v1/namespaces/test/pods/nginx", request.getPath());

  request = server.getMockServer().takeRequest();
  Pod requestPod = new ObjectMapper().readerFor(Pod.class).readValue(request.getBody().inputStream());
  assertEquals("nginx", requestPod.getMetadata().getName());
}
 
Example #3
Source File: CreateOrReplaceResourceTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateFromLoad() throws Exception {
  server.expect().get().withPath("/api/v1/namespaces/test/pods/nginx").andReturn(404, new StatusBuilder().build()).always();

  server.expect().post().withPath("/api/v1/namespaces/test/pods").andReturn(201, new PodBuilder()
    .withNewMetadata().withResourceVersion("12345").and().build()).once();

  KubernetesClient client = server.getClient();
  Pod pod = client.pods().load(getClass().getResourceAsStream("/test-pod-create-from-load.yml")).createOrReplace();
  assertNotNull(pod);
  assertEquals("12345", pod.getMetadata().getResourceVersion());

  RecordedRequest request = server.getLastRequest();
  Pod requestPod = new ObjectMapper().readerFor(Pod.class).readValue(request.getBody().inputStream());
  assertEquals("nginx", requestPod.getMetadata().getName());
}
 
Example #4
Source File: CustomResourceTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateOrReplace() throws IOException {
  String jsonObject = "{\"apiVersion\": \"test.fabric8.io/v1alpha1\",\"kind\": \"Hello\"," +
    "\"metadata\": {\"resourceVersion\":\"1\", \"name\": \"example-hello\"},\"spec\": {\"size\": 3}}";

  server.expect().post().withPath("/apis/test.fabric8.io/v1alpha1/namespaces/ns1/hellos").andReturn(HttpURLConnection.HTTP_INTERNAL_ERROR, new StatusBuilder().build()).once();
  server.expect().post().withPath("/apis/test.fabric8.io/v1alpha1/namespaces/ns1/hellos").andReturn(HttpURLConnection.HTTP_CREATED, jsonObject).once();
  server.expect().post().withPath("/apis/test.fabric8.io/v1alpha1/namespaces/ns1/hellos").andReturn(HttpURLConnection.HTTP_CONFLICT, jsonObject).once();
  server.expect().put().withPath("/apis/test.fabric8.io/v1alpha1/namespaces/ns1/hellos/example-hello").andReturn(HttpURLConnection.HTTP_OK, jsonObject).once();
  KubernetesClient client = server.getClient();

  KubernetesClientException exception = Assertions.assertThrows(KubernetesClientException.class,
    () -> client.customResource(customResourceDefinitionContext).createOrReplace("ns1", jsonObject));
  assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, exception.getCode());

  Map<String, Object> resource = client.customResource(customResourceDefinitionContext).createOrReplace("ns1", jsonObject);
  assertEquals("example-hello", ((Map<String, Object>)resource.get("metadata")).get("name").toString());

  resource = client.customResource(customResourceDefinitionContext).createOrReplace("ns1", jsonObject);
  assertEquals("example-hello", ((Map<String, Object>)resource.get("metadata")).get("name").toString());
}
 
Example #5
Source File: ErrorMessageTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testServerErrorWithStatus() {
  expectedEx.expectMessage(startsWith("Failure executing: POST"));
  expectedEx.expectMessage(containsString("Received status"));
  expectedEx.expectMessage(containsString("Message: This operation"));

  server.expect().withPath("/api/v1/namespaces/test/events").andReturn(500, new StatusBuilder()
    .withMessage("This operation is not allowed for some reason")
    .withReason("Some reason")
    .withCode(500)
    .build()).once();


  KubernetesClient client = server.getClient();

  client.v1().events().inNamespace("test").createNew().withNewMetadata().withName("event1").endMetadata().done();
}
 
Example #6
Source File: DeploymentTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testRollback() {
  DeploymentRollback deploymentRollback = new DeploymentRollbackBuilder()
    .withName("deployment1")
    .withNewRollbackTo().withRevision(1L).endRollbackTo()
    .withUpdatedAnnotations(Collections.singletonMap("foo", "bar"))
    .build();

  Status status = new StatusBuilder().build();
  KubernetesClient client = server.getClient();
  server.expect()
    .post()
    .withPath("/apis/extensions/v1beta1/namespaces/test/deployments/deployment1/rollback")
    .andReturn(201, status).once();

  client.extensions().deployments().inNamespace("test").withName("deployment1").rollback(deploymentRollback);
}
 
Example #7
Source File: SubjectAccessReviewOperationImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public Createable<SelfSubjectRulesReview, SelfSubjectRulesReview, CreateableSelfSubjectRulesReview> list(ListOptions listOptions) {
  throw new KubernetesClientException(new StatusBuilder()
    .withStatus("Failure")
    .withMessage("the server does not allow this method on the requested resource")
    .withReason("MethodNotAllowed")
    .withCode(405)
    .build());
}
 
Example #8
Source File: AdmissionReviewService.java    From vault-crd with Apache License 2.0 5 votes vote down vote up
private AdmissionResponse invalidRequest(String uid, String message) {
    Status status = new StatusBuilder()
            .withCode(400)
            .withMessage(message)
            .build();
    return new AdmissionResponseBuilder()
            .withAllowed(false)
            .withUid(uid)
            .withStatus(status)
            .build();
}
 
Example #9
Source File: SubjectAccessReviewOperationImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public Createable<SelfSubjectRulesReview, SelfSubjectRulesReview, CreateableSelfSubjectRulesReview> list(Integer limitVal, String continueVal) {
  throw new KubernetesClientException(new StatusBuilder()
    .withStatus("Failure")
    .withMessage("the server does not allow this method on the requested resource")
    .withReason("MethodNotAllowed")
    .withCode(405)
    .build());
}
 
Example #10
Source File: SubjectAccessReviewOperationImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public Createable<SelfSubjectRulesReview, SelfSubjectRulesReview, CreateableSelfSubjectRulesReview> list() {
  throw new KubernetesClientException(new StatusBuilder()
    .withStatus("Failure")
    .withMessage("the server does not allow this method on the requested resource")
    .withReason("MethodNotAllowed")
    .withCode(405)
    .build());
}
 
Example #11
Source File: SubjectAccessReviewDSLImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public Createable<SelfSubjectRulesReview, SelfSubjectRulesReview, DoneableSelfSubjectRulesReview> list(ListOptions listOptions) {
  throw new KubernetesClientException(new StatusBuilder()
    .withStatus("Failure")
    .withMessage("the server does not allow this method on the requested resource")
    .withReason("MethodNotAllowed")
    .withCode(405)
    .build());
}
 
Example #12
Source File: SubjectAccessReviewDSLImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public Createable<SelfSubjectRulesReview, SelfSubjectRulesReview, DoneableSelfSubjectRulesReview> list(Integer limitVal, String continueVal) {
  throw new KubernetesClientException(new StatusBuilder()
    .withStatus("Failure")
    .withMessage("the server does not allow this method on the requested resource")
    .withReason("MethodNotAllowed")
    .withCode(405)
    .build());
}
 
Example #13
Source File: SubjectAccessReviewDSLImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public Createable<SelfSubjectRulesReview, SelfSubjectRulesReview, DoneableSelfSubjectRulesReview> list() {
  throw new KubernetesClientException(new StatusBuilder()
    .withStatus("Failure")
    .withMessage("the server does not allow this method on the requested resource")
    .withReason("MethodNotAllowed")
    .withCode(405)
    .build());
}
 
Example #14
Source File: OperationSupport.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public static Status createStatus(int statusCode, String message) {
  Status status = new StatusBuilder()
          .withCode(statusCode)
          .withMessage(message)
          .build();
  status.getAdditionalProperties().put(CLIENT_STATUS_FLAG, "true");
  return status;
}
 
Example #15
Source File: WatchTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpErrorReconnect() throws InterruptedException {
  logger.info("testHttpErrorReconnect");
  String path = "/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&resourceVersion=1&watch=true";
  KubernetesClient client = server.getClient().inNamespace("test");
  // 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();

  final CountDownLatch closeLatch = 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();
    }

    @Override
    public void onClose(KubernetesClientException cause) {
      logger.debug("onClose", cause);
      closeLatch.countDown();
    }
  })) /* autoclose */ {
    assertTrue(closeLatch.await(3, TimeUnit.MINUTES));
  }
}
 
Example #16
Source File: ResourceTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
void testDontRetryWatchOnHttpGone() throws InterruptedException {
  Pod noReady = new PodBuilder().withNewMetadata()
    .withName("pod1")
    .withResourceVersion("1")
    .withNamespace("test").and().withNewStatus()
    .addNewCondition()
    .withType("Ready")
    .withStatus("False")
    .endCondition()
    .endStatus()
    .build();

  Status status = new StatusBuilder()
    .withCode(HttpURLConnection.HTTP_GONE)
    .build();

  // once not ready, to begin watch
  server.expect().get().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, noReady).once();

  server.expect().get().withPath("/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&resourceVersion=1&watch=true").andUpgradeToWebSocket()
    .open()
    .waitFor(500).andEmit(new WatchEvent(status, "ERROR"))
    .done()
    .once();

  KubernetesClient client = server.getClient();
  try {
    client.resource(noReady).waitUntilReady(5, TimeUnit.SECONDS);
    fail("should have thrown KubernetesClientException");
  } catch (KubernetesClientException e) {
    assertTrue(e.getCause() instanceof WaitForConditionWatcher.WatchException);
  }
}
 
Example #17
Source File: WatchOverHTTP.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpErrorReconnect() throws InterruptedException {
  logger.info("testHttpErrorReconnect");
  KubernetesClient client = server.getClient().inNamespace("test");

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

  final CountDownLatch closeLatch = 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();
    }

    @Override
    public void onClose(KubernetesClientException cause) {
      logger.debug("onClose", cause);
      closeLatch.countDown();
    }
  })) /* autoclose */ {
    assertTrue(closeLatch.await(3, TimeUnit.MINUTES));
  }
}
 
Example #18
Source File: CreateOrReplaceResourceTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreate() throws Exception {
  server.expect().get().withPath("/api/v1/namespaces/test/pods/pod123").andReturn(404, new StatusBuilder().build()).always();

  server.expect().post().withPath("/api/v1/namespaces/test/pods").andReturn(201, new PodBuilder()
    .withNewMetadata().withResourceVersion("12345").and().build()).once();

  KubernetesClient client = server.getClient();
  Pod pod = client.pods().createOrReplaceWithNew().withNewMetadata().withName("pod123").and().withNewSpec().and().done();
  assertNotNull(pod);
  assertEquals("12345", pod.getMetadata().getResourceVersion());
}
 
Example #19
Source File: CreateOrReplaceResourceTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testResourceCreate() throws Exception {
  server.expect().get().withPath("/api/v1/namespaces/test/pods/pod123").andReturn(404, new StatusBuilder().build()).always();

  server.expect().post().withPath("/api/v1/namespaces/test/pods").andReturn(201, new PodBuilder()
    .withNewMetadata().withResourceVersion("12345").and().build()).once();

  KubernetesClient client = server.getClient();
  HasMetadata result = client.resource(new PodBuilder().withNewMetadata().withName("pod123").and().withNewSpec().and().build()).createOrReplace();
  assertNotNull(result);
  assertEquals("12345", result.getMetadata().getResourceVersion());
}
 
Example #20
Source File: ProjectRequestTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testList() {
 server.expect().withPath("/apis/project.openshift.io/v1/projectrequests").andReturn(200, new StatusBuilder().withMessage("success").build()).once();
  OpenShiftClient client = server.getOpenshiftClient();

  Status status = client.projectrequests().list();
  assertNotNull(status);
  assertEquals("success", status.getMessage());
}
 
Example #21
Source File: DefaultExceptionMapperTest.java    From enmasse with Apache License 2.0 5 votes vote down vote up
@Test
public void testToResponseStatus422() {
    int code = 422;
    io.fabric8.kubernetes.api.model.Status status = new StatusBuilder().withCode(code).build();
    String message = "Some error message";
    KubernetesClientException kubernetesClientException = new KubernetesClientException(message, code, status);

    Response response = new DefaultExceptionMapper().toResponse(kubernetesClientException);
    assertEquals(code, response.getStatus());
    // can't check for response.getStatusInfo().getReasonPhrase() here because 422 isn't known in Response.Status 
    assertTrue(response.getEntity() instanceof Status);
    Status responseEntity = (Status) response.getEntity();
    assertEquals("Unprocessable Entity", responseEntity.getReason());
    assertEquals(message, responseEntity.getMessage());
}
 
Example #22
Source File: KubernetesDockerRunnerTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldThrowIOException() throws IOException {
  Mockito.reset(k8sClient);
  when(k8sClient.createPod(any(Pod.class))).thenThrow(
      new KubernetesClientException("foobar", 500,
          new StatusBuilder().withReason("foobar").build()));
  exception.expectMessage("Failed to create Kubernetes pod");
  kdr.start(RUN_STATE, RUN_SPEC);
}
 
Example #23
Source File: KubernetesDockerRunnerTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldToleratePodAlreadyCreated() throws IOException {
  Mockito.reset(k8sClient);
  when(k8sClient.createPod(any(Pod.class))).thenThrow(
      new KubernetesClientException("Already created", 409,
          new StatusBuilder().withReason("AlreadyExists").build()));
  assertThat(kdr.start(RUN_STATE, RUN_SPEC), is(RUNNER_ID));
  verifyZeroInteractions(stateManager);
}
 
Example #24
Source File: OpenShiftServiceImplTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
void expectDeploymentOf(final String name, final DeploymentConfig expectedDeploymentConfig) {
    final DeploymentConfig deployed = new DeploymentConfigBuilder(expectedDeploymentConfig)
        .withNewStatus()
            .withLatestVersion(1L)
        .endStatus()
        .build();
    server.expect()
        .get()
        .withPath("/apis/apps.openshift.io/v1/namespaces/test/deploymentconfigs/" + openshiftName(name))
        .andReturn(404, new StatusBuilder().withCode(404).build())
        .times(1);
    server.expect()
        .get()
        .withPath("/apis/apps.openshift.io/v1/namespaces/test/deploymentconfigs/" + openshiftName(name))
        .andReturn(200, deployed)
        .always();
    server.expect()
        .patch()
        .withPath("/apis/apps.openshift.io/v1/namespaces/test/deploymentconfigs/" + openshiftName(name))
        .andReturn(200, deployed)
        .always();
    server.expect()
        .post()
        .withPath("/apis/apps.openshift.io/v1/namespaces/test/deploymentconfigs")
        .andReturn(200, expectedDeploymentConfig)
        .always();
}
 
Example #25
Source File: ResourceTest.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Test
void testRetryOnErrorEventDuringWait() throws InterruptedException {
  Pod pod1 = new PodBuilder().withNewMetadata()
    .withName("pod1")
    .withResourceVersion("1")
    .withNamespace("test").and().build();

  Pod noReady = new PodBuilder(pod1).withNewStatus()
    .addNewCondition()
    .withType("Ready")
    .withStatus("False")
    .endCondition()
    .endStatus()
    .build();

  Pod ready = new PodBuilder(pod1).withNewStatus()
    .addNewCondition()
    .withType("Ready")
    .withStatus("True")
    .endCondition()
    .endStatus()
    .build();

  Status status = new StatusBuilder()
    .withCode(HttpURLConnection.HTTP_FORBIDDEN)
    .build();

  // once not ready, to begin watch
  server.expect().get().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, noReady).times(2);

  server.expect().get().withPath("/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&resourceVersion=1&watch=true").andUpgradeToWebSocket()
    .open()
    .waitFor(500).andEmit(new WatchEvent(status, "ERROR"))
    .done()
    .once();

  server.expect().get().withPath("/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&resourceVersion=1&watch=true").andUpgradeToWebSocket()
    .open()
    .waitFor(500).andEmit(new WatchEvent(ready, "MODIFIED"))
    .done()
    .once();

  KubernetesClient client = server.getClient();
  Pod p = client.resource(noReady).waitUntilReady(5, TimeUnit.SECONDS);
  Assert.assertTrue(Readiness.isPodReady(p));
}
 
Example #26
Source File: ResourceTest.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Test
void testRetryOnErrorEventDuringWaitReturnFromAPIIfMatch() throws InterruptedException {
  Pod pod1 = new PodBuilder().withNewMetadata()
    .withName("pod1")
    .withResourceVersion("1")
    .withNamespace("test").and().build();


  Pod noReady = new PodBuilder(pod1).withNewStatus()
    .addNewCondition()
    .withType("Ready")
    .withStatus("False")
    .endCondition()
    .endStatus()
    .build();

  Pod ready = new PodBuilder(pod1).withNewStatus()
    .addNewCondition()
    .withType("Ready")
    .withStatus("True")
    .endCondition()
    .endStatus()
    .build();

  Status status = new StatusBuilder()
    .withCode(HttpURLConnection.HTTP_FORBIDDEN)
    .build();

  // once not ready, to begin watch
  server.expect().get().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, noReady).once();
  // once ready, after watch fails
  server.expect().get().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, ready).once();

  server.expect().get().withPath("/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&resourceVersion=1&watch=true").andUpgradeToWebSocket()
    .open()
    .waitFor(500).andEmit(new WatchEvent(status, "ERROR"))
    .done()
    .once();

  KubernetesClient client = server.getClient();
  Pod p = client.resource(noReady).waitUntilReady(5, TimeUnit.SECONDS);
  Assert.assertTrue(Readiness.isPodReady(p));
}