Search in sources :

Example 26 with ClusterRole

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

the class ClusterRoleBindingTemplates method clusterRoleBindingsForAllNamespaces.

public static List<ClusterRoleBinding> clusterRoleBindingsForAllNamespaces(String namespace, String coName) {
    LOGGER.info("Creating ClusterRoleBinding that grant cluster-wide access to all OpenShift projects");
    List<ClusterRoleBinding> kCRBList = new ArrayList<>();
    kCRBList.add(new ClusterRoleBindingBuilder().withNewMetadata().withName(coName + "-namespaced").endMetadata().withNewRoleRef().withApiGroup("rbac.authorization.k8s.io").withKind("ClusterRole").withName("strimzi-cluster-operator-namespaced").endRoleRef().withSubjects(new SubjectBuilder().withKind("ServiceAccount").withName("strimzi-cluster-operator").withNamespace(namespace).build()).build());
    kCRBList.add(new ClusterRoleBindingBuilder().withNewMetadata().withName(coName + "-entity-operator").endMetadata().withNewRoleRef().withApiGroup("rbac.authorization.k8s.io").withKind("ClusterRole").withName("strimzi-entity-operator").endRoleRef().withSubjects(new SubjectBuilder().withKind("ServiceAccount").withName("strimzi-cluster-operator").withNamespace(namespace).build()).build());
    return kCRBList;
}
Also used : ClusterRoleBindingBuilder(io.fabric8.kubernetes.api.model.rbac.ClusterRoleBindingBuilder) ClusterRoleBinding(io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding) ArrayList(java.util.ArrayList) SubjectBuilder(io.fabric8.kubernetes.api.model.rbac.SubjectBuilder)

Example 27 with ClusterRole

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

the class Main method maybeCreateClusterRoles.

