Search in sources :

Example 36 with RoleBinding

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

the class AddRoleBindingsDecorator method visit.

@Override
public void visit(KubernetesListBuilder list) {
    final var serviceAccountName = getMandatoryDeploymentMetadata(list).getName();
    for (Entry<String, QuarkusControllerConfiguration> entry : configs.entrySet()) {
        String controllerName = entry.getKey();
        QuarkusControllerConfiguration config = entry.getValue();
        if (config.watchCurrentNamespace()) {
            // create a RoleBinding that will be applied in the current namespace if watching only the current NS
            list.addToItems(new RoleBindingBuilder().withNewMetadata().withName(controllerName + "-role-binding").endMetadata().withNewRoleRef(RBAC_AUTHORIZATION_GROUP, CLUSTER_ROLE, getClusterRoleName(controllerName)).addNewSubject(null, SERVICE_ACCOUNT, serviceAccountName, null).build());
        } else if (config.watchAllNamespaces()) {
            handleClusterRoleBinding(list, serviceAccountName, controllerName, controllerName + "-cluster-role-binding", "watch all namespaces", getClusterRoleName(controllerName));
        } else {
            config.getEffectiveNamespaces().forEach(ns -> list.addToItems(new RoleBindingBuilder().withNewMetadata().withName(controllerName + "-role-binding").withNamespace((String) ns).endMetadata().withNewRoleRef(RBAC_AUTHORIZATION_GROUP, CLUSTER_ROLE, getClusterRoleName(controllerName)).addNewSubject(null, SERVICE_ACCOUNT, serviceAccountName, null).build()));
        }
        // if we validate the CRDs, also create a binding for the CRD validating role
        if (validateCRDs) {
            final var crBindingName = controllerName + "-crd-validating-role-binding";
            handleClusterRoleBinding(list, serviceAccountName, controllerName, crBindingName, "validate CRDs", AddClusterRolesDecorator.JOSDK_CRD_VALIDATING_CLUSTER_ROLE);
        }
    }
}
Also used : AddClusterRolesDecorator.getClusterRoleName(io.quarkiverse.operatorsdk.deployment.AddClusterRolesDecorator.getClusterRoleName) ResourceProvidingDecorator(io.dekorate.kubernetes.decorator.ResourceProvidingDecorator) KubernetesListBuilder(io.fabric8.kubernetes.api.model.KubernetesListBuilder) RoleBindingBuilder(io.fabric8.kubernetes.api.model.rbac.RoleBindingBuilder) ConfigProvider(org.eclipse.microprofile.config.ConfigProvider) Map(java.util.Map) Entry(java.util.Map.Entry) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Optional(java.util.Optional) QuarkusControllerConfiguration(io.quarkiverse.operatorsdk.runtime.QuarkusControllerConfiguration) ClusterRoleBindingBuilder(io.fabric8.kubernetes.api.model.rbac.ClusterRoleBindingBuilder) ConcurrentMap(java.util.concurrent.ConcurrentMap) RoleBindingBuilder(io.fabric8.kubernetes.api.model.rbac.RoleBindingBuilder) ClusterRoleBindingBuilder(io.fabric8.kubernetes.api.model.rbac.ClusterRoleBindingBuilder) QuarkusControllerConfiguration(io.quarkiverse.operatorsdk.runtime.QuarkusControllerConfiguration)

Example 37 with RoleBinding

use of io.fabric8.kubernetes.api.model.rbac.RoleBinding 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)

Example 38 with RoleBinding

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

the class CsvManifestsBuilder method handlePermissions.

