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

The following examples show how to use io.fabric8.kubernetes.client.dsl.MixedOperation. 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 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 #2
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 #3
Source File: PropagationPolicyTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("Should delete a Custom Resource with PropagationPolicy=Background")
void testDeleteCustomResource() throws InterruptedException {
  // Given
  server.expect().delete().withPath("/apis/demo.k8s.io/v1alpha1/namespaces/test/podsets/example-podset").andReturn(HttpURLConnection.HTTP_OK, new PodSet()).once();
  MixedOperation<PodSet, PodSetList, DoneablePodSet, Resource<PodSet, DoneablePodSet>> podSetClient = server.getClient().customResources(new CustomResourceDefinitionBuilder()
    .withNewMetadata().withName("podsets.demo.k8s.io").endMetadata()
    .withNewSpec()
    .withGroup("demo.k8s.io")
    .withVersion("v1alpha1")
    .withNewNames().withKind("PodSet").withPlural("podsets").endNames()
    .withScope("Namespaced")
    .endSpec()
    .build(), PodSet.class, PodSetList.class, DoneablePodSet.class);

  // When
  boolean isDeleted = podSetClient.inNamespace("test").withName("example-podset").delete();

  // Then
  assertTrue(isDeleted);
  assertDeleteOptionsInLastRecordedRequest(DeletionPropagation.BACKGROUND.toString(), server.getLastRequest());
}
 
Example #4
Source File: Operator.java    From java-operator-sdk with Apache License 2.0 6 votes vote down vote up
private <R extends CustomResource> void registerWatches(ResourceController<R> controller, MixedOperation client,
                                                        Class<R> resClass,
                                                        boolean watchAllNamespaces, String[] targetNamespaces, EventScheduler eventScheduler) {

    CustomResourceOperationsImpl crClient = (CustomResourceOperationsImpl) client;
    if (watchAllNamespaces) {
        crClient.inAnyNamespace().watch(eventScheduler);
    } else if (targetNamespaces.length == 0) {
        client.watch(eventScheduler);
    } else {
        for (String targetNamespace : targetNamespaces) {
            crClient.inNamespace(targetNamespace).watch(eventScheduler);
            log.debug("Registered controller for namespace: {}", targetNamespace);
        }
    }
    customResourceClients.put(resClass, (CustomResourceOperationsImpl) client);
    log.info("Registered Controller: '{}' for CRD: '{}' for namespaces: {}", controller.getClass().getSimpleName(),
            resClass, targetNamespaces.length == 0 ? "[all/client namespace]" : Arrays.toString(targetNamespaces));
}
 
Example #5
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 #6
Source File: MockBuilder.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
MixedOperation<T, L, D, R> mockWithLabels(Map<String, String> labels) {
    return mockWithLabelPredicate(p -> {
        Map<String, String> m = new HashMap<>(p.getMetadata().getLabels());
        m.keySet().retainAll(labels.keySet());
        return labels.equals(m);
    });
}
 
Example #7
Source File: CustomResourceCrudTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testCrudWithDashSymbolInCRDName() throws IOException {
  CronTab cronTab1 = createCronTab("my-new-cron-object", "* * * * */5", 3, "my-awesome-cron-image");
  CronTab cronTab2 = createCronTab("my-second-cron-object", "* * * * */4", 2, "my-second-cron-image");
  CronTab cronTab3 = createCronTab("my-third-cron-object", "* * * * */3", 1, "my-third-cron-image");
  KubernetesClient client = kubernetesServer.getClient();

  MixedOperation<CronTab, CronTabList, DoneableCronTab, Resource<CronTab, DoneableCronTab>> cronTabClient = client
    .customResources(cronTabCrd, CronTab.class, CronTabList.class, DoneableCronTab.class);

  cronTabClient.inNamespace("test-ns").create(cronTab1);
  cronTabClient.inNamespace("test-ns").create(cronTab2);
  cronTabClient.inNamespace("test-ns").create(cronTab3);

  CronTabList cronTabList = cronTabClient.inNamespace("test-ns").list();
  assertNotNull(cronTabList);
  assertEquals(3, cronTabList.getItems().size());

  CronTab fromServerCronTab = cronTabClient.inNamespace("test-ns").withName("my-new-cron-object").get();
  assertNotNull(fromServerCronTab);
  assertCronTab(fromServerCronTab, "my-new-cron-object", "* * * * */5", 3, "my-awesome-cron-image");

  CronTab fromServerCronTab2 = cronTabClient.inNamespace("test-ns").withName("my-second-cron-object").get();
  assertNotNull(fromServerCronTab2);
  assertCronTab(fromServerCronTab2, "my-second-cron-object", "* * * * */4", 2, "my-second-cron-image");

  CronTab fromServerCronTab3 = cronTabClient.inNamespace("test-ns").withName("my-third-cron-object").get();
  assertNotNull(fromServerCronTab3);
  assertCronTab(fromServerCronTab3, "my-third-cron-object", "* * * * */3", 1, "my-third-cron-image");

  cronTabClient.inNamespace("test-ns").withName("my-third-cron-object").delete();
  cronTabList = cronTabClient.inNamespace("test-ns").list();
  assertEquals(2, cronTabList.getItems().size());
}
 
