Skip to content

Commit

Permalink
Merge pull request #64 from RHEcosystemAppEng/50-move-exporter-code-i…
Browse files Browse the repository at this point in the history
…nto-crane

50 move exporter code into crane
  • Loading branch information
IlonaShishov authored Mar 9, 2023
2 parents a36b832 + bb2b157 commit e59ba31
Show file tree
Hide file tree
Showing 4 changed files with 6 additions and 253 deletions.
7 changes: 3 additions & 4 deletions exporter/pkg/export/app/appexporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,13 @@ func NewAppExporterFromConfig(config *config.Config, connectionStatus *connect.C
}

func (e *AppExporter) Export() {
clusterRolesInspector := NewClusterRolesInspector(e.appContext)
clusterRolesInspector.LoadClusterRoles()

e.PrepareOutput()
e.ExportWithCrane()

parametrizer := NewParametrizerFromConfig(e.appContext)
parametrizer.ExposeParameters()

installer := NewInstallerFromConfig(e.appContext, clusterRolesInspector)
installer := NewInstallerFromConfig(e.appContext)
installer.BuildKustomizeInstaller()
}

Expand Down Expand Up @@ -79,6 +76,8 @@ func doExport(kubeConfigPath string, namespace string, exportFolder string) {
ErrOut: os.Stderr,
}, nil)

clusterScopedRbac := exportCmd.Flags().Lookup("cluster-scoped-rbac")
clusterScopedRbac.Value.Set("true")
exportNamespace := exportCmd.Flags().Lookup("namespace")
exportNamespace.Value.Set(namespace)
exportDir := exportCmd.Flags().Lookup("export-dir")
Expand Down
97 changes: 0 additions & 97 deletions exporter/pkg/export/app/clusterroles.go

This file was deleted.

116 changes: 3 additions & 113 deletions exporter/pkg/export/app/installer.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,16 @@ package app
import (
"fmt"
"io/fs"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"

"github.com/RHEcosystemAppEng/SaaSi/exporter/pkg/export/utils"
v1 "k8s.io/api/core/v1"
rbacV1 "k8s.io/api/rbac/v1"
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/cli-runtime/pkg/printers"
"k8s.io/client-go/kubernetes/scheme"
)

type Installer struct {
appContext *AppContext
clusterRolesInspector *ClusterRolesInspector
appContext *AppContext

sccToBeReplacedByNS map[string][]SccForSA
}
Expand All @@ -29,8 +22,8 @@ type SccForSA struct {
sccName string
}

func NewInstallerFromConfig(appContext *AppContext, clusterRolesInspector *ClusterRolesInspector) *Installer {
installer := Installer{appContext: appContext, clusterRolesInspector: clusterRolesInspector}
func NewInstallerFromConfig(appContext *AppContext) *Installer {
installer := Installer{appContext: appContext}

installer.sccToBeReplacedByNS = make(map[string][]SccForSA)
return &installer
Expand All @@ -51,19 +44,6 @@ func (i *Installer) BuildKustomizeInstaller() {
return e
}
if !d.IsDir() && filepath.Ext(d.Name()) == ".yaml" {
yfile, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal(err)
}
decode := scheme.Codecs.UniversalDeserializer().Decode
obj, gKV, err := decode(yfile, nil, nil)
if err == nil {
if gKV.Kind == "ServiceAccount" {
serviceAccount := obj.(*v1.ServiceAccount)
i.handleServiceAccount(kustomization, ns.Name, serviceAccount)
}
}

// log.Printf("Moving %s to %s", d.Name(), kustomizeFolder)
os.Rename(path, filepath.Join(kustomizeFolder, d.Name()))
utils.AppendToFile(kustomization, fmt.Sprintf("\n - %s", d.Name()))
Expand Down Expand Up @@ -161,94 +141,4 @@ func (i *Installer) createKustomizeTemplate() {
}
}
}

}

