Search in sources :

Example 1 with ServiceAccountBuilder

use of io.fabric8.kubernetes.api.model.ServiceAccountBuilder in project strimzi by strimzi.

the class SetupDrainCleaner method applyInstallFiles.

public void applyInstallFiles(ExtensionContext extensionContext) {
    List<File> drainCleanerFiles = Arrays.stream(new File(PATH_TO_DC_CONFIG).listFiles()).sorted().filter(File::isFile).collect(Collectors.toList());
    drainCleanerFiles.forEach(file -> {
        if (!file.getName().contains("README") && !file.getName().contains("Namespace") && !file.getName().contains("Deployment")) {
            final String resourceType = file.getName().split("-")[1].split(".yaml")[0];
            switch(resourceType) {
                case Constants.CLUSTER_ROLE:
                    ClusterRole clusterRole = TestUtils.configFromYaml(file, ClusterRole.class);
                    ResourceManager.getInstance().createResource(extensionContext, clusterRole);
                    break;
                case Constants.SERVICE_ACCOUNT:
                    ServiceAccount serviceAccount = TestUtils.configFromYaml(file, ServiceAccount.class);
                    ResourceManager.getInstance().createResource(extensionContext, new ServiceAccountBuilder(serviceAccount).editMetadata().withNamespace(Constants.DRAIN_CLEANER_NAMESPACE).endMetadata().build());
                    break;
                case Constants.CLUSTER_ROLE_BINDING:
                    ClusterRoleBinding clusterRoleBinding = TestUtils.configFromYaml(file, ClusterRoleBinding.class);
                    ResourceManager.getInstance().createResource(extensionContext, new ClusterRoleBindingBuilder(clusterRoleBinding).build());
                    break;
                case Constants.SECRET:
                    Secret secret = TestUtils.configFromYaml(file, Secret.class);
                    ResourceManager.getInstance().createResource(extensionContext, secret);
                    break;
                case Constants.SERVICE:
                    Service service = TestUtils.configFromYaml(file, Service.class);
                    ResourceManager.getInstance().createResource(extensionContext, service);
                    break;
                case Constants.VALIDATION_WEBHOOK_CONFIG:
                    ValidatingWebhookConfiguration webhookConfiguration = TestUtils.configFromYaml(file, ValidatingWebhookConfiguration.class);
                    ResourceManager.getInstance().createResource(extensionContext, webhookConfiguration);
                    break;
                default:
                    LOGGER.error("Unknown installation resource type: {}", resourceType);
                    throw new RuntimeException("Unknown installation resource type:" + resourceType);
            }
        }
    });
}
Also used : Secret(io.fabric8.kubernetes.api.model.Secret) ServiceAccount(io.fabric8.kubernetes.api.model.ServiceAccount) ValidatingWebhookConfiguration(io.fabric8.kubernetes.api.model.admissionregistration.v1.ValidatingWebhookConfiguration) ClusterRoleBindingBuilder(io.fabric8.kubernetes.api.model.rbac.ClusterRoleBindingBuilder) ClusterRoleBinding(io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding) ServiceAccountBuilder(io.fabric8.kubernetes.api.model.ServiceAccountBuilder) Service(io.fabric8.kubernetes.api.model.Service) File(java.io.File) ClusterRole(io.fabric8.kubernetes.api.model.rbac.ClusterRole)

Example 2 with ServiceAccountBuilder

use of io.fabric8.kubernetes.api.model.ServiceAccountBuilder in project strimzi-kafka-operator by strimzi.

the class ServiceAccountOperatorTest method testSecretsPatching.

