Search in sources :

Example 61 with Resource

use of io.fabric8.support.api.Resource in project strimzi by strimzi.

the class AbstractAssemblyOperator method reconcileAssembly.

/**
 * Reconcile assembly resources in the given namespace having the given {@code assemblyName}.
 * Reconciliation works by getting the assembly ConfigMap in the given namespace with the given assemblyName and
 * comparing with the corresponding {@linkplain #getResources(String) resource}.
 * <ul>
 * <li>An assembly will be {@linkplain #createOrUpdate(Reconciliation, ConfigMap, Handler) created or updated} if ConfigMap is without same-named resources</li>
 * <li>An assembly will be {@linkplain #delete(Reconciliation, Handler) deleted} if resources without same-named ConfigMap</li>
 * </ul>
 */
public final void reconcileAssembly(Reconciliation reconciliation, Handler<AsyncResult<Void>> handler) {
    String namespace = reconciliation.namespace();
    String assemblyName = reconciliation.assemblyName();
    final String lockName = getLockName(assemblyType, namespace, assemblyName);
    vertx.sharedData().getLockWithTimeout(lockName, LOCK_TIMEOUT, res -> {
        if (res.succeeded()) {
            log.debug("{}: Lock {} acquired", reconciliation, lockName);
            Lock lock = res.result();
            try {
                // get ConfigMap and related resources for the specific cluster
                ConfigMap cm = configMapOperations.get(namespace, assemblyName);
                if (cm != null) {
                    log.info("{}: assembly {} should be created or updated", reconciliation, assemblyName);
                    createOrUpdate(reconciliation, cm, createResult -> {
                        lock.release();
                        log.debug("{}: Lock {} released", reconciliation, lockName);
                        handler.handle(createResult);
                    });
                } else {
                    log.info("{}: assembly {} should be deleted", reconciliation, assemblyName);
                    delete(reconciliation, deleteResult -> {
                        lock.release();
                        log.debug("{}: Lock {} released", reconciliation, lockName);
                        handler.handle(deleteResult);
                    });
                }
            } catch (Throwable ex) {
                lock.release();
                log.debug("{}: Lock {} released", reconciliation, lockName);
                handler.handle(Future.failedFuture(ex));
            }
        } else {
            log.warn("{}: Failed to acquire lock {}.", reconciliation, lockName);
        }
    });
}
Also used : ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) Lock(io.vertx.core.shareddata.Lock)

Example 62 with Resource

use of io.fabric8.support.api.Resource in project strimzi by strimzi.

the class AbstractResourceOperatorTest method createWhenExistsIsAPatch.

public void createWhenExistsIsAPatch(TestContext context, boolean cascade) {
    T 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);
    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);
    AbstractResourceOperator<C, T, L, D, R, P> op = createResourceOperations(vertx, mockClient);
    Async async = context.async();
    Future<ReconcileResult<P>> fut = op.createOrUpdate(resource);
    fut.setHandler(ar -> {
        assertTrue(ar.succeeded());
        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.complete();
    });
}
Also used : Resource(io.fabric8.kubernetes.client.dsl.Resource) NonNamespaceOperation(io.fabric8.kubernetes.client.dsl.NonNamespaceOperation) Async(io.vertx.ext.unit.Async) MixedOperation(io.fabric8.kubernetes.client.dsl.MixedOperation)

Example 63 with Resource

use of io.fabric8.support.api.Resource in project strimzi by strimzi.

the class MockKube method buildStatefulSets.

