Skip to content

Commit

Permalink
Merge pull request #9 from flanksource/refactor-2
Browse files Browse the repository at this point in the history
refactor: remove in-place global obj changes
  • Loading branch information
moshloop committed Aug 31, 2023
2 parents 497ea5d + 7ddaa4a commit 0597b28
Show file tree
Hide file tree
Showing 9 changed files with 96 additions and 66 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1 @@
Tenant Controller
# Tenant Controller
1 change: 1 addition & 0 deletions cmd/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ func serve(configFile string) {
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: allowedCors,
}))
e.Use(middleware.Logger())

if debug {
logger.Infof("Starting pprof at /debug")
Expand Down
13 changes: 0 additions & 13 deletions deploy/cm.yml

This file was deleted.

7 changes: 4 additions & 3 deletions deploy/configmap.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ kind: ConfigMap
metadata:
name: tenant-controller
data:
config.yaml: |
key: some-arn
config.yml: |
aws:
key: some-arn
azure:
tenant_id: <TENANT_ID>
client_secret: <CLIENT_SECRET>
Expand All @@ -13,8 +14,8 @@ data:
git:
repository: https://github.com/flanksource/aws-sandbox
user: flankbot
base: main
pull_request:
base: main
assignees:
- Kaitou786
reviewers:
Expand Down
6 changes: 4 additions & 2 deletions deploy/deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@ spec:
spec:
containers:
- name: tenant-controller
image: docker.io/flanksource/tenant-controller:v0.0.0
image: docker.io/flanksource/tenant-controller:v1.0.2
command:
- /app/tenant-controller
args:
- -c config.yml
- serve
- -c
- /app/config.yml
volumeMounts:
- name: config-volume
mountPath: /app/config.yml
Expand Down
19 changes: 15 additions & 4 deletions pkg/api/tenant.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"net/http"

"github.com/flanksource/commons/logger"
"github.com/flanksource/tenant-controller/pkg"
"github.com/flanksource/tenant-controller/pkg/git"
"github.com/flanksource/tenant-controller/pkg/secrets"
Expand All @@ -18,11 +19,21 @@ func CreateTenant(c echo.Context) error {
}
defer c.Request().Body.Close()

var tenant *pkg.Tenant
if err := c.Bind(tenant); err != nil {
var reqBody pkg.TenantRequestBody
if err := c.Bind(&reqBody); err != nil {
logger.Infof("Broken %v", err)
return errorResonse(c, err, http.StatusBadRequest)
}

t, err := pkg.NewTenant(reqBody)
if err != nil {
return errorResonse(c, err, http.StatusBadRequest)
}

// TODO: Pointer ref should not be required
// remove places with side-effects
tenant := &t

if tenant.Slug == "" {
tenant.Slug = slug.Make(tenant.Name)
}
Expand All @@ -35,10 +46,10 @@ func CreateTenant(c echo.Context) error {
Password: tenant.GenerateDBPassword(),
})
if err != nil {
return errorResonse(c, err, http.StatusInternalServerError)
return errorResonse(c, fmt.Errorf("Error generating sealed secret: %s %v", string(sealedSecretRaw), err), http.StatusInternalServerError)
}

objs, err := pkg.GetTenantResources(tenant.Slug, sealedSecretRaw)
objs, err := pkg.GetTenantResources(tenant.Slug, string(sealedSecretRaw))
if err != nil {
return errorResonse(c, err, http.StatusInternalServerError)
}
Expand Down
27 changes: 3 additions & 24 deletions pkg/git/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"context"
"fmt"
"io"
"path"
"path/filepath"
"strings"
"time"
Expand Down Expand Up @@ -82,12 +81,10 @@ func CreateTenantResources(connector connectors.Connector, tenant *pkg.Tenant, t
if err != nil {
return
}
// path at which tenant resources will be stored
contentsPath := getContentsPath(tenant)

// add tenant resources to git
for _, obj := range tenantObjs {
contentPath := filepath.Join(contentsPath, strings.ToLower(obj.GetKind())+".yaml")
contentPath := filepath.Join(tenant.ContentPath, strings.ToLower(obj.GetKind())+".yaml")
body, err := yaml.Marshal(obj.Object)
if err != nil {
return nil, "", err
Expand All @@ -97,7 +94,7 @@ func CreateTenantResources(connector connectors.Connector, tenant *pkg.Tenant, t
}
}
// update root kustomization and add tenant kustomization to it
kustomization, err := getKustomizaton(fs, pkg.Config.Git.KustomizationPath)
kustomization, err := getKustomizaton(fs, tenant.KustomizationPath)
if err != nil {
return nil, "", err
}
Expand All @@ -109,7 +106,7 @@ func CreateTenantResources(connector connectors.Connector, tenant *pkg.Tenant, t
if err != nil {
return nil, "", err
}
if err = writeGitWorkTree(existingKustomization, pkg.Config.Git.KustomizationPath, fs, work); err != nil {
if err = writeGitWorkTree(existingKustomization, tenant.KustomizationPath, fs, work); err != nil {
return nil, "", err
}
return
Expand Down Expand Up @@ -139,24 +136,6 @@ func CreateCommit(work *gitv5.Worktree, title string) (hash string, err error) {
return
}

func getContentsPath(tenant *pkg.Tenant) string {
pkg.Config.Git.KustomizationPath, _ = pkg.Template(pkg.Config.Git.KustomizationPath, map[string]interface{}{
"cluster": getClusterName(tenant),
})
return path.Dir(pkg.Config.Git.KustomizationPath) + "/" + tenant.Slug
}

func getClusterName(tenant *pkg.Tenant) string {
// TODO: Take this from config
switch tenant.Cloud {
case pkg.Azure:
return "azure-internal-prod"
case pkg.AWS:
return "aws-demo"
}
return ""
}

func writeGitWorkTree(data []byte, path string, fs billy.Filesystem, work *gitv5.Worktree) error {
dst, err := openOrCreate(path, fs)
if err != nil {
Expand Down
32 changes: 19 additions & 13 deletions pkg/tenant.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,37 +33,43 @@ spec:
- --tls-san={{.tenant}}.{{.tenant}}.svc
- --out-kube-config-server=https://{{.tenant}}.{{.tenant}}.svc
missionControl:
authProvider: clerk
flanksource-ui:
oryKratosURL: https://{{.tenant}}.internal-prod.flanksource.com/api/.ory
enabled: false
db:
# We are creating our own secrets
create: false
`

NAMESPACE_TEMPLATE = `apiVersion: v1
NAMESPACE_TEMPLATE = `
apiVersion: v1
kind: Namespace
metadata:
name: {{.tenant}}`
name: {{.tenant}}
`

KUSTOMIZATION_RAW = `apiVersion: kustomize.config.k8s.io/v1beta1
KUSTOMIZATION_RAW = `
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- namespace.yaml
- helmrelease.yaml
- secret.yaml`
- secret.yaml
`
)

func GetTenantResources(tenantSlug string, sealedSecretResource []byte) (obj []*unstructured.Unstructured, err error) {
helmReleaseRaw, err := Template(HELM_RELEASE_TEMPLATE, map[string]interface{}{
func GetTenantResources(tenantSlug, sealedSecret string) (obj []*unstructured.Unstructured, err error) {
vars := map[string]any{
"tenant": tenantSlug,
})
}
helmReleaseRaw, err := Template(HELM_RELEASE_TEMPLATE, vars)
if err != nil {
return nil, err
}
namespaceRaw, err := Template(NAMESPACE_TEMPLATE, map[string]interface{}{
"tenant": tenantSlug,
})
namespaceRaw, err := Template(NAMESPACE_TEMPLATE, vars)
if err != nil {
return nil, err
}
sealedSecretRaw := string(sealedSecretResource)

return GetUnstructuredObjects(namespaceRaw, sealedSecretRaw, KUSTOMIZATION_RAW, helmReleaseRaw)
return GetUnstructuredObjects(namespaceRaw, sealedSecret, KUSTOMIZATION_RAW, helmReleaseRaw)
}
55 changes: 49 additions & 6 deletions pkg/tenant_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ package pkg
import (
"fmt"
"math/rand"
"path"
"strings"

v1 "github.com/flanksource/tenant-controller/api/v1"
)

type CloudProvider string
Expand All @@ -15,18 +14,51 @@ const (
Azure CloudProvider = "azure"
)

type TenantRequestBody struct {
Name string `json:"name"`
Cloud CloudProvider `json:"cloud"`
Slug string `json:"slug,omitempty"`
}

type Tenant struct {
Name string `json:"name"`
Cloud CloudProvider `json:"cloud"`
Slug string `json:"slug,omitempty"`
Azure v1.AzureConfig `json:"-"`
Name string `json:"name"`
Cloud CloudProvider `json:"cloud"`
Slug string `json:"slug,omitempty"`

// Not sure why this was added
// But commenting out since it is not in use
//Azure v1.AzureConfig `json:"-"`

KustomizationPath string `json:"kustomizationPath"`

// ContentPath is where all the tenant resources will be stored
ContentPath string `json:"contentPath"`
}

type DBCredentials struct {
Username string `json:"username"`
Password string `json:"password"`
}

func NewTenant(t TenantRequestBody) (Tenant, error) {
kPath, err := Template(Config.Git.KustomizationPath, map[string]any{
"cluster": getClusterName(t.Cloud),
})
if err != nil {
return Tenant{}, err
}

contentPath := path.Join(path.Dir(kPath), t.Slug)

return Tenant{
Name: t.Name,
Cloud: t.Cloud,
Slug: t.Slug,
KustomizationPath: kPath,
ContentPath: contentPath,
}, nil
}

func (tenant Tenant) GenerateDBUsername() string {
return fmt.Sprintf("%s_%d", strings.ToLower(tenant.Slug), rand.Intn(1000))
}
Expand All @@ -45,3 +77,14 @@ func generateRandomPassword() string {
}
return string(password)
}

func getClusterName(cloud CloudProvider) string {
// TODO: Take this from config
switch cloud {
case Azure:
return "azure-internal-prod"
case AWS:
return "aws-demo"
}
return ""
}

0 comments on commit 0597b28

Please sign in to comment.