@Test
public void testSecretsPatching(VertxTestContext context) {
    List<ObjectReference> secrets = List.of(new ObjectReferenceBuilder().withName("secretName1").build(), new ObjectReferenceBuilder().withName("secretName2").build());
    ServiceAccount current = new ServiceAccountBuilder().withNewMetadata().withNamespace(NAMESPACE).withName(RESOURCE_NAME).endMetadata().withSecrets(secrets).build();
    ServiceAccount desired = new ServiceAccountBuilder().withNewMetadata().withNamespace(NAMESPACE).withName(RESOURCE_NAME).withLabels(Map.of("lKey", "lValue")).withAnnotations(Map.of("aKey", "aValue")).endMetadata().build();
    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenReturn(current);
    ArgumentCaptor<ServiceAccount> saCaptor = ArgumentCaptor.forClass(ServiceAccount.class);
    when(mockResource.patch(saCaptor.capture())).thenReturn(desired);
    when(mockResource.withPropagationPolicy(DeletionPropagation.FOREGROUND)).thenReturn(mockResource);
    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);
    KubernetesClient mockClient = mock(clientType());
    mocker(mockClient, mockCms);
    ServiceAccountOperator op = new ServiceAccountOperator(vertx, mockClient, true);
    Checkpoint async = context.checkpoint();
    op.reconcile(Reconciliation.DUMMY_RECONCILIATION, NAMESPACE, RESOURCE_NAME, desired).onComplete(context.succeeding(rr -> {
        verify(mockResource, times(1)).patch(any(ServiceAccount.class));
        assertThat(saCaptor.getValue(), is(notNullValue()));
        assertThat(saCaptor.getValue().getSecrets().size(), is(2));
        assertThat(saCaptor.getValue().getSecrets(), is(secrets));
        assertThat(saCaptor.getValue().getMetadata().getLabels().get("lKey"), is("lValue"));
        assertThat(saCaptor.getValue().getMetadata().getAnnotations().get("aKey"), is("aValue"));
        async.flag();
    }));
}
Also used : VertxTestContext(io.vertx.junit5.VertxTestContext) CoreMatchers.is(org.hamcrest.CoreMatchers.is) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) DeletionPropagation(io.fabric8.kubernetes.api.model.DeletionPropagation) MixedOperation(io.fabric8.kubernetes.client.dsl.MixedOperation) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) Resource(io.fabric8.kubernetes.client.dsl.Resource) ArgumentCaptor(org.mockito.ArgumentCaptor) ServiceAccountList(io.fabric8.kubernetes.api.model.ServiceAccountList) Map(java.util.Map) Collections.singletonMap(java.util.Collections.singletonMap) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) ServiceAccountBuilder(io.fabric8.kubernetes.api.model.ServiceAccountBuilder) Vertx(io.vertx.core.Vertx) ObjectReference(io.fabric8.kubernetes.api.model.ObjectReference) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) ObjectReferenceBuilder(io.fabric8.kubernetes.api.model.ObjectReferenceBuilder) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) Reconciliation(io.strimzi.operator.common.Reconciliation) List(java.util.List) Mockito.never(org.mockito.Mockito.never) NonNamespaceOperation(io.fabric8.kubernetes.client.dsl.NonNamespaceOperation) ArgumentMatchers.matches(org.mockito.ArgumentMatchers.matches) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) Checkpoint(io.vertx.junit5.Checkpoint) ServiceAccount(io.fabric8.kubernetes.api.model.ServiceAccount) Mockito.mock(org.mockito.Mockito.mock) ServiceAccount(io.fabric8.kubernetes.api.model.ServiceAccount) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) Resource(io.fabric8.kubernetes.client.dsl.Resource) ServiceAccountBuilder(io.fabric8.kubernetes.api.model.ServiceAccountBuilder) NonNamespaceOperation(io.fabric8.kubernetes.client.dsl.NonNamespaceOperation) Checkpoint(io.vertx.junit5.Checkpoint) ObjectReference(io.fabric8.kubernetes.api.model.ObjectReference) ObjectReferenceBuilder(io.fabric8.kubernetes.api.model.ObjectReferenceBuilder) MixedOperation(io.fabric8.kubernetes.client.dsl.MixedOperation) Test(org.junit.jupiter.api.Test)

Example 3 with ServiceAccountBuilder

use of io.fabric8.kubernetes.api.model.ServiceAccountBuilder in project strimzi-kafka-operator by strimzi.

the class SetupClusterOperator method applyClusterOperatorInstallFiles.

/**
 * Perform application of ServiceAccount, Roles and CRDs needed for proper cluster operator deployment.
 * Configuration files are loaded from packaging/install/cluster-operator directory.
 */