private MixedOperation<StatefulSet, StatefulSetList, DoneableStatefulSet, RollableScalableResource<StatefulSet, DoneableStatefulSet>> buildStatefulSets(MixedOperation<Pod, PodList, DoneablePod, PodResource<Pod, DoneablePod>> mockPods) {
    return new AbstractMockBuilder<StatefulSet, StatefulSetList, DoneableStatefulSet, RollableScalableResource<StatefulSet, DoneableStatefulSet>>(StatefulSet.class, StatefulSetList.class, DoneableStatefulSet.class, castClass(RollableScalableResource.class), ssDb) {

        @Override
        protected void nameScopedMocks(RollableScalableResource<StatefulSet, DoneableStatefulSet> resource, String resourceName) {
            mockGet(resourceName, resource);
            // mockCreate("endpoint", endpointDb, resourceName, resource);
            mockCascading(resource);
            mockPatch(resourceName, resource);
            mockDelete(resourceName, resource);
            mockIsReady(resourceName, resource);
            when(resource.create(any())).thenAnswer(cinvocation -> {
                checkNotExists(resourceName);
                StatefulSet argument = cinvocation.getArgument(0);
                LOGGER.debug("create {} {} -> {}", resourceType, resourceName, argument);
                ssDb.put(resourceName, copyResource(argument));
                for (int i = 0; i < argument.getSpec().getReplicas(); i++) {
                    String podName = argument.getMetadata().getName() + "-" + i;
                    podDb.put(podName, new PodBuilder().withNewMetadata().withNamespace(argument.getMetadata().getNamespace()).withName(podName).endMetadata().build());
                }
                return argument;
            });
            EditReplacePatchDeletable<StatefulSet, StatefulSet, DoneableStatefulSet, Boolean> c = mock(EditReplacePatchDeletable.class);
            when(resource.cascading(false)).thenReturn(c);
            when(c.patch(any())).thenAnswer(patchInvocation -> {
                StatefulSet argument = patchInvocation.getArgument(0);
                return doPatch(resourceName, argument);
            });
            when(resource.scale(anyInt(), anyBoolean())).thenAnswer(invocation -> {
                checkDoesExist(resourceName);
                StatefulSet ss = copyResource(ssDb.get(resourceName));
                int newScale = invocation.getArgument(0);
                ss.getSpec().setReplicas(newScale);
                return doPatch(resourceName, ss);
            });
            when(resource.scale(anyInt())).thenAnswer(invocation -> {
                checkDoesExist(resourceName);
                StatefulSet ss = copyResource(ssDb.get(resourceName));
                int newScale = invocation.getArgument(0);
                ss.getSpec().setReplicas(newScale);
                return doPatch(resourceName, ss);
            });
            when(resource.isReady()).thenAnswer(i -> {
                LOGGER.debug("{} {} is ready", resourceType, resourceName);
                return true;
            });
            mockPods.inNamespace(any()).withName(any()).watch(new Watcher<Pod>() {

                @Override
                public void eventReceived(Action action, Pod resource) {
                    if (action == Action.DELETED) {
                        String podName = resource.getMetadata().getName();
                        String podNamespace = resource.getMetadata().getNamespace();
                        StatefulSet statefulSet = ssDb.get(resourceName);
                        if (podName.startsWith(resourceName + "-") && Integer.parseInt(podName.substring(podName.lastIndexOf("-") + 1)) < statefulSet.getSpec().getReplicas()) {
                            mockPods.inNamespace(podNamespace).withName(podName).create(resource);
                        }
                    }
                }

                @Override
                public void onClose(KubernetesClientException e) {
                }
            });
        }

        private StatefulSet doPatch(String resourceName, StatefulSet argument) {
            int oldScale = ssDb.get(resourceName).getSpec().getReplicas();
            int newScale = argument.getSpec().getReplicas();
            if (newScale > oldScale) {
                LOGGER.debug("scaling up {} {} from {} to {}", resourceType, resourceName, oldScale, newScale);
                Pod examplePod = mockPods.inNamespace(argument.getMetadata().getNamespace()).withName(argument.getMetadata().getName() + "-0").get();
                for (int i = oldScale; i < newScale; i++) {
                    String newPodName = argument.getMetadata().getName() + "-" + i;
                    mockPods.inNamespace(argument.getMetadata().getNamespace()).withName(newPodName).create(new PodBuilder(examplePod).editMetadata().withName(newPodName).endMetadata().build());
                }
                ssDb.put(resourceName, copyResource(argument));
            } else if (newScale < oldScale) {
                ssDb.put(resourceName, copyResource(argument));
                LOGGER.debug("scaling down {} {} from {} to {}", resourceType, resourceName, oldScale, newScale);
                for (int i = oldScale - 1; i >= newScale; i--) {
                    String newPodName = argument.getMetadata().getName() + "-" + i;
                    mockPods.inNamespace(argument.getMetadata().getNamespace()).withName(newPodName).delete();
                }
            } else {
                ssDb.put(resourceName, copyResource(argument));
            }
            return argument;
        }
    }.build();
}
Also used : DoneablePod(io.fabric8.kubernetes.api.model.DoneablePod) KubernetesResourceList(io.fabric8.kubernetes.api.model.KubernetesResourceList) Doneable(io.fabric8.kubernetes.api.model.Doneable) Deployment(io.fabric8.kubernetes.api.model.extensions.Deployment) LoggerFactory(org.slf4j.LoggerFactory) Watcher(io.fabric8.kubernetes.client.Watcher) DoneablePersistentVolumeClaim(io.fabric8.kubernetes.api.model.DoneablePersistentVolumeClaim) Resource(io.fabric8.kubernetes.client.dsl.Resource) PodBuilder(io.fabric8.kubernetes.api.model.PodBuilder) Map(java.util.Map) Mockito.doAnswer(org.mockito.Mockito.doAnswer) PersistentVolumeClaimList(io.fabric8.kubernetes.api.model.PersistentVolumeClaimList) EditReplacePatchDeletable(io.fabric8.kubernetes.client.dsl.EditReplacePatchDeletable) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) ExtensionsAPIGroupDSL(io.fabric8.kubernetes.client.dsl.ExtensionsAPIGroupDSL) Predicate(java.util.function.Predicate) Collection(java.util.Collection) Set(java.util.Set) HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) Collectors(java.util.stream.Collectors) DoneableDeployment(io.fabric8.kubernetes.api.model.extensions.DoneableDeployment) DoneableEndpoints(io.fabric8.kubernetes.api.model.DoneableEndpoints) PersistentVolumeClaim(io.fabric8.kubernetes.api.model.PersistentVolumeClaim) ServiceList(io.fabric8.kubernetes.api.model.ServiceList) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) DoneableService(io.fabric8.kubernetes.api.model.DoneableService) MixedOperation(io.fabric8.kubernetes.client.dsl.MixedOperation) DoneableStatefulSet(io.fabric8.kubernetes.api.model.extensions.DoneableStatefulSet) DeploymentList(io.fabric8.kubernetes.api.model.extensions.DeploymentList) EndpointsList(io.fabric8.kubernetes.api.model.EndpointsList) Watch(io.fabric8.kubernetes.client.Watch) HashMap(java.util.HashMap) ArgumentMatchers.anyBoolean(org.mockito.ArgumentMatchers.anyBoolean) ScalableResource(io.fabric8.kubernetes.client.dsl.ScalableResource) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) RollableScalableResource(io.fabric8.kubernetes.client.dsl.RollableScalableResource) Service(io.fabric8.kubernetes.api.model.Service) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) StatefulSetList(io.fabric8.kubernetes.api.model.extensions.StatefulSetList) Endpoints(io.fabric8.kubernetes.api.model.Endpoints) Logger(org.slf4j.Logger) Collections.emptySet(java.util.Collections.emptySet) StatefulSet(io.fabric8.kubernetes.api.model.extensions.StatefulSet) OngoingStubbing(org.mockito.stubbing.OngoingStubbing) ConfigMapList(io.fabric8.kubernetes.api.model.ConfigMapList) Pod(io.fabric8.kubernetes.api.model.Pod) Mockito.when(org.mockito.Mockito.when) DoneableConfigMap(io.fabric8.kubernetes.api.model.DoneableConfigMap) PodResource(io.fabric8.kubernetes.client.dsl.PodResource) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) KubernetesResource(io.fabric8.kubernetes.api.model.KubernetesResource) PodList(io.fabric8.kubernetes.api.model.PodList) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) AppsAPIGroupDSL(io.fabric8.kubernetes.client.dsl.AppsAPIGroupDSL) DoneableStatefulSet(io.fabric8.kubernetes.api.model.extensions.DoneableStatefulSet) DoneablePod(io.fabric8.kubernetes.api.model.DoneablePod) Pod(io.fabric8.kubernetes.api.model.Pod) PodBuilder(io.fabric8.kubernetes.api.model.PodBuilder) EditReplacePatchDeletable(io.fabric8.kubernetes.client.dsl.EditReplacePatchDeletable) Watcher(io.fabric8.kubernetes.client.Watcher) RollableScalableResource(io.fabric8.kubernetes.client.dsl.RollableScalableResource) StatefulSetList(io.fabric8.kubernetes.api.model.extensions.StatefulSetList) DoneableStatefulSet(io.fabric8.kubernetes.api.model.extensions.DoneableStatefulSet) StatefulSet(io.fabric8.kubernetes.api.model.extensions.StatefulSet) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 64 with Resource