func (i *Installer) handleServiceAccount(kustomization string, namespace string, serviceAccount *v1.ServiceAccount) {
log.Printf("Handling ServiceAccount %s", serviceAccount.Name)

clusterRoleBindings := i.clusterRolesInspector.ClusterRoleBindingsForSA(namespace, serviceAccount.Name)

for _, clusterRoleBinding := range clusterRoleBindings {
// TODO: update CRB name
yamlFile := fmt.Sprintf("%s-%s.yaml", "ClusterRoleBinding", clusterRoleBinding.Name)
yamlPath := filepath.Join(i.appContext.BaseKustomizeFolderForNS(namespace), yamlFile)

clusterRoleBindingSpec := rbacV1.ClusterRoleBinding{
// TODO: These two are not collected by client-go API
TypeMeta: metaV1.TypeMeta{
APIVersion: "rbac.authorization.k8s.io/v1",
Kind: "ClusterRoleBinding",
},
ObjectMeta: metaV1.ObjectMeta{
Name: clusterRoleBinding.Name,
},
RoleRef: rbacV1.RoleRef{
Kind: clusterRoleBinding.RoleRef.Kind,
Name: clusterRoleBinding.RoleRef.Name,
// Do not copy the original namespace, will be overriden at install time
},
// TODO: API Group
Subjects: []rbacV1.Subject{},
}
for _, subject := range clusterRoleBinding.Subjects {
clusterRoleBindingSpec.Subjects = append(clusterRoleBindingSpec.Subjects, rbacV1.Subject{
Kind: subject.Kind,
Name: subject.Name,
Namespace: subject.Namespace,
})
// TODO: API Group
}

log.Printf("Creating YAML %s for ClusterRoleBinding %s to assign role %s to ServiceAccount %s", yamlFile,
clusterRoleBindingSpec.Name, clusterRoleBindingSpec.RoleRef.Name, serviceAccount.Name)
newFile, err := os.Create(yamlPath)
if err != nil {
log.Fatal(err)
}
y := printers.YAMLPrinter{}
defer newFile.Close()
if err = y.PrintObj(&clusterRoleBindingSpec, newFile); err != nil {
log.Fatal(err)
}

utils.AppendToFile(kustomization, fmt.Sprintf("\n - %s", yamlFile))
}

sccs := i.clusterRolesInspector.SecurityContextConstraintsForSA(namespace, serviceAccount.Name)
systemName := utils.SystemNameForSA(namespace, serviceAccount.Name)
for _, scc := range sccs {
// Temporary solution
// Create a copy of the original SCC, rename it top match the SA and connect to this SA only
// Final solution is:
// 1- to avoid such cases and use CRB and SCC instead
// 2- to avoid such cases and use CRB and CR instead
sccCopy := scc.DeepCopy()
sccCopy.Name = fmt.Sprintf("%s-%s", scc.Name, serviceAccount.Name)
sccCopy.Users = []string{systemName}

yamlFile := fmt.Sprintf("%s-%s.yaml", "SecurityContextConstraints", sccCopy.Name)
yamlPath := filepath.Join(i.appContext.BaseKustomizeFolderForNS(namespace), yamlFile)

log.Printf("Creating YAML %s for SecurityContextConstraints %s to assign to ServiceAccount %s", yamlFile,
sccCopy.Name, serviceAccount.Name)
newFile, err := os.Create(yamlPath)
if err != nil {
log.Fatal(err)
}
y := printers.YAMLPrinter{}
defer newFile.Close()
if err = y.PrintObj(sccCopy, newFile); err != nil {
log.Fatal(err)
}

utils.AppendToFile(kustomization, fmt.Sprintf("\n - %s", yamlFile))

sccForSA := SccForSA{serviceAccountName: serviceAccount.Name, sccName: sccCopy.Name}
if sccsForSA, ok := i.sccToBeReplacedByNS[namespace]; ok {
sccsForSA = append(sccsForSA, sccForSA)
} else {
i.sccToBeReplacedByNS[namespace] = []SccForSA{sccForSA}
}
}
}
39 changes: 0 additions & 39 deletions exporter/pkg/export/app/parametrizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,12 @@ import (
"log"
"os"
"path/filepath"
"reflect"

api "github.com/openshift/api"

"github.com/RHEcosystemAppEng/SaaSi/exporter/pkg/export/utils"
"golang.org/x/exp/slices"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/cli-runtime/pkg/printers"
"k8s.io/client-go/kubernetes/scheme"
)

Expand Down Expand Up @@ -64,40 +61,12 @@ func (p *Parametrizer) ExposeParameters() {
} else if gKV.Kind == "Secret" {
secret := obj.(*v1.Secret)
p.handleSecret(yamlFile, secret)
} else {
p.resetNamespace(obj, yamlFile)
}
}
}
}
}

func (*Parametrizer) resetNamespace(obj runtime.Object, yamlFile string) {
value := reflect.Indirect(reflect.ValueOf(obj))
ns := value.FieldByName("Namespace")
name := value.FieldByName("Name").String()
kind := value.FieldByName("Kind").String()
// log.Printf("yamlFile is %s", yamlFile)
// log.Printf("ns is %+v", ns)
if !ns.IsZero() {
namespace := reflect.Indirect(ns).String()

log.Printf("Resetting namespace %s at %s/%s", namespace, kind, name)
ns.SetString("")

os.Rename(yamlFile, utils.BackupFile(yamlFile))
newFile, err := os.Create(yamlFile)
if err != nil {
log.Fatal(err)
}
y := printers.YAMLPrinter{}
defer newFile.Close()
y.PrintObj(obj, newFile)
} else {
log.Printf("Found not namespaced resource %s/%s", kind, name)
}
}

func (p *Parametrizer) handleConfigMap(configMapFile string, configMap *v1.ConfigMap) {
log.Printf("Handling ConfigMap %s", configMap.Name)
tmpParamsFolder := p.appContext.TmpParamsFolderForNS(configMap.Namespace)
Expand All @@ -113,7 +82,6 @@ func (p *Parametrizer) handleConfigMap(configMapFile string, configMap *v1.Confi
} else {
utils.AppendToFile(templateFile, fmt.Sprintf("#%s=%s\n", key, NoValue))
}

}

for _, mandatoryParam := range mandatoryParams {
Expand All @@ -124,7 +92,6 @@ func (p *Parametrizer) handleConfigMap(configMapFile string, configMap *v1.Confi
log.Fatalf("The mandatory parameter %s for ConfigMap %s does not exist", mandatoryParam, configMap.Name)
}
}
p.resetNamespace(configMap, configMapFile)
// os.Rename(configMapFile, BackupFile(configMapFile))
}

Expand All @@ -140,11 +107,5 @@ func (p *Parametrizer) handleSecret(secretFile string, secret *v1.Secret) {
utils.AppendToFile(secretsFile, fmt.Sprintf("%s=%s\n", key, MandatoryValue))
}
os.Rename(secretFile, utils.BackupFile(secretFile))
} else if secret.Type == "kubernetes.io/dockerconfigjson" {
log.Printf("Keeping kubernetes.io/dockerconfigjson Secret %s", secret.Name)
p.resetNamespace(secret, secretFile)
} else {
log.Printf("Removing unmanaged Secret %s", secret.Name)
os.Rename(secretFile, utils.BackupFile(secretFile))
}
}

0 comments on commit e59ba31

Please sign in to comment.