io.fabric8.kubernetes.client.dsl.NonNamespaceOperation Java Examples

The following examples show how to use io.fabric8.kubernetes.client.dsl.NonNamespaceOperation. 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: AbstractResourceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccessfulCreation(VertxTestContext context) {
    T resource = resource();
    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenReturn(null);
    when(mockResource.create(any())).thenReturn(resource);

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(resource.getMetadata().getName()))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.inNamespace(matches(resource.getMetadata().getNamespace()))).thenReturn(mockNameable);

    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractResourceOperator<C, T, L, D, R> op = createResourceOperationsWithMockedReadiness(vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.createOrUpdate(resource).onComplete(context.succeeding(rr -> context.verify(() -> {
        verify(mockResource).get();
        verify(mockResource).create(eq(resource));
        async.flag();
    })));
}
 
Example #2
Source File: K8sManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the client for deploying custom resources
 *
 * @param client , openshift client
 * @param crd    , CustomResourceDefinition
 * @return , Custom resource client
 */
private NonNamespaceOperation<APICustomResourceDefinition, APICustomResourceDefinitionList,
        DoneableAPICustomResourceDefinition, Resource<APICustomResourceDefinition,
        DoneableAPICustomResourceDefinition>> getCRDClient(OpenShiftClient client, CustomResourceDefinition crd) {

    NonNamespaceOperation<APICustomResourceDefinition, APICustomResourceDefinitionList,
            DoneableAPICustomResourceDefinition, Resource<APICustomResourceDefinition,
            DoneableAPICustomResourceDefinition>> crdClient = client
            .customResources(crd, APICustomResourceDefinition.class, APICustomResourceDefinitionList.class,
                    DoneableAPICustomResourceDefinition.class);

    crdClient = ((MixedOperation<APICustomResourceDefinition, APICustomResourceDefinitionList,
            DoneableAPICustomResourceDefinition, Resource<APICustomResourceDefinition,
            DoneableAPICustomResourceDefinition>>) crdClient).inNamespace(client.getNamespace());

    return crdClient;
}
 
Example #3
Source File: InitWriterTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
/**
 * Mock a Kubernetes client for getting cluster node information
 *
 * @param nodeName cluster node name
 * @param labels metadata labels to be returned for the provided cluster node name
 * @return mocked Kubernetes client
 */
private KubernetesClient mockKubernetesClient(String nodeName, Map<String, String> labels, List<NodeAddress> addresses) {

    KubernetesClient client = mock(KubernetesClient.class);
    NonNamespaceOperation mockNodes = mock(NonNamespaceOperation.class);
    Resource mockResource = mock(Resource.class);
    Node mockNode = mock(Node.class);
    ObjectMeta mockNodeMetadata = mock(ObjectMeta.class);
    NodeStatus mockNodeStatus = mock(NodeStatus.class);

    when(client.nodes()).thenReturn(mockNodes);
    when(mockNodes.withName(nodeName)).thenReturn(mockResource);
    when(mockResource.get()).thenReturn(mockNode);
    when(mockNode.getMetadata()).thenReturn(mockNodeMetadata);
    when(mockNodeMetadata.getLabels()).thenReturn(labels);
    when(mockNode.getStatus()).thenReturn(mockNodeStatus);
    when(mockNodeStatus.getAddresses()).thenReturn(addresses);

    return client;
}
 
Example #4
Source File: AbstractResourceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteWhenResourceDoesNotExistIsANop(VertxTestContext context) {
    T resource = resource();
    Resource mockResource = mock(resourceType());

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(RESOURCE_NAME))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.inNamespace(matches(NAMESPACE))).thenReturn(mockNameable);

    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractResourceOperator<C, T, L, D, R> op = createResourceOperations(vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.reconcile(resource.getMetadata().getNamespace(), resource.getMetadata().getName(), null)
        .onComplete(context.succeeding(rr -> context.verify(() -> {
            verify(mockResource).get();
            verify(mockResource, never()).delete();
            async.flag();
        })));
}
 