Example #8
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 #9
Source File: LeaseLockTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() {
  kc = mock(DefaultKubernetesClient.class, Answers.RETURNS_DEEP_STUBS);
  leases = mock(MixedOperation.class, Answers.RETURNS_DEEP_STUBS);
  doneableLease = mock(DoneableLease.class, Answers.RETURNS_DEEP_STUBS);
  metadata = mock(DoneableLease.MetadataNested.class, Answers.RETURNS_DEEP_STUBS);
  spec = mock(DoneableLease.SpecNested.class, Answers.RETURNS_DEEP_STUBS);
  when(kc.inNamespace(anyString()).leases()).thenReturn(leases);
  when(leases.withName(anyString()).createNew()).thenReturn(doneableLease);
  when(doneableLease.withNewMetadata()).thenReturn(metadata);
  when(doneableLease.withNewSpec()).thenReturn(spec);
}
 
Example #10
Source File: SparkClusterOperator.java    From spark-operator with Apache License 2.0 5 votes vote down vote up
private Map<String, Integer> getActual() {
    MixedOperation<ReplicationController, ReplicationControllerList, DoneableReplicationController, RollableScalableResource<ReplicationController, DoneableReplicationController>> aux1 =
            client.replicationControllers();
    FilterWatchListMultiDeletable<ReplicationController, ReplicationControllerList, Boolean, Watch, Watcher<ReplicationController>> aux2 =
            "*".equals(namespace) ? aux1.inAnyNamespace() : aux1.inNamespace(namespace);
    Map<String, String> labels =new HashMap<>(2);
    labels.put(prefix + OPERATOR_KIND_LABEL, entityName);
    labels.put(prefix + OPERATOR_RC_TYPE_LABEL, "worker");
    List<ReplicationController> workerRcs = aux2.withLabels(labels).list().getItems();
    Map<String, Integer> retMap = workerRcs
            .stream()
            .collect(Collectors.toMap(rc -> rc.getMetadata().getLabels().get(prefix + entityName),
                    rc -> rc.getSpec().getReplicas()));
    return retMap;
}
 
Example #11
Source File: MockBuilder.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
MixedOperation<T, L, D, R> mockWithLabelPredicate(Predicate<T> predicate) {
    MixedOperation<T, L, D, R> mixedWithLabels = mock(MixedOperation.class);
    when(mixedWithLabels.list()).thenAnswer(i2 -> {
        return mockList(predicate);
    });
    when(mixedWithLabels.watch(any())).thenAnswer(i2 -> {
        Watcher watcher = i2.getArgument(0);
        return addWatcher(PredicatedWatcher.predicatedWatcher(resourceTypeClass.getName(), "watch on labeled", predicate, watcher));
    });
    return mixedWithLabels;
}
 
Example #12
Source File: ExtensionsAPIGroupClient.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
@Deprecated
/**
 * @deprecated Replaced by {@link PolicyAPIGroupClient#podSecurityPolicies()}
 */
public MixedOperation<PodSecurityPolicy, PodSecurityPolicyList, DoneablePodSecurityPolicy, Resource<PodSecurityPolicy, DoneablePodSecurityPolicy>> podSecurityPolicies() {
  return new PodSecurityPolicyOperationsImpl(httpClient, getConfiguration());
}
 
Example #13
Source File: DeploymentConfigOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Override
protected void mocker(OpenShiftClient mockClient, MixedOperation op) {
    /*ExtensionsAPIGroupDSL mockExt = mock(ExtensionsAPIGroupDSL.class);
    when(mockExt.deployments()).thenReturn(op);
    when(mockClient.extensions()).thenReturn(mockExt);*/
    when(mockClient.deploymentConfigs()).thenReturn(op);
}
 