public void applyClusterOperatorInstallFiles(String namespace) {
    List<File> operatorFiles = Arrays.stream(new File(CO_INSTALL_DIR).listFiles()).sorted().filter(File::isFile).filter(file -> !file.getName().matches(".*(Binding|Deployment)-.*")).collect(Collectors.toList());
    for (File operatorFile : operatorFiles) {
        File createFile = operatorFile;
        if (createFile.getName().contains(Constants.CLUSTER_ROLE + "-")) {
            createFile = switchClusterRolesToRolesIfNeeded(createFile);
        }
        final String resourceType = createFile.getName().split("-")[1];
        LOGGER.debug("Installation resource type: {}", resourceType);
        switch(resourceType) {
            case Constants.ROLE:
                Role role = TestUtils.configFromYaml(createFile, Role.class);
                ResourceManager.getInstance().createResource(extensionContext, new RoleBuilder(role).editMetadata().withNamespace(namespace).endMetadata().build());
                break;
            case Constants.CLUSTER_ROLE:
                ClusterRole clusterRole = TestUtils.configFromYaml(createFile, ClusterRole.class);
                ResourceManager.getInstance().createResource(extensionContext, clusterRole);
                break;
            case Constants.SERVICE_ACCOUNT:
                ServiceAccount serviceAccount = TestUtils.configFromYaml(createFile, ServiceAccount.class);
                ResourceManager.getInstance().createResource(extensionContext, new ServiceAccountBuilder(serviceAccount).editMetadata().withNamespace(namespace).endMetadata().build());
                break;
            case Constants.CONFIG_MAP:
                ConfigMap configMap = TestUtils.configFromYaml(createFile, ConfigMap.class);
                ResourceManager.getInstance().createResource(extensionContext, new ConfigMapBuilder(configMap).editMetadata().withNamespace(namespace).endMetadata().build());
                break;
            case Constants.CUSTOM_RESOURCE_DEFINITION_SHORT:
                CustomResourceDefinition customResourceDefinition = TestUtils.configFromYaml(createFile, CustomResourceDefinition.class);
                ResourceManager.getInstance().createResource(extensionContext, customResourceDefinition);
                break;
            default:
                LOGGER.error("Unknown installation resource type: {}", resourceType);
                throw new RuntimeException("Unknown installation resource type:" + resourceType);
        }
    }
}
Also used : Environment(io.strimzi.systemtest.Environment) ClusterRoleBinding(io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding) EnvVar(io.fabric8.kubernetes.api.model.EnvVar) Arrays(java.util.Arrays) OlmResource(io.strimzi.systemtest.resources.operator.specific.OlmResource) RoleBindingResource(io.strimzi.systemtest.resources.kubernetes.RoleBindingResource) NetworkPolicyResource(io.strimzi.systemtest.resources.kubernetes.NetworkPolicyResource) Role(io.fabric8.kubernetes.api.model.rbac.Role) Level(org.apache.logging.log4j.Level) HashMap(java.util.HashMap) ExtensionContext(org.junit.jupiter.api.extension.ExtensionContext) ClusterRoleBindingResource(io.strimzi.systemtest.resources.kubernetes.ClusterRoleBindingResource) ArrayList(java.util.ArrayList) RoleBuilder(io.fabric8.kubernetes.api.model.rbac.RoleBuilder) HelmResource(io.strimzi.systemtest.resources.operator.specific.HelmResource) KubeClusterResource(io.strimzi.test.k8s.KubeClusterResource) Map(java.util.Map) TestUtils(io.strimzi.test.TestUtils) Assumptions.assumeTrue(org.junit.jupiter.api.Assumptions.assumeTrue) CustomResourceDefinition(io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceDefinition) StUtils(io.strimzi.systemtest.utils.StUtils) ClusterOperatorRBACType(io.strimzi.systemtest.enums.ClusterOperatorRBACType) BeforeAllOnce(io.strimzi.systemtest.BeforeAllOnce) OpenShift(io.strimzi.test.k8s.cluster.OpenShift) Predicate(java.util.function.Predicate) CollectorElement(io.strimzi.test.logs.CollectorElement) ServiceAccountBuilder(io.fabric8.kubernetes.api.model.ServiceAccountBuilder) Constants(io.strimzi.systemtest.Constants) IOException(java.io.IOException) ClusterRoleBindingTemplates(io.strimzi.systemtest.templates.kubernetes.ClusterRoleBindingTemplates) Collectors(java.util.stream.Collectors) File(java.io.File) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) KubeClusterResource.kubeClient(io.strimzi.test.k8s.KubeClusterResource.kubeClient) ConfigMapBuilder(io.fabric8.kubernetes.api.model.ConfigMapBuilder) Objects(java.util.Objects) RoleResource(io.strimzi.systemtest.resources.kubernetes.RoleResource) List(java.util.List) Exec(io.strimzi.test.executor.Exec) Logger(org.apache.logging.log4j.Logger) ResourceManager(io.strimzi.systemtest.resources.ResourceManager) ClusterRole(io.fabric8.kubernetes.api.model.rbac.ClusterRole) ServiceAccount(io.fabric8.kubernetes.api.model.ServiceAccount) LogManager(org.apache.logging.log4j.LogManager) Collections(java.util.Collections) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) ServiceAccount(io.fabric8.kubernetes.api.model.ServiceAccount) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) CustomResourceDefinition(io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceDefinition) ServiceAccountBuilder(io.fabric8.kubernetes.api.model.ServiceAccountBuilder) RoleBuilder(io.fabric8.kubernetes.api.model.rbac.RoleBuilder) ClusterRole(io.fabric8.kubernetes.api.model.rbac.ClusterRole) Role(io.fabric8.kubernetes.api.model.rbac.Role) ClusterRole(io.fabric8.kubernetes.api.model.rbac.ClusterRole) ConfigMapBuilder(io.fabric8.kubernetes.api.model.ConfigMapBuilder) File(java.io.File)