Example #5
Source File: AbstractResourceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateOrUpdateThrowsWhenCreateThrows(VertxTestContext context) {
    T resource = resource();
    RuntimeException ex = new RuntimeException("Testing this exception is handled correctly");

    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenReturn(null);

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(resource.getMetadata().getName()))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.inNamespace(matches(resource.getMetadata().getNamespace()))).thenReturn(mockNameable);
    when(mockResource.create(any())).thenThrow(ex);

    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractResourceOperator<C, T, L, D, R> op = createResourceOperations(vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.createOrUpdate(resource).onComplete(context.failing(e -> {
        context.verify(() -> assertThat(e, is(ex)));
        async.flag();
    }));
}
 
Example #6
Source File: AbstractResourceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testExistenceCheckThrows(VertxTestContext context) {
    T resource = resource();
    RuntimeException ex = new RuntimeException();

    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenThrow(ex);

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(resource.getMetadata().getName()))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.inNamespace(matches(resource.getMetadata().getNamespace()))).thenReturn(mockNameable);

    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractResourceOperator<C, T, L, D, R> op = createResourceOperations(vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.createOrUpdate(resource).onComplete(context.failing(e -> context.verify(() -> {
        assertThat(e, is(ex));
        async.flag();
    })));
}
 
Example #7
Source File: AbtractReadyResourceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadinessThrowsWhenResourceDoesNotExist(VertxTestContext context) {
    T resource = resource();
    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenReturn(null);

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(resource.getMetadata().getName()))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.inNamespace(matches(resource.getMetadata().getNamespace()))).thenReturn(mockNameable);

    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractReadyResourceOperator<C, T, L, D, R> op = createResourceOperations(vertx, mockClient);
    Checkpoint async = context.checkpoint();
    op.readiness(NAMESPACE, RESOURCE_NAME, 20, 100)
        .onComplete(context.failing(e -> context.verify(() -> {
            assertThat(e, instanceOf(TimeoutException.class));
            verify(mockResource, atLeastOnce()).get();
            verify(mockResource, never()).isReady();
            async.flag();
        })));

}
 
Example #8
Source File: AbstractNonNamespacedResourceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeletionWhenResourceDoesNotExistIsANop(VertxTestContext context) {
    T resource = resource();
    Resource mockResource = mock(resourceType());

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(RESOURCE_NAME))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.withName(matches(RESOURCE_NAME))).thenReturn(mockResource);

    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractNonNamespacedResourceOperator<C, T, L, D, R> op = createResourceOperations(vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.reconcile(resource.getMetadata().getName(), null).onComplete(context.succeeding(rrDeleted -> {
        verify(mockResource).get();
        verify(mockResource, never()).delete();
        async.flag();
    }));
}
 
Example #9
Source File: AbstractNonNamespacedResourceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateOrUpdateThrowsWhenCreateThrows(VertxTestContext context) {
    T resource = resource();
    RuntimeException ex = new RuntimeException("Testing this exception is handled correctly");

    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenReturn(null);

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(resource.getMetadata().getName()))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.withName(matches(RESOURCE_NAME))).thenReturn(mockResource);
    when(mockResource.create(any())).thenThrow(ex);

    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractNonNamespacedResourceOperator<C, T, L, D, R> op = createResourceOperations(vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.createOrUpdate(resource).onComplete(context.failing(e -> {
        context.verify(() -> assertThat(e, is(ex)));
        async.flag();
    }));
}
 
Example #10
Source File: AbstractNonNamespacedResourceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccessfulCreation(VertxTestContext context) {
    T resource = resource();
    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenReturn(null);
    when(mockResource.create(any())).thenReturn(resource);

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(resource.getMetadata().getName()))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.withName(matches(RESOURCE_NAME))).thenReturn(mockResource);

    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractNonNamespacedResourceOperator<C, T, L, D, R> op = createResourceOperationsWithMockedReadiness(
            vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.createOrUpdate(resource).onComplete(context.succeeding(rr -> {
        verify(mockResource).get();
        verify(mockResource).create(eq(resource));
        async.flag();
    }));
}
 