Example #14
Source File: RabbitMQResourceController.java    From rabbitmq-operator with Apache License 2.0 5 votes vote down vote up
@Override
protected MixedOperation<RabbitMQCustomResource, RabbitMQCustomResourceList, DoneableRabbitMQCustomResource, Resource<RabbitMQCustomResource, DoneableRabbitMQCustomResource>> operation() {
    final CustomResourceDefinition rabbitCrd = getClient().customResourceDefinitions().withName(RABBITMQ_CRD_NAME).get();

    if (rabbitCrd == null) {
        throw new RuntimeException(String.format("CustomResourceDefinition %s has not been defined", RABBITMQ_CRD_NAME));
    }

    return getClient().customResources(rabbitCrd, RabbitMQCustomResource.class, RabbitMQCustomResourceList.class, DoneableRabbitMQCustomResource.class);
}
 
Example #15
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 #16
Source File: DeploymentOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Override
protected void mocker(KubernetesClient mockClient, MixedOperation op) {
    AppsAPIGroupDSL mockExt = mock(AppsAPIGroupDSL.class);
    when(mockExt.deployments()).thenReturn(op);
    when(mockClient.apps()).thenReturn(mockExt);

}
 
Example #17
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 #18
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();
    }));
}
 
Example #19
Source File: FakeKubeClient.java    From teamcity-kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public MixedOperation<Pod, PodList, DoneablePod, PodResource<Pod, DoneablePod>> pods() {
  if (myException != null){
    throw myException;
  }
  return new MyOperation(){
    @Override
    public Object create(final Object[] resources) throws KubernetesClientException {
      return new Pod();
    }
  };
}
 
Example #20
Source File: ConfigMapLockTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() {
  kc = mock(DefaultKubernetesClient.class, Answers.RETURNS_DEEP_STUBS);
  configMaps = mock(MixedOperation.class, Answers.RETURNS_DEEP_STUBS);
  doneableConfigMap = mock(DoneableConfigMap.class, Answers.RETURNS_DEEP_STUBS);
  metadata = mock(DoneableConfigMap.MetadataNested.class, Answers.RETURNS_DEEP_STUBS);
  when(kc.inNamespace(anyString()).configMaps()).thenReturn(configMaps);
  when(configMaps.withName(anyString()).createNew()).thenReturn(doneableConfigMap);
  when(doneableConfigMap.editOrNewMetadata()).thenReturn(metadata);
}
 
Example #21
Source File: Kubernetes.java    From enmasse with Apache License 2.0 4 votes vote down vote up
public MixedOperation<User, UserList, DoneableUser,
        Resource<User, DoneableUser>> getUserClient(String namespace) {
    return (MixedOperation<User, UserList, DoneableUser, Resource<User, DoneableUser>>) client.customResources(UserCrd.messagingUser(), User.class, UserList.class, DoneableUser.class).inNamespace(namespace);
}
 
Example #22
Source File: Kubernetes.java    From enmasse with Apache License 2.0 4 votes vote down vote up
public MixedOperation<ConsoleService, ConsoleServiceList, DoneableConsoleService,
        Resource<ConsoleService, DoneableConsoleService>> getConsoleServiceClient(String namespace) {
    return (MixedOperation<ConsoleService, ConsoleServiceList, DoneableConsoleService,
            Resource<ConsoleService, DoneableConsoleService>>) client.customResources(AdminCrd.consoleServices(), ConsoleService.class, ConsoleServiceList.class, DoneableConsoleService.class).inNamespace(namespace);
}
 
Example #23
Source File: PodDisruptionBudgetOperator.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
@Override
protected MixedOperation<PodDisruptionBudget, PodDisruptionBudgetList, DoneablePodDisruptionBudget, Resource<PodDisruptionBudget, DoneablePodDisruptionBudget>> operation() {
    return client.policy().podDisruptionBudget();
}
 
Example #24
Source File: KafkaBridgeResource.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
public static MixedOperation<KafkaBridge, KafkaBridgeList, DoneableKafkaBridge, Resource<KafkaBridge, DoneableKafkaBridge>> kafkaBridgeClient() {
    return Crds.kafkaBridgeOperation(ResourceManager.kubeClient().getClient());
}
 
Example #25
Source File: RbacAPIGroupClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public MixedOperation<RoleBinding, RoleBindingList, DoneableRoleBinding, Resource<RoleBinding, DoneableRoleBinding>> roleBindings() {
  return new RoleBindingOperationsImpl(httpClient, getConfiguration());
}
 
Example #26
Source File: BatchAPIGroupClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public MixedOperation<CronJob, CronJobList, DoneableCronJob, Resource<CronJob, DoneableCronJob>> cronjobs() {
  return new CronJobOperationsImpl(httpClient, getConfiguration());
}
 