/*test*/
static Future<Void> maybeCreateClusterRoles(Vertx vertx, ClusterOperatorConfig config, KubernetesClient client) {
    if (config.isCreateClusterRoles()) {
        List<Future> futures = new ArrayList<>();
        ClusterRoleOperator cro = new ClusterRoleOperator(vertx, client);
        Map<String, String> clusterRoles = new HashMap<>(6);
        clusterRoles.put("strimzi-cluster-operator-namespaced", "020-ClusterRole-strimzi-cluster-operator-role.yaml");
        clusterRoles.put("strimzi-cluster-operator-global", "021-ClusterRole-strimzi-cluster-operator-role.yaml");
        clusterRoles.put("strimzi-kafka-broker", "030-ClusterRole-strimzi-kafka-broker.yaml");
        clusterRoles.put("strimzi-entity-operator", "031-ClusterRole-strimzi-entity-operator.yaml");
        clusterRoles.put("strimzi-kafka-client", "033-ClusterRole-strimzi-kafka-client.yaml");
        for (Map.Entry<String, String> clusterRole : clusterRoles.entrySet()) {
            LOGGER.info("Creating cluster role {}", clusterRole.getKey());
            try (BufferedReader br = new BufferedReader(new InputStreamReader(Main.class.getResourceAsStream("/cluster-roles/" + clusterRole.getValue()), StandardCharsets.UTF_8))) {
                String yaml = br.lines().collect(Collectors.joining(System.lineSeparator()));
                ClusterRole role = ClusterRoleOperator.convertYamlToClusterRole(yaml);
                Future fut = cro.reconcile(new Reconciliation("start-cluster-operator", "Deployment", config.getOperatorNamespace(), "cluster-operator"), role.getMetadata().getName(), role);
                futures.add(fut);
            } catch (IOException e) {
                LOGGER.error("Failed to create Cluster Roles.", e);
                throw new RuntimeException(e);
            }
        }
        Promise<Void> returnPromise = Promise.promise();
        CompositeFuture.all(futures).onComplete(res -> {
            if (res.succeeded()) {
                returnPromise.complete();
            } else {
                returnPromise.fail("Failed to create Cluster Roles.");
            }
        });
        return returnPromise.future();
    } else {
        return Future.succeededFuture();
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) IOException(java.io.IOException) ClusterRole(io.fabric8.kubernetes.api.model.rbac.ClusterRole) ClusterRoleOperator(io.strimzi.operator.common.operator.resource.ClusterRoleOperator) Reconciliation(io.strimzi.operator.common.Reconciliation) BufferedReader(java.io.BufferedReader) CompositeFuture(io.vertx.core.CompositeFuture) Future(io.vertx.core.Future) HashMap(java.util.HashMap) Map(java.util.Map)

Example 28 with ClusterRole

use of io.fabric8.kubernetes.api.model.rbac.ClusterRole 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 29 with ClusterRole

use of io.fabric8.kubernetes.api.model.rbac.ClusterRole 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 30 with ClusterRole

use of io.fabric8.kubernetes.api.model.rbac.ClusterRole in project quarkus-operator-sdk by quarkiverse.

the class ManifestsProcessor method generateCSV.

@BuildStep
void generateCSV(CSVGenerationConfiguration configuration, OutputTargetBuildItem outputTarget, CSVMetadataBuildItem csvMetadata, BuildProducer<GeneratedCSVBuildItem> doneGeneratingCSV, GeneratedCRDInfoBuildItem generatedCustomResourcesDefinitions, List<GeneratedKubernetesResourceBuildItem> generatedKubernetesManifests, BuildProducer<GeneratedFileSystemResourceBuildItem> generatedCSVs) {
    if (configuration.generateCSV.orElse(false)) {
        try {
            final var outputDir = outputTarget.getOutputDirectory().resolve(MANIFESTS);
            final var serviceAccounts = new LinkedList<ServiceAccount>();
            final var clusterRoleBindings = new LinkedList<ClusterRoleBinding>();
            final var clusterRoles = new LinkedList<ClusterRole>();
            final var roleBindings = new LinkedList<RoleBinding>();
            final var roles = new LinkedList<Role>();
            final var deployments = new LinkedList<Deployment>();
            generatedKubernetesManifests.stream().filter(bi -> bi.getName().equals("kubernetes.yml")).findAny().ifPresent(bi -> {
                final var resources = Serialization.unmarshalAsList(new ByteArrayInputStream(bi.getContent()));
                resources.getItems().forEach(r -> {
                    if (r instanceof ServiceAccount) {
                        serviceAccounts.add((ServiceAccount) r);
                        return;
                    }
                    if (r instanceof ClusterRoleBinding) {
                        clusterRoleBindings.add((ClusterRoleBinding) r);
                        return;
                    }
                    if (r instanceof ClusterRole) {
                        clusterRoles.add((ClusterRole) r);
                        return;
                    }
                    if (r instanceof RoleBinding) {
                        roleBindings.add((RoleBinding) r);
                        return;
                    }
                    if (r instanceof Role) {
                        roles.add((Role) r);
                        return;
                    }
                    if (r instanceof Deployment) {
                        deployments.add((Deployment) r);
                        return;
                    }
                });
            });
            final var generated = ManifestsGenerator.prepareGeneration(csvMetadata.getAugmentedCustomResourceInfos(), csvMetadata.getCSVMetadata());
            generated.forEach(manifestBuilder -> {
                final var fileName = manifestBuilder.getFileName();
                try {
                    generatedCSVs.produce(new GeneratedFileSystemResourceBuildItem(Path.of(MANIFESTS, fileName).toString(), manifestBuilder.getYAMLData(serviceAccounts, clusterRoleBindings, clusterRoles, roleBindings, roles, deployments)));
                    log.infov("Generating CSV for {0} controller -> {1}", manifestBuilder.getControllerName(), outputDir.resolve(fileName));
                } catch (IOException e) {
                    log.errorv("Cannot generate CSV for {0}: {1}", manifestBuilder.getControllerName(), e.getMessage());
                }
            });
            // copy custom resources to the manifests folder
            generatedCustomResourcesDefinitions.getCRDGenerationInfo().getCrds().values().stream().flatMap(crds -> crds.values().stream()).forEach(crd -> {
                try {
                    FileUtils.copyFileToDirectory(new File(crd.getFilePath()), outputDir.toFile());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            doneGeneratingCSV.produce(new GeneratedCSVBuildItem());
        } catch (Exception e) {
            log.infov(e, "Couldn't generate CSV:");
        }
    }
}
Also used : ClusterRoleBinding(io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding) ClassUtils(io.quarkiverse.operatorsdk.common.ClassUtils) Logger(org.jboss.logging.Logger) DotName(org.jboss.jandex.DotName) Role(io.fabric8.kubernetes.api.model.rbac.Role) HashMap(java.util.HashMap) SharedCSVMetadata(io.quarkiverse.operatorsdk.csv.runtime.SharedCSVMetadata) ClassInfo(org.jboss.jandex.ClassInfo) CombinedIndexBuildItem(io.quarkus.deployment.builditem.CombinedIndexBuildItem) GeneratedCRDInfoBuildItem(io.quarkiverse.operatorsdk.deployment.GeneratedCRDInfoBuildItem) BuildProducer(io.quarkus.deployment.annotations.BuildProducer) GeneratedKubernetesResourceBuildItem(io.quarkus.kubernetes.spi.GeneratedKubernetesResourceBuildItem) RoleBinding(io.fabric8.kubernetes.api.model.rbac.RoleBinding) BuildStep(io.quarkus.deployment.annotations.BuildStep) ByteArrayInputStream(java.io.ByteArrayInputStream) ResourceInfo(io.quarkiverse.operatorsdk.common.ResourceInfo) ConfigurationUtils(io.quarkiverse.operatorsdk.common.ConfigurationUtils) LinkedList(java.util.LinkedList) Path(java.nio.file.Path) IndexView(org.jboss.jandex.IndexView) CSVGenerationConfiguration(io.quarkiverse.operatorsdk.csv.runtime.CSVGenerationConfiguration) AnnotationValue(org.jboss.jandex.AnnotationValue) CSVMetadata(io.quarkiverse.operatorsdk.csv.runtime.CSVMetadata) IOException(java.io.IOException) FileUtils(org.apache.commons.io.FileUtils) Serialization(io.dekorate.utils.Serialization) CSVMetadataHolder(io.quarkiverse.operatorsdk.csv.runtime.CSVMetadataHolder) ConfigurationServiceBuildItem(io.quarkiverse.operatorsdk.deployment.ConfigurationServiceBuildItem) File(java.io.File) List(java.util.List) OutputTargetBuildItem(io.quarkus.deployment.pkg.builditem.OutputTargetBuildItem) AnnotationInstance(org.jboss.jandex.AnnotationInstance) GeneratedFileSystemResourceBuildItem(io.quarkus.deployment.builditem.GeneratedFileSystemResourceBuildItem) ClusterRole(io.fabric8.kubernetes.api.model.rbac.ClusterRole) ALL_VERBS(io.quarkiverse.operatorsdk.deployment.AddClusterRolesDecorator.ALL_VERBS) Optional(java.util.Optional) ServiceAccount(io.fabric8.kubernetes.api.model.ServiceAccount) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) ServiceAccount(io.fabric8.kubernetes.api.model.ServiceAccount) ClusterRoleBinding(io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) IOException(java.io.IOException) LinkedList(java.util.LinkedList) ClusterRole(io.fabric8.kubernetes.api.model.rbac.ClusterRole) IOException(java.io.IOException) Role(io.fabric8.kubernetes.api.model.rbac.Role) ClusterRole(io.fabric8.kubernetes.api.model.rbac.ClusterRole) ByteArrayInputStream(java.io.ByteArrayInputStream) ClusterRoleBinding(io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding) RoleBinding(io.fabric8.kubernetes.api.model.rbac.RoleBinding) GeneratedFileSystemResourceBuildItem(io.quarkus.deployment.builditem.GeneratedFileSystemResourceBuildItem) File(java.io.File) BuildStep(io.quarkus.deployment.annotations.BuildStep)

Aggregations

ClusterRole (io.fabric8.kubernetes.api.model.rbac.ClusterRole)23 SubjectBuilder (io.fabric8.kubernetes.api.model.rbac.SubjectBuilder)20 ClusterRoleBinding (io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding)18 RoleRefBuilder (io.fabric8.kubernetes.api.model.rbac.RoleRefBuilder)18 ClusterRoleBindingBuilder (io.fabric8.kubernetes.api.model.rbac.ClusterRoleBindingBuilder)15 RoleRef (io.fabric8.kubernetes.api.model.rbac.RoleRef)14 Subject (io.fabric8.kubernetes.api.model.rbac.Subject)14 Test (org.junit.Test)11 IOException (java.io.IOException)10 RoleBindingBuilder (io.fabric8.kubernetes.api.model.rbac.RoleBindingBuilder)7 ArrayList (java.util.ArrayList)7 HashMap (java.util.HashMap)7 List (java.util.List)7 Map (java.util.Map)7 ServiceAccount (io.fabric8.kubernetes.api.model.ServiceAccount)6 ServiceAccountBuilder (io.fabric8.kubernetes.api.model.ServiceAccountBuilder)6 Role (io.fabric8.kubernetes.api.model.rbac.Role)6 ClusterRoleBuilder (io.fabric8.kubernetes.api.model.rbac.ClusterRoleBuilder)5 EnvVar (io.fabric8.kubernetes.api.model.EnvVar)4 File (java.io.File)4