Example #11
Source File: AbstractNonNamespacedResourceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateOrUpdateThrowsWhenExistenceCheckThrows(VertxTestContext context) {
    T resource = resource();
    RuntimeException ex = new RuntimeException();

    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenThrow(ex);

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(resource.getMetadata().getName()))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.withName(matches(RESOURCE_NAME))).thenReturn(mockResource);

    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractNonNamespacedResourceOperator<C, T, L, D, R> op = createResourceOperations(vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.createOrUpdate(resource).onComplete(context.failing(e -> {
        context.verify(() -> assertThat(e, is(ex)));
        async.flag();
    }));
}
 
Example #12
Source File: AbstractResourceOperator.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked") // due to L extends KubernetesResourceList/*<T>*/
protected List<T> listInNamespace(String namespace, Labels selector) {
    NonNamespaceOperation<T, L, D, R> tldrNonNamespaceOperation = operation().inNamespace(namespace);

    if (selector != null) {
        Map<String, String> labels = selector.toMap();
        FilterWatchListDeletable<T, L, Boolean, Watch, Watcher<T>> tlBooleanWatchWatcherFilterWatchListDeletable = tldrNonNamespaceOperation.withLabels(labels);
        return tlBooleanWatchWatcherFilterWatchListDeletable
                .list()
                .getItems();
    } else {
        return tldrNonNamespaceOperation
                .list()
                .getItems();
    }
}
 
Example #13
Source File: AbstractNonNamespacedResourceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
public void createWhenExistsIsAPatch(VertxTestContext context, boolean cascade) {
    T resource = resource();
    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenReturn(resource);
    when(mockResource.cascading(cascade)).thenReturn(mockResource);
    when(mockResource.patch(any())).thenReturn(resource);

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(resource.getMetadata().getName()))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.withName(matches(RESOURCE_NAME))).thenReturn(mockResource);

    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractNonNamespacedResourceOperator<C, T, L, D, R> op = createResourceOperations(vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.createOrUpdate(resource())
        .onComplete(context.succeeding(ar -> {
            verify(mockResource).get();
            verify(mockResource).patch(any());
            verify(mockResource, never()).create(any());
            verify(mockResource, never()).createNew();
            verify(mockResource, never()).createOrReplace(any());
            verify(mockCms, never()).createOrReplace(any());
            async.flag();
        }));
}
 
Example #14
Source File: K8sManager.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes the API from all the clusters it had been deployed
 *
 * @param apiId                   API Identifier
 * @param containerMgtInfoDetails Clusters which the API has published
 */
@Override
public void deleteAPI(APIIdentifier apiId, JSONObject containerMgtInfoDetails) {

    String apiName = apiId.getApiName();

    JSONObject propreties = (JSONObject) containerMgtInfoDetails.get(PROPERTIES);

    if (propreties.get(MASTER_URL) != null &&
            propreties.get(SATOKEN) != null &&
            propreties.get(NAMESPACE) != null) {
        Config config = new ConfigBuilder()
                .withMasterUrl(propreties.get(MASTER_URL).toString().replace("\\", ""))
                .withOauthToken(propreties.get(SATOKEN).toString())
                .withNamespace(propreties.get(NAMESPACE).toString())
                .withClientKeyPassphrase(System.getProperty(CLIENT_KEY_PASSPHRASE)).build();

        OpenShiftClient client = new DefaultOpenShiftClient(config);
        CustomResourceDefinition apiCRD = client.customResourceDefinitions().withName(API_CRD_NAME).get();

        NonNamespaceOperation<APICustomResourceDefinition, APICustomResourceDefinitionList,
                DoneableAPICustomResourceDefinition, Resource<APICustomResourceDefinition,
                DoneableAPICustomResourceDefinition>> crdClient = getCRDClient(client, apiCRD);

        crdClient.withName(apiName.toLowerCase()).cascading(true).delete();

        log.info("Successfully deleted the [API] " + apiName);
    } else {
        log.error("Error occurred while deleting API from Kubernetes cluster");
    }

}
 