use of io.fabric8.support.api.Resource in project strimzi by strimzi.

the class MockKube method build.

public KubernetesClient build() {
    KubernetesClient mockClient = mock(KubernetesClient.class);
    MixedOperation<ConfigMap, ConfigMapList, DoneableConfigMap, Resource<ConfigMap, DoneableConfigMap>> mockCms = buildConfigMaps();
    MixedOperation<PersistentVolumeClaim, PersistentVolumeClaimList, DoneablePersistentVolumeClaim, Resource<PersistentVolumeClaim, DoneablePersistentVolumeClaim>> mockPvcs = buildPvcs();
    MixedOperation<Endpoints, EndpointsList, DoneableEndpoints, Resource<Endpoints, DoneableEndpoints>> mockEndpoints = buildEndpoints();
    MixedOperation<Service, ServiceList, DoneableService, Resource<Service, DoneableService>> mockSvc = buildServices();
    MixedOperation<Pod, PodList, DoneablePod, PodResource<Pod, DoneablePod>> mockPods = buildPods();
    MixedOperation<StatefulSet, StatefulSetList, DoneableStatefulSet, RollableScalableResource<StatefulSet, DoneableStatefulSet>> mockSs = buildStatefulSets(mockPods);
    MixedOperation<Deployment, DeploymentList, DoneableDeployment, ScalableResource<Deployment, DoneableDeployment>> mockDep = buildDeployments();
    when(mockClient.configMaps()).thenReturn(mockCms);
    when(mockClient.services()).thenReturn(mockSvc);
    AppsAPIGroupDSL api = mock(AppsAPIGroupDSL.class);
    when(api.statefulSets()).thenReturn(mockSs);
    when(mockClient.apps()).thenReturn(api);
    ExtensionsAPIGroupDSL ext = mock(ExtensionsAPIGroupDSL.class);
    when(mockClient.extensions()).thenReturn(ext);
    when(ext.deployments()).thenReturn(mockDep);
    when(mockClient.pods()).thenReturn(mockPods);
    when(mockClient.endpoints()).thenReturn(mockEndpoints);
    when(mockClient.persistentVolumeClaims()).thenReturn(mockPvcs);
    return mockClient;
}
Also used : ConfigMapList(io.fabric8.kubernetes.api.model.ConfigMapList) PodResource(io.fabric8.kubernetes.client.dsl.PodResource) PersistentVolumeClaimList(io.fabric8.kubernetes.api.model.PersistentVolumeClaimList) DoneableStatefulSet(io.fabric8.kubernetes.api.model.extensions.DoneableStatefulSet) DoneablePod(io.fabric8.kubernetes.api.model.DoneablePod) Deployment(io.fabric8.kubernetes.api.model.extensions.Deployment) DoneableDeployment(io.fabric8.kubernetes.api.model.extensions.DoneableDeployment) DoneableEndpoints(io.fabric8.kubernetes.api.model.DoneableEndpoints) Endpoints(io.fabric8.kubernetes.api.model.Endpoints) DoneableDeployment(io.fabric8.kubernetes.api.model.extensions.DoneableDeployment) DeploymentList(io.fabric8.kubernetes.api.model.extensions.DeploymentList) DoneableService(io.fabric8.kubernetes.api.model.DoneableService) ExtensionsAPIGroupDSL(io.fabric8.kubernetes.client.dsl.ExtensionsAPIGroupDSL) StatefulSetList(io.fabric8.kubernetes.api.model.extensions.StatefulSetList) DoneableConfigMap(io.fabric8.kubernetes.api.model.DoneableConfigMap) EndpointsList(io.fabric8.kubernetes.api.model.EndpointsList) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) PodList(io.fabric8.kubernetes.api.model.PodList) DoneableConfigMap(io.fabric8.kubernetes.api.model.DoneableConfigMap) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) DoneablePod(io.fabric8.kubernetes.api.model.DoneablePod) Pod(io.fabric8.kubernetes.api.model.Pod) ServiceList(io.fabric8.kubernetes.api.model.ServiceList) Resource(io.fabric8.kubernetes.client.dsl.Resource) ScalableResource(io.fabric8.kubernetes.client.dsl.ScalableResource) RollableScalableResource(io.fabric8.kubernetes.client.dsl.RollableScalableResource) PodResource(io.fabric8.kubernetes.client.dsl.PodResource) KubernetesResource(io.fabric8.kubernetes.api.model.KubernetesResource) DoneableService(io.fabric8.kubernetes.api.model.DoneableService) Service(io.fabric8.kubernetes.api.model.Service) AppsAPIGroupDSL(io.fabric8.kubernetes.client.dsl.AppsAPIGroupDSL) ScalableResource(io.fabric8.kubernetes.client.dsl.ScalableResource) RollableScalableResource(io.fabric8.kubernetes.client.dsl.RollableScalableResource) DoneableEndpoints(io.fabric8.kubernetes.api.model.DoneableEndpoints) RollableScalableResource(io.fabric8.kubernetes.client.dsl.RollableScalableResource) DoneablePersistentVolumeClaim(io.fabric8.kubernetes.api.model.DoneablePersistentVolumeClaim) PersistentVolumeClaim(io.fabric8.kubernetes.api.model.PersistentVolumeClaim) DoneablePersistentVolumeClaim(io.fabric8.kubernetes.api.model.DoneablePersistentVolumeClaim) DoneableStatefulSet(io.fabric8.kubernetes.api.model.extensions.DoneableStatefulSet) StatefulSet(io.fabric8.kubernetes.api.model.extensions.StatefulSet)