private void handlePermissions(List<ClusterRole> clusterRoles, List<RoleBinding> roleBindings, List<Role> roles, String defaultServiceAccountName, NamedInstallStrategyFluent.SpecNested<ClusterServiceVersionSpecFluent.InstallNested<ClusterServiceVersionFluent.SpecNested<ClusterServiceVersionBuilder>>> installSpec) {
    Map<String, List<PolicyRule>> customPermissionRules = new HashMap<>();
    if (metadata.permissionRules != null) {
        for (CSVMetadataHolder.PermissionRule permissionRule : metadata.permissionRules) {
            String serviceAccountName = StringUtils.defaultIfEmpty(permissionRule.serviceAccountName, defaultServiceAccountName);
            List<PolicyRule> customRulesByServiceAccount = customPermissionRules.get(serviceAccountName);
            if (customRulesByServiceAccount == null) {
                customRulesByServiceAccount = new LinkedList<>();
                customPermissionRules.put(serviceAccountName, customRulesByServiceAccount);
            }
            customRulesByServiceAccount.add(new PolicyRuleBuilder().addAllToApiGroups(Arrays.asList(permissionRule.apiGroups)).addAllToResources(Arrays.asList(permissionRule.resources)).addAllToVerbs(Arrays.asList(permissionRule.verbs)).build());
        }
    }
    for (RoleBinding binding : roleBindings) {
        String serviceAccountName = findServiceAccountFromSubjects(binding.getSubjects(), defaultServiceAccountName);
        if (NO_SERVICE_ACCOUNT.equals(serviceAccountName)) {
            LOGGER.warnf("Role '%s' was not added because the service account is missing", binding.getRoleRef().getName());
            continue;
        }
        List<PolicyRule> rules = new LinkedList<>();
        rules.addAll(findRules(binding.getRoleRef(), clusterRoles, roles));
        Optional.ofNullable(customPermissionRules.remove(serviceAccountName)).ifPresent(rules::addAll);
        handlerPermission(rules, serviceAccountName, installSpec);
    }
}
Also used : PolicyRule(io.fabric8.kubernetes.api.model.rbac.PolicyRule) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) PolicyRuleBuilder(io.fabric8.kubernetes.api.model.rbac.PolicyRuleBuilder) LinkedList(java.util.LinkedList) CSVMetadataHolder(io.quarkiverse.operatorsdk.csv.runtime.CSVMetadataHolder) LinkedList(java.util.LinkedList) List(java.util.List) ClusterRoleBinding(io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding) RoleBinding(io.fabric8.kubernetes.api.model.rbac.RoleBinding)

Example 39 with RoleBinding

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

the class Controller method applyRoleBinding.

public void applyRoleBinding(RoleBinding entity, String sourceName) {
    OpenShiftClient openShiftClient = getOpenShiftClientOrJenkinshift();
    if (openShiftClient != null) {
        String id = getName(entity);
        Objects.notNull(id, "No name for " + entity + " " + sourceName);
        String namespace = KubernetesHelper.getNamespace(entity);
        if (Strings.isNullOrBlank(namespace)) {
            namespace = getNamespace();
        }
        applyNamespace(namespace);
        RoleBinding old = openShiftClient.roleBindings().inNamespace(namespace).withName(id).get();
        if (isRunning(old)) {
            if (UserConfigurationCompare.configEqual(entity, old)) {
                LOG.info("RoleBinding has not changed so not doing anything");
            } else {
                if (isRecreateMode()) {
                    LOG.info("Deleting RoleBinding: " + id);
                    openShiftClient.roleBindings().inNamespace(namespace).withName(id).delete();
                    doCreateRoleBinding(entity, namespace, sourceName);
                } else {
                    LOG.info("Updating RoleBinding from " + sourceName);
                    try {
                        String resourceVersion = KubernetesHelper.getResourceVersion(old);
                        ObjectMeta metadata = KubernetesHelper.getOrCreateMetadata(entity);
                        metadata.setNamespace(namespace);
                        metadata.setResourceVersion(resourceVersion);
                        Object answer = openShiftClient.roleBindings().inNamespace(namespace).withName(id).replace(entity);
                        logGeneratedEntity("Updated RoleBinding: ", namespace, entity, answer);
                    } catch (Exception e) {
                        onApplyError("Failed to update RoleBinding from " + sourceName + ". " + e + ". " + entity, e);
                    }
                }
            }
        } else {
            if (!isAllowCreate()) {
                LOG.warn("Creation disabled so not creating RoleBinding from " + sourceName + " namespace " + namespace + " name " + getName(entity));
            } else {
                doCreateRoleBinding(entity, namespace, sourceName);
            }
        }
    }
}
Also used : ObjectMeta(io.fabric8.kubernetes.api.model.ObjectMeta) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) JSONObject(org.json.JSONObject) RoleBinding(io.fabric8.openshift.api.model.RoleBinding) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) FileNotFoundException(java.io.FileNotFoundException) OpenShiftNotAvailableException(io.fabric8.openshift.client.OpenShiftNotAvailableException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException)

Example 40 with RoleBinding

use of io.fabric8.kubernetes.api.model.rbac.RoleBinding in project jointware by isdream.

the class KubernetesKeyValueStyleGeneratorTest method testOpenShiftWithAllKind.