Example #15
Source File: OpenShiftProjectTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private Resource prepareProjectResource(String projectName) {
  Resource projectResource = mock(Resource.class);

  NonNamespaceOperation projectOperation = mock(NonNamespaceOperation.class);
  doReturn(projectResource).when(projectOperation).withName(projectName);
  doReturn(projectOperation).when(openShiftClient).projects();

  when(projectResource.get())
      .thenReturn(
          new ProjectBuilder().withNewMetadata().withName(projectName).endMetadata().build());

  openShiftClient.projects().withName(projectName).get();
  return projectResource;
}
 
Example #16
Source File: OpenShiftProjectTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@BeforeMethod
public void setUp() throws Exception {
  lenient().when(clientFactory.create(anyString())).thenReturn(kubernetesClient);
  lenient().when(clientFactory.createOC()).thenReturn(openShiftClient);
  lenient().when(clientFactory.createOC(anyString())).thenReturn(openShiftClient);
  lenient().when(openShiftClient.adapt(OpenShiftClient.class)).thenReturn(openShiftClient);

  final MixedOperation mixedOperation = mock(MixedOperation.class);
  final NonNamespaceOperation namespaceOperation = mock(NonNamespaceOperation.class);
  lenient().doReturn(mixedOperation).when(kubernetesClient).serviceAccounts();
  lenient().when(mixedOperation.inNamespace(anyString())).thenReturn(namespaceOperation);
  lenient().when(namespaceOperation.withName(anyString())).thenReturn(serviceAccountResource);
  lenient().when(serviceAccountResource.get()).thenReturn(mock(ServiceAccount.class));

  openShiftProject =
      new OpenShiftProject(
          clientFactory,
          WORKSPACE_ID,
          PROJECT_NAME,
          deployments,
          services,
          routes,
          pvcs,
          ingresses,
          secrets,
          configsMaps);
}
 
Example #17
Source File: IstioExecutor.java    From istio-apim with Apache License 2.0 5 votes vote down vote up
/**
 * Create Mixer rule for the API
 *
 * @param apiName     Name of the API
 * @param serviceName Istio service name
 */
private void createRule(String apiName, String serviceName) {

    NonNamespaceOperation<Rule, RuleList, DoneableRule,
            io.fabric8.kubernetes.client.dsl.Resource<Rule, DoneableRule>> ruleCRDClient
            = client.customResource(ruleCRD, Rule.class, RuleList.class,
            DoneableRule.class).inNamespace(istioSystemNamespace);
    String ruleName = Strings.toLowerCase(apiName) + "-rule";

    Rule rule = new Rule();
    ObjectMeta metadata = new ObjectMeta();
    metadata.setName(ruleName);
    rule.setMetadata(metadata);

    Action action = new Action();
    String handlerName = "wso2-handler." + istioSystemNamespace;
    action.setHandler(handlerName);
    ArrayList<String> instances = new ArrayList<>();
    instances.add("wso2-authorization");
    instances.add("wso2-metrics");
    action.setInstances(instances);

    ArrayList<Action> actions = new ArrayList<>();
    actions.add(action);

    RuleSpec ruleSpec = new RuleSpec();
    String matchValue = "context.reporter.kind == \"inbound\" && destination.namespace == \"" + appNamespace +
            "\" && destination.service.name == \"" + serviceName + "\"";
    ruleSpec.setMatch(matchValue);
    ruleSpec.setActions(actions);
    rule.setSpec(ruleSpec);

    ruleCRDClient.createOrReplace(rule);
    log.info("[Rule] " + ruleName + " Created in the [Namespace] " + istioSystemNamespace + " for the [API] "
            + apiName);

}
 