Example 4 with ServiceAccountBuilder

use of io.fabric8.kubernetes.api.model.ServiceAccountBuilder in project strimzi-kafka-operator by strimzi.

the class SetupDrainCleaner method applyInstallFiles.

public void applyInstallFiles(ExtensionContext extensionContext) {
    List<File> drainCleanerFiles = Arrays.stream(new File(PATH_TO_DC_CONFIG).listFiles()).sorted().filter(File::isFile).collect(Collectors.toList());
    drainCleanerFiles.forEach(file -> {
        if (!file.getName().contains("README") && !file.getName().contains("Namespace") && !file.getName().contains("Deployment")) {
            final String resourceType = file.getName().split("-")[1].split(".yaml")[0];
            switch(resourceType) {
                case Constants.CLUSTER_ROLE:
                    ClusterRole clusterRole = TestUtils.configFromYaml(file, ClusterRole.class);
                    ResourceManager.getInstance().createResource(extensionContext, clusterRole);
                    break;
                case Constants.SERVICE_ACCOUNT:
                    ServiceAccount serviceAccount = TestUtils.configFromYaml(file, ServiceAccount.class);
                    ResourceManager.getInstance().createResource(extensionContext, new ServiceAccountBuilder(serviceAccount).editMetadata().withNamespace(Constants.DRAIN_CLEANER_NAMESPACE).endMetadata().build());
                    break;
                case Constants.CLUSTER_ROLE_BINDING:
                    ClusterRoleBinding clusterRoleBinding = TestUtils.configFromYaml(file, ClusterRoleBinding.class);
                    ResourceManager.getInstance().createResource(extensionContext, new ClusterRoleBindingBuilder(clusterRoleBinding).build());
                    break;
                case Constants.SECRET:
                    Secret secret = TestUtils.configFromYaml(file, Secret.class);
                    ResourceManager.getInstance().createResource(extensionContext, secret);
                    break;
                case Constants.SERVICE:
                    Service service = TestUtils.configFromYaml(file, Service.class);
                    ResourceManager.getInstance().createResource(extensionContext, service);
                    break;
                case Constants.VALIDATION_WEBHOOK_CONFIG:
                    ValidatingWebhookConfiguration webhookConfiguration = TestUtils.configFromYaml(file, ValidatingWebhookConfiguration.class);
                    ResourceManager.getInstance().createResource(extensionContext, webhookConfiguration);
                    break;
                default:
                    LOGGER.error("Unknown installation resource type: {}", resourceType);
                    throw new RuntimeException("Unknown installation resource type:" + resourceType);
            }
        }
    });
}
Also used : Secret(io.fabric8.kubernetes.api.model.Secret) ServiceAccount(io.fabric8.kubernetes.api.model.ServiceAccount) ValidatingWebhookConfiguration(io.fabric8.kubernetes.api.model.admissionregistration.v1.ValidatingWebhookConfiguration) ClusterRoleBindingBuilder(io.fabric8.kubernetes.api.model.rbac.ClusterRoleBindingBuilder) ClusterRoleBinding(io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding) ServiceAccountBuilder(io.fabric8.kubernetes.api.model.ServiceAccountBuilder) Service(io.fabric8.kubernetes.api.model.Service) File(java.io.File) ClusterRole(io.fabric8.kubernetes.api.model.rbac.ClusterRole)