protected static void testOpenShiftWithAllKind() throws Exception {
    info(OPENSHIFT_KIND, OpenShiftDocumentKeyValueStyleGenerator.class.getName(), new Policy());
    info(OPENSHIFT_KIND, OpenShiftDocumentKeyValueStyleGenerator.class.getName(), new Group());
    info(OPENSHIFT_KIND, OpenShiftDocumentKeyValueStyleGenerator.class.getName(), new User());
    info(OPENSHIFT_KIND, OpenShiftDocumentKeyValueStyleGenerator.class.getName(), new OAuthClient());
    info(OPENSHIFT_KIND, OpenShiftDocumentKeyValueStyleGenerator.class.getName(), new ClusterRoleBinding());
    info(OPENSHIFT_KIND, OpenShiftDocumentKeyValueStyleGenerator.class.getName(), new ImageStreamTag());
    info(OPENSHIFT_KIND, OpenShiftDocumentKeyValueStyleGenerator.class.getName(), new ImageStream());
    info(OPENSHIFT_KIND, OpenShiftDocumentKeyValueStyleGenerator.class.getName(), new Build());
    info(OPENSHIFT_KIND, OpenShiftDocumentKeyValueStyleGenerator.class.getName(), new BuildConfig());
    info(OPENSHIFT_KIND, OpenShiftDocumentKeyValueStyleGenerator.class.getName(), new RoleBinding());
    info(OPENSHIFT_KIND, OpenShiftDocumentKeyValueStyleGenerator.class.getName(), new Route());
    info(OPENSHIFT_KIND, OpenShiftDocumentKeyValueStyleGenerator.class.getName(), new PolicyBinding());
    info(OPENSHIFT_KIND, OpenShiftDocumentKeyValueStyleGenerator.class.getName(), new OAuthAuthorizeToken());
    info(OPENSHIFT_KIND, OpenShiftDocumentKeyValueStyleGenerator.class.getName(), new Role());
    info(OPENSHIFT_KIND, OpenShiftDocumentKeyValueStyleGenerator.class.getName(), new Project());
    info(OPENSHIFT_KIND, OpenShiftDocumentKeyValueStyleGenerator.class.getName(), new OAuthAccessToken());
    info(OPENSHIFT_KIND, OpenShiftDocumentKeyValueStyleGenerator.class.getName(), new DeploymentConfig());
}
Also used : NetworkPolicy(io.fabric8.kubernetes.api.model.extensions.NetworkPolicy) Policy(io.fabric8.openshift.api.model.Policy) Group(io.fabric8.openshift.api.model.Group) User(io.fabric8.openshift.api.model.User) OAuthClient(io.fabric8.openshift.api.model.OAuthClient) ClusterRoleBinding(io.fabric8.openshift.api.model.ClusterRoleBinding) ImageStreamTag(io.fabric8.openshift.api.model.ImageStreamTag) ImageStream(io.fabric8.openshift.api.model.ImageStream) PolicyBinding(io.fabric8.openshift.api.model.PolicyBinding) OAuthAuthorizeToken(io.fabric8.openshift.api.model.OAuthAuthorizeToken) Role(io.fabric8.openshift.api.model.Role) Project(io.fabric8.openshift.api.model.Project) Build(io.fabric8.openshift.api.model.Build) OpenShiftDocumentKeyValueStyleGenerator(com.github.isdream.chameleon.docs.OpenShiftDocumentKeyValueStyleGenerator) BuildConfig(io.fabric8.openshift.api.model.BuildConfig) OAuthAccessToken(io.fabric8.openshift.api.model.OAuthAccessToken) ClusterRoleBinding(io.fabric8.openshift.api.model.ClusterRoleBinding) RoleBinding(io.fabric8.openshift.api.model.RoleBinding) DeploymentConfig(io.fabric8.openshift.api.model.DeploymentConfig) Route(io.fabric8.openshift.api.model.Route)

Aggregations

RoleBinding (io.fabric8.kubernetes.api.model.rbac.RoleBinding)33 RoleRefBuilder (io.fabric8.kubernetes.api.model.rbac.RoleRefBuilder)20 RoleBinding (io.fabric8.openshift.api.model.RoleBinding)19 Test (org.junit.jupiter.api.Test)19 RoleBindingBuilder (io.fabric8.kubernetes.api.model.rbac.RoleBindingBuilder)16 RoleRef (io.fabric8.kubernetes.api.model.rbac.RoleRef)16 SubjectBuilder (io.fabric8.kubernetes.api.model.rbac.SubjectBuilder)14 RoleBindingBuilder (io.fabric8.openshift.api.model.RoleBindingBuilder)13 Role (io.fabric8.kubernetes.api.model.rbac.Role)10 Subject (io.fabric8.kubernetes.api.model.rbac.Subject)10 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)10 OpenShiftClient (io.fabric8.openshift.client.OpenShiftClient)10 List (java.util.List)8 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)6 ServiceAccount (io.fabric8.kubernetes.api.model.ServiceAccount)6 Kafka (io.strimzi.api.kafka.model.Kafka)6 KafkaBuilder (io.strimzi.api.kafka.model.KafkaBuilder)6 CertManager (io.strimzi.certs.CertManager)6 KubernetesVersion (io.strimzi.operator.KubernetesVersion)6 PlatformFeaturesAvailability (io.strimzi.operator.PlatformFeaturesAvailability)6