Example #18
Source File: ServiceAccountOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Override
public void createWhenExistsIsAPatch(VertxTestContext context, boolean cascade) {
    // This is overridden because SA patch is coded as a no op to avoid needless token creation.
    ServiceAccount resource = resource();
    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenReturn(resource);
    when(mockResource.cascading(cascade)).thenReturn(mockResource);

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(resource.getMetadata().getName()))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.inNamespace(matches(resource.getMetadata().getNamespace()))).thenReturn(mockNameable);

    KubernetesClient mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractResourceOperator<KubernetesClient, ServiceAccount, ServiceAccountList, DoneableServiceAccount, Resource<ServiceAccount, DoneableServiceAccount>> op = createResourceOperations(vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.createOrUpdate(resource)
        .onComplete(context.succeeding(rr -> {
            context.verify(() -> assertThat(rr, instanceOf(ReconcileResult.Noop.class)));
            verify(mockResource).get();
            //verify(mockResource).patch(any());
            verify(mockResource, never()).create(any());
            verify(mockResource, never()).createNew();
            verify(mockResource, never()).createOrReplace(any());
            verify(mockCms, never()).createOrReplace(any());
            async.flag();
        }));
}
 
Example #19
Source File: AbstractResourceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testReconcileDeleteThrowsWhenDeletionThrows(VertxTestContext context) {
    RuntimeException ex = new RuntimeException("Testing this exception is handled correctly");
    Deletable mockDeletable = mock(Deletable.class);
    when(mockDeletable.delete()).thenThrow(ex);

    EditReplacePatchDeletable mockERPD = mock(EditReplacePatchDeletable.class);
    when(mockERPD.withGracePeriod(anyLong())).thenReturn(mockDeletable);

    T resource = resource();
    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenReturn(resource);
    when(mockResource.cascading(eq(true))).thenReturn(mockERPD);

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(RESOURCE_NAME))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.inNamespace(matches(NAMESPACE))).thenReturn(mockNameable);

    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractResourceOperator<C, T, L, D, R> op = createResourceOperations(vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.reconcile(resource.getMetadata().getNamespace(), resource.getMetadata().getName(), null)
        .onComplete(context.failing(e -> context.verify(() -> {
            assertThat(e, is(ex));
            async.flag();
        })));
}
 
Example #20
Source File: AbstractResourceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testReconcileDeletionSuccessfullyDeletes(VertxTestContext context) {
    Deletable mockDeletable = mock(Deletable.class);

    EditReplacePatchDeletable mockERPD = mock(EditReplacePatchDeletable.class);
    when(mockERPD.withGracePeriod(anyLong())).thenReturn(mockDeletable);

    T resource = resource();
    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenReturn(resource);
    when(mockResource.cascading(eq(true))).thenReturn(mockERPD);

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(RESOURCE_NAME))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.inNamespace(matches(NAMESPACE))).thenReturn(mockNameable);

    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractResourceOperator<C, T, L, D, R> op = createResourceOperations(vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.reconcile(resource.getMetadata().getNamespace(), resource.getMetadata().getName(), null)
        .onComplete(context.succeeding(rr -> context.verify(() -> {
            verify(mockDeletable).delete();
            async.flag();
        })));
}
 
Example #21
Source File: AbstractResourceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testReconcileDeleteWhenResourceExistsStillDeletes(VertxTestContext context) {
    Deletable mockDeletable = mock(Deletable.class);

    EditReplacePatchDeletable mockERPD = mock(EditReplacePatchDeletable.class);
    when(mockERPD.withGracePeriod(anyLong())).thenReturn(mockDeletable);

    T resource = resource();
    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenReturn(resource);
    when(mockResource.cascading(eq(true))).thenReturn(mockERPD);

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(RESOURCE_NAME))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.inNamespace(matches(NAMESPACE))).thenReturn(mockNameable);

    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractResourceOperator<C, T, L, D, R> op = createResourceOperations(vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.reconcile(resource.getMetadata().getNamespace(), resource.getMetadata().getName(), null)
        .onComplete(context.succeeding(rr -> context.verify(() -> {
            verify(mockDeletable).delete();
            async.flag();
        })));
}
 