Example #27
Source File: PvcOperator.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
@Override
protected MixedOperation<PersistentVolumeClaim, PersistentVolumeClaimList, DoneablePersistentVolumeClaim, Resource<PersistentVolumeClaim, DoneablePersistentVolumeClaim>> operation() {
    return client.persistentVolumeClaims();
}
 
Example #28
Source File: DefaultKnativeClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public MixedOperation<Revision, RevisionList, DoneableRevision, Resource<Revision, DoneableRevision>> revisions() {
    return new RevisionOperationsImpl(this.getHttpClient(), this.getConfiguration());
}
 
Example #29
Source File: ClusterOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
/**
 * Asserts that Cluster Operator starts and then stops a verticle in every namespace using the namespace wildcard (*)
 * @param context test context passed in for assertions
 * @param namespaces namespaces the operator should be watching and operating on
 */
private void startStopAllNamespaces(VertxTestContext context, String namespaces, boolean openShift) throws InterruptedException {
    AtomicInteger numWatchers = new AtomicInteger(0);
    KubernetesClient client;
    if (openShift) {
        client = mock(OpenShiftClient.class);
        when(client.isAdaptable(eq(OpenShiftClient.class))).thenReturn(true);
        when(client.adapt(eq(OpenShiftClient.class))).thenReturn((OpenShiftClient) client);
    } else {
        client = mock(KubernetesClient.class);
        when(client.isAdaptable(eq(OpenShiftClient.class))).thenReturn(false);
    }
    when(client.isAdaptable(eq(OkHttpClient.class))).thenReturn(true);

    try {
        when(client.getMasterUrl()).thenReturn(new URL("http://localhost"));
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }

    MixedOperation mockCms = mock(MixedOperation.class);
    NonNamespaceOperation<CustomResourceDefinition, CustomResourceDefinitionList, DoneableCustomResourceDefinition,
            Resource<CustomResourceDefinition, DoneableCustomResourceDefinition>> mockCrds = mock(NonNamespaceOperation.class);
    Resource<CustomResourceDefinition, DoneableCustomResourceDefinition> mockResource = mock(Resource.class);
    if (openShift) {
        when(mockResource.get()).thenReturn(Crds.kafkaConnectS2I());
    } else {
        when(mockResource.get()).thenReturn(null);
    }
    when(mockCrds.withName(KafkaConnectS2I.CRD_NAME)).thenReturn(mockResource);
    when(client.customResourceDefinitions()).thenReturn(mockCrds);
    when(client.customResources(any(), any(), any(), any())).thenReturn(mockCms);

    FilterWatchListMultiDeletable mockFilteredCms = mock(FilterWatchListMultiDeletable.class);
    when(mockFilteredCms.withLabels(any())).thenReturn(mockFilteredCms);
    when(mockFilteredCms.watch(any())).thenAnswer(invo -> {
        numWatchers.incrementAndGet();
        Watch mockWatch = mock(Watch.class);
        doAnswer(invo2 -> {
            ((Watcher) invo.getArgument(0)).onClose(null);
            return null;
        }).when(mockWatch).close();
        return mockWatch;
    });
    when(mockCms.inAnyNamespace()).thenReturn(mockFilteredCms);

    Map<String, String> env = buildEnv(namespaces);

    CountDownLatch latch = new CountDownLatch(2);
    Main.run(vertx, client, new PlatformFeaturesAvailability(openShift, KubernetesVersion.V1_9),
            ClusterOperatorConfig.fromMap(env, KafkaVersionTestUtils.getKafkaVersionLookup()))
        .onComplete(context.succeeding(v -> context.verify(() -> {
            assertThat("A verticle per namespace", vertx.deploymentIDs(), hasSize(1));
            for (String deploymentId: vertx.deploymentIDs()) {
                vertx.undeploy(deploymentId, asyncResult -> {
                    if (asyncResult.failed()) {
                        log.error("Failed to undeploy {}", deploymentId);
                        context.failNow(asyncResult.cause());
                    }
                    latch.countDown();
                });
            }

            int maximumExpectedNumberOfWatchers = openShift ? 9 : 7; // we do not have connectS2I on k8s
            assertThat("Looks like there were more watchers than namespaces", numWatchers.get(), lessThanOrEqualTo(maximumExpectedNumberOfWatchers));
            latch.countDown();
        })));
    latch.await(10, TimeUnit.SECONDS);
    context.completeNow();
}
 
Example #30
Source File: DefaultServingV1Client.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public MixedOperation<Configuration, ConfigurationList, DoneableConfiguration, Resource<Configuration, DoneableConfiguration>> configurations() {
  return new ConfigurationOperationsImpl(this.getHttpClient(), this.getConfiguration());
}