Example 5 with ServiceAccountBuilder

use of io.fabric8.kubernetes.api.model.ServiceAccountBuilder in project fabric8 by fabric8io.

the class SessionListener method generateServiceAccount.

private void generateServiceAccount(KubernetesClient client, Session session, Set<Secret> secrets, String serviceAccountName) {
    List<ObjectReference> secretRefs = new ArrayList<>();
    for (Secret secret : secrets) {
        secretRefs.add(new ObjectReferenceBuilder().withNamespace(session.getNamespace()).withName(KubernetesHelper.getName(secret)).build());
    }
    SecurityContextConstraints securityContextConstraints = client.securityContextConstraints().withName(session.getNamespace()).get();
    if (securityContextConstraints == null) {
        client.securityContextConstraints().createNew().withNewMetadata().withName(session.getNamespace()).endMetadata().withAllowHostDirVolumePlugin(true).withAllowPrivilegedContainer(true).withNewRunAsUser().withType("RunAsAny").endRunAsUser().withNewSeLinuxContext().withType("RunAsAny").endSeLinuxContext().withUsers("system:serviceaccount:" + session.getNamespace() + ":" + serviceAccountName).done();
    }
    ServiceAccount serviceAccount = client.serviceAccounts().inNamespace(session.getNamespace()).withName(serviceAccountName).get();
    if (serviceAccount == null) {
        client.serviceAccounts().inNamespace(session.getNamespace()).createNew().withNewMetadata().withName(serviceAccountName).endMetadata().withSecrets(secretRefs).done();
    } else {
        client.serviceAccounts().inNamespace(session.getNamespace()).withName(serviceAccountName).replace(new ServiceAccountBuilder(serviceAccount).withNewMetadata().withName(serviceAccountName).endMetadata().addToSecrets(secretRefs.toArray(new ObjectReference[secretRefs.size()])).build());
    }
}
Also used : SecurityContextConstraints(io.fabric8.openshift.api.model.SecurityContextConstraints)

Aggregations

ServiceAccount (io.fabric8.kubernetes.api.model.ServiceAccount)6 ServiceAccountBuilder (io.fabric8.kubernetes.api.model.ServiceAccountBuilder)6 ClusterRole (io.fabric8.kubernetes.api.model.rbac.ClusterRole)4 ClusterRoleBinding (io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding)4 List (java.util.List)4 Map (java.util.Map)4 File (java.io.File)3 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)2 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)2 ConfigMapBuilder (io.fabric8.kubernetes.api.model.ConfigMapBuilder)2 DeletionPropagation (io.fabric8.kubernetes.api.model.DeletionPropagation)2 EnvVar (io.fabric8.kubernetes.api.model.EnvVar)2 ObjectReference (io.fabric8.kubernetes.api.model.ObjectReference)2 ObjectReferenceBuilder (io.fabric8.kubernetes.api.model.ObjectReferenceBuilder)2 Secret (io.fabric8.kubernetes.api.model.Secret)2 Service (io.fabric8.kubernetes.api.model.Service)2 ServiceAccountList (io.fabric8.kubernetes.api.model.ServiceAccountList)2 ValidatingWebhookConfiguration (io.fabric8.kubernetes.api.model.admissionregistration.v1.ValidatingWebhookConfiguration)2 CustomResourceDefinition (io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceDefinition)2 ClusterRoleBindingBuilder (io.fabric8.kubernetes.api.model.rbac.ClusterRoleBindingBuilder)2