Example #22
Source File: KubernetesClientUtil.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public static FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> withSelector(NonNamespaceOperation<Pod, PodList, DoneablePod, PodResource<Pod, DoneablePod>> pods, LabelSelector selector, KitLogger log) {
    FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> answer = pods;
    Map<String, String> matchLabels = selector.getMatchLabels();
    if (matchLabels != null && !matchLabels.isEmpty()) {
        answer = answer.withLabels(matchLabels);
    }
    List<LabelSelectorRequirement> matchExpressions = selector.getMatchExpressions();
    if (matchExpressions != null) {
        for (LabelSelectorRequirement expression : matchExpressions) {
            String key = expression.getKey();
            List<String> values = expression.getValues();
            if (StringUtils.isBlank(key)) {
                log.warn("Ignoring empty key in selector expression %s", expression);
                continue;
            }
            if (values == null || values.isEmpty()) {
                log.warn("Ignoring empty values in selector expression %s", expression);
                continue;
            }
            String[] valuesArray = values.toArray(new String[values.size()]);
            String operator = expression.getOperator();
            switch (operator) {
            case "In":
                answer = answer.withLabelIn(key, valuesArray);
                break;
            case "NotIn":
                answer = answer.withLabelNotIn(key, valuesArray);
                break;
            default:
                log.warn("Ignoring unknown operator %s in selector expression %s", operator, expression);
            }
        }
    }
    return answer;
}
 
Example #23
Source File: KubernetesHelper.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public static FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> withSelector(NonNamespaceOperation<Pod, PodList, DoneablePod, PodResource<Pod, DoneablePod>> pods, LabelSelector selector, KitLogger log) {
    FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> answer = pods;
    Map<String, String> matchLabels = selector.getMatchLabels();
    if (matchLabels != null && !matchLabels.isEmpty()) {
        answer = answer.withLabels(matchLabels);
    }
    List<LabelSelectorRequirement> matchExpressions = selector.getMatchExpressions();
    if (matchExpressions != null) {
        for (LabelSelectorRequirement expression : matchExpressions) {
            String key = expression.getKey();
            List<String> values = expression.getValues();
            if (StringUtils.isBlank(key)) {
                log.warn("Ignoring empty key in selector expression %s", expression);
                continue;
            }
            if (values == null || values.isEmpty()) {
                log.warn("Ignoring empty values in selector expression %s", expression);
                continue;
            }
            String[] valuesArray = values.toArray(new String[values.size()]);
            String operator = expression.getOperator();
            switch (operator) {
                case "In":
                    answer = answer.withLabelIn(key, valuesArray);
                    break;
                case "NotIn":
                    answer = answer.withLabelNotIn(key, valuesArray);
                    break;
                default:
                    log.warn("Ignoring unknown operator %s in selector expression %s", operator, expression);
            }
        }
    }
    return answer;
}
 
Example #24
Source File: IstioExecutor.java    From istio-apim with Apache License 2.0 5 votes vote down vote up
/**
 * Create HTTPAPISpecBinding for the API
 *
 * @param apiName  Name of the API
 * @param endPoint Endpoint of the API
 */