Example 65 with Resource

use of io.fabric8.support.api.Resource in project strimzi by strimzi.

the class AbtractReadyResourceOperatorTest method waitUntilReadyWhenDoesNotExist.

@Test
public void waitUntilReadyWhenDoesNotExist(TestContext 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, P> op = createResourceOperations(vertx, mockClient);
    Async async = context.async();
    Future<Void> fut = op.readiness(NAMESPACE, RESOURCE_NAME, 20, 100);
    fut.setHandler(ar -> {
        assertTrue(ar.failed());
        assertThat(ar.cause(), instanceOf(TimeoutException.class));
        verify(mockResource, atLeastOnce()).get();
        verify(mockResource, never()).isReady();
        async.complete();
    });
}
Also used : Resource(io.fabric8.kubernetes.client.dsl.Resource) NonNamespaceOperation(io.fabric8.kubernetes.client.dsl.NonNamespaceOperation) Async(io.vertx.ext.unit.Async) MixedOperation(io.fabric8.kubernetes.client.dsl.MixedOperation) Test(org.junit.Test)

Aggregations

HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)25 Resource (io.fabric8.kubernetes.client.dsl.Resource)25 Map (java.util.Map)20 Test (org.junit.Test)20 IOException (java.io.IOException)19 HashMap (java.util.HashMap)16 Deployment (io.fabric8.kubernetes.api.model.extensions.Deployment)14 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)14 MixedOperation (io.fabric8.kubernetes.client.dsl.MixedOperation)14 Resource (org.osgi.resource.Resource)14 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)13 NonNamespaceOperation (io.fabric8.kubernetes.client.dsl.NonNamespaceOperation)13 ArrayList (java.util.ArrayList)13 Async (io.vertx.ext.unit.Async)12 File (java.io.File)10 ReplicationController (io.fabric8.kubernetes.api.model.ReplicationController)9 Service (io.fabric8.kubernetes.api.model.Service)9 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)9 DeploymentConfig (io.fabric8.openshift.api.model.DeploymentConfig)8 Bundle (org.osgi.framework.Bundle)7