public void createHttpAPISpecBinding(String apiName, String endPoint) {

    NonNamespaceOperation<HTTPAPISpecBinding, HTTPAPISpecBindingList, DoneableHTTPAPISpecBinding,
            io.fabric8.kubernetes.client.dsl.Resource<HTTPAPISpecBinding, DoneableHTTPAPISpecBinding>> bindingClient
            = client.customResource(httpAPISpecBindingCRD, HTTPAPISpecBinding.class, HTTPAPISpecBindingList.class,
            DoneableHTTPAPISpecBinding.class).inNamespace(appNamespace);

    String bindingName = Strings.toLowerCase(apiName) + "-binding";
    String apiSpecName = Strings.toLowerCase(apiName) + "-apispec";

    HTTPAPISpecBinding httpapiSpecBinding = new HTTPAPISpecBinding();
    ObjectMeta metadata = new ObjectMeta();
    metadata.setName(bindingName);
    httpapiSpecBinding.setMetadata(metadata);
    HTTPAPISpecBindingSpec httpapiSpecBindingSpec = new HTTPAPISpecBindingSpec();

    APISpec apiSpec = new APISpec();
    apiSpec.setName(apiSpecName);
    apiSpec.setNamespace(appNamespace);
    ArrayList<APISpec> apiSpecsList = new ArrayList<>();
    apiSpecsList.add(apiSpec);
    httpapiSpecBindingSpec.setApi_specs(apiSpecsList);

    Service service = new Service();
    service.setName(endPoint);
    service.setNamespace(appNamespace);
    ArrayList<Service> servicesList = new ArrayList<>();
    servicesList.add(service);
    httpapiSpecBindingSpec.setServices(servicesList);
    httpapiSpecBinding.setSpec(httpapiSpecBindingSpec);

    bindingClient.createOrReplace(httpapiSpecBinding);
    log.info("[HTTPAPISpecBinding] " + bindingName + " Created in the [Namespace] " + appNamespace + " for the"
            + " [API] " + apiName);
}
 
Example #25
Source File: AbstractResourceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
public void createWhenExistsIsAPatch(VertxTestContext context, boolean cascade) {
    T resource = resource();
    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenReturn(resource);
    when(mockResource.cascading(cascade)).thenReturn(mockResource);
    when(mockResource.patch(any())).thenReturn(resource);

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(resource.getMetadata().getName()))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.inNamespace(matches(resource.getMetadata().getNamespace()))).thenReturn(mockNameable);

    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractResourceOperator<C, T, L, D, R> op = createResourceOperations(vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.createOrUpdate(resource()).onComplete(context.succeeding(rr -> context.verify(() -> {
        verify(mockResource).get();
        verify(mockResource).patch(any());
        verify(mockResource, never()).create(any());
        verify(mockResource, never()).createNew();
        verify(mockResource, never()).createOrReplace(any());
        verify(mockCms, never()).createOrReplace(any());
        async.flag();
    })));
}
 
Example #26
Source File: AbtractReadyResourceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testWaitUntilReadyThrows(VertxTestContext context) {
    T resource = resource();

    // This test does not apply to the resource types without the Ready field
    if (!Readiness.isReadinessApplicable(resource.getClass()))  {
        context.completeNow();
    }

    RuntimeException ex = new RuntimeException("This is a test exception");

    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenReturn(resource());
    when(mockResource.isReady()).thenThrow(ex);

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(resource.getMetadata().getName()))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.inNamespace(matches(resource.getMetadata().getNamespace()))).thenReturn(mockNameable);

    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractReadyResourceOperator<C, T, L, D, R> op = createResourceOperations(vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.readiness(NAMESPACE, RESOURCE_NAME, 20, 100)
        .onComplete(context.failing(e -> context.verify(() -> {
            assertThat(e, instanceOf(TimeoutException.class));
            async.flag();
        })));
}
 
Example #27
Source File: AbtractReadyResourceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadinessThrowsWhenExistenceCheckThrows(VertxTestContext context) {
    T resource = resource();
    RuntimeException ex = new RuntimeException("This is a test exception");

    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenThrow(ex);

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(resource.getMetadata().getName()))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.inNamespace(matches(resource.getMetadata().getNamespace()))).thenReturn(mockNameable);

    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractReadyResourceOperator<C, T, L, D, R> op = createResourceOperations(vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.readiness(NAMESPACE, RESOURCE_NAME, 20, 100)
        .onComplete(context.failing(e -> context.verify(() -> {
            assertThat(e, instanceOf(TimeoutException.class));
            verify(mockResource, never()).isReady();
            async.flag();
        })));
}
 
Example #28
Source File: AbstractNonNamespacedResourceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testDeletionWhenResourceExistsStillDeletes(VertxTestContext context) {
    T resource = resource();
    AtomicBoolean watchWasClosed = new AtomicBoolean(false);
    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenReturn(resource);
    when(mockResource.withGracePeriod(anyLong())).thenReturn(mockResource);
    when(mockResource.delete()).thenReturn(true);
    when(mockResource.watch(any())).thenAnswer(invocation -> {
        Watcher<T> watcher = invocation.getArgument(0);
        watcher.eventReceived(Watcher.Action.DELETED, null);
        return (Watch) () -> {
            watchWasClosed.set(true);
        };
    });

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(RESOURCE_NAME))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.withName(matches(RESOURCE_NAME))).thenReturn(mockResource);

    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractNonNamespacedResourceOperator<C, T, L, D, R> op = createResourceOperations(vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.reconcile(resource.getMetadata().getName(), null).onComplete(context.succeeding(rrDeleted -> {
        verify(mockResource).delete();
        context.verify(() -> assertThat("Watch was not closed", watchWasClosed.get(), is(true)));
        async.flag();
    }));
}
 
Example #29
Source File: AbstractNonNamespacedResourceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testReconcileThrowsWhenDeletionTimesOut(VertxTestContext context) {
    T resource = resource();
    AtomicBoolean watchWasClosed = new AtomicBoolean(false);
    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenReturn(resource);
    when(mockResource.withGracePeriod(anyLong())).thenReturn(mockResource);
    when(mockResource.delete()).thenReturn(true);
    when(mockResource.watch(any())).thenAnswer(invocation -> {
        Watcher<T> watcher = invocation.getArgument(0);
        return (Watch) () -> {
            watchWasClosed.set(true);
        };
    });

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(RESOURCE_NAME))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.withName(matches(RESOURCE_NAME))).thenReturn(mockResource);

    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractNonNamespacedResourceOperator<C, T, L, D, R> op = createResourceOperations(vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.reconcile(resource.getMetadata().getName(), null).onComplete(context.failing(e -> context.verify(() -> {
        assertThat(e, instanceOf(TimeoutException.class));
        verify(mockResource).delete();
        assertThat("Watch was not closed", watchWasClosed.get(), is(true));
        async.flag();
    })));
}
 
Example #30
Source File: AbstractNonNamespacedResourceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testReconcileDeletionSuccessful(VertxTestContext context) {
    T resource = resource();
    AtomicBoolean watchWasClosed = new AtomicBoolean(false);
    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenReturn(resource);
    when(mockResource.withGracePeriod(anyLong())).thenReturn(mockResource);
    when(mockResource.delete()).thenReturn(Boolean.TRUE);
    when(mockResource.watch(any())).thenAnswer(invocation -> {
        Watcher<T> watcher = invocation.getArgument(0);
        watcher.eventReceived(Watcher.Action.DELETED, null);
        return (Watch) () -> {
            watchWasClosed.set(true);
        };
    });

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(RESOURCE_NAME))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.withName(matches(RESOURCE_NAME))).thenReturn(mockResource);

    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractNonNamespacedResourceOperator<C, T, L, D, R> op = createResourceOperations(vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.reconcile(resource.getMetadata().getName(), null).onComplete(context.succeeding(rrDeleted -> {
        verify(mockResource).delete();
        context.verify(() -> assertThat("Watch was not closed", watchWasClosed.get(), is(true)));
        async.flag();
    }));
}