Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions cmd/grus/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ type config struct {
AdminToken string
ProcessDir string
ReconcileInterval time.Duration
CRDs bool
}

// loadConfig parses args (the controller flags) on top of the environment read through getenv.
Expand Down Expand Up @@ -72,6 +73,7 @@ func loadConfig(args []string, getenv func(string) string) (config, error) {
debugEndpoints := str("debug-endpoints", "GRUS_DEBUG_ENDPOINTS", "false", "enable the admin debug endpoints (true/false)")
hostID := str("host-id", "GRUS_HOST_ID", "", "host id; default k8s-<namespace> or local")
processDir := str("process-dir", "GRUS_PROCESS_DIR", "./instances", "working directories of the process driver")
crds := str("crds", "GRUS_CRDS", "false", "watch the Grus custom resources of the namespace (true/false)")
interval := str("reconcile-interval", "GRUS_RECONCILE_INTERVAL", "5s", "reconcile interval")

if err := fs.Parse(args); err != nil {
Expand Down Expand Up @@ -119,6 +121,9 @@ func loadConfig(args []string, getenv func(string) string) (config, error) {
if cfg.ReconcileInterval, err = time.ParseDuration(*interval); err != nil {
return config{}, fmt.Errorf("GRUS_RECONCILE_INTERVAL: %w", err)
}
if cfg.CRDs, err = strconv.ParseBool(*crds); err != nil {
return config{}, fmt.Errorf("GRUS_CRDS: %w", err)
}
if cfg.S3Insecure, err = strconv.ParseBool(*s3Insecure); err != nil {
return config{}, fmt.Errorf("GRUS_S3_INSECURE: %w", err)
}
Expand All @@ -145,6 +150,9 @@ func (c config) validate() error {
if c.PublicURL == "" {
return errors.New("GRUS_PUBLIC_URL is required")
}
if c.CRDs && c.Namespace == "" {
return errors.New("GRUS_NAMESPACE is required for GRUS_CRDS")
}
switch c.TemplatesBackend {
case "fs":
case "s3":
Expand Down
42 changes: 42 additions & 0 deletions cmd/grus/config_crds_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package main

import "testing"

func TestLoadConfigCRDsDefaultToOff(t *testing.T) {
cfg, err := loadConfig(nil, fakeEnv(validEnv()))
if err != nil {
t.Fatalf("loadConfig: %v", err)
}
if cfg.CRDs {
t.Error("CRDs = true, want false by default")
}
}

func TestLoadConfigReadsCRDsFlagFromEnvironment(t *testing.T) {
env := validEnv()
env["GRUS_CRDS"] = "true"
env["GRUS_NAMESPACE"] = "grus-dev"
cfg, err := loadConfig(nil, fakeEnv(env))
if err != nil {
t.Fatalf("loadConfig: %v", err)
}
if !cfg.CRDs {
t.Error("CRDs = false, want true from GRUS_CRDS")
}
}

func TestLoadConfigRejectsCRDsWithoutNamespace(t *testing.T) {
env := validEnv()
env["GRUS_CRDS"] = "true"
if _, err := loadConfig(nil, fakeEnv(env)); err == nil {
t.Fatal("loadConfig accepted GRUS_CRDS without GRUS_NAMESPACE")
}
}

func TestLoadConfigRejectsInvalidCRDsValue(t *testing.T) {
env := validEnv()
env["GRUS_CRDS"] = "maybe"
if _, err := loadConfig(nil, fakeEnv(env)); err == nil {
t.Fatal("loadConfig accepted GRUS_CRDS=maybe")
}
}
1 change: 1 addition & 0 deletions cmd/grus/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ func runController(args []string) error {
ctrlErr = s.ctrl.Run(ctrlCtx)
close(ctrlExited)
}()
startCRDSync(ctrlCtx, cfg, s, logger)
logger.Info("controller started", "listen", cfg.Listen, "driver", s.drv.Name(), "host", s.drv.Host())

var runErr error
Expand Down
50 changes: 50 additions & 0 deletions cmd/grus/crds.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package main

import (
"context"
"fmt"
"log/slog"

"k8s.io/client-go/dynamic"
"k8s.io/client-go/rest"

"github.com/OneLiteFeatherNET/grus/internal/kube/crdsync"
"github.com/OneLiteFeatherNET/grus/internal/model"
)

// newCRDSyncer builds the custom resource syncer on the in-cluster config. It watches only the controller's
// own namespace, so the chart needs a namespaced Role and no ClusterRole.
func newCRDSyncer(cfg config, s *stack, logger *slog.Logger) (*crdsync.Syncer, error) {
restCfg, err := rest.InClusterConfig()
if err != nil {
return nil, fmt.Errorf("in-cluster config: %w", err)
}
client, err := dynamic.NewForConfig(restCfg)
if err != nil {
return nil, fmt.Errorf("dynamic client: %w", err)
}
return crdsync.New(client, s.ctrl, crdsync.Config{
Namespace: cfg.Namespace,
Clock: model.SystemClock{},
Logger: logger,
}), nil
}

// startCRDSync runs the syncer in the background when GRUS_CRDS is set. A failure is logged and does not stop
// the controller: the REST API and the api-owned declarations keep working without the custom resources.
func startCRDSync(ctx context.Context, cfg config, s *stack, logger *slog.Logger) {
if !cfg.CRDs {
return
}
syncer, err := newCRDSyncer(cfg, s, logger)
if err != nil {
logger.Error("custom resource sync disabled", "error", err)
return
}
go func() {
if err := syncer.Run(ctx); err != nil {
logger.Error("custom resource sync stopped", "error", err)
}
}()
logger.Info("custom resource sync started", "namespace", cfg.Namespace)
}
98 changes: 98 additions & 0 deletions deploy/crds/environments.grus.onelitefeather.net.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: environments.grus.onelitefeather.net
spec:
group: grus.onelitefeather.net
scope: Namespaced
names:
kind: Environment
listKind: EnvironmentList
plural: environments
singular: environment
shortNames: [genv]
categories: [grus]
versions:
- name: v1alpha1
served: true
storage: true
subresources:
status: {}
additionalPrinterColumns:
- name: Kind
type: string
jsonPath: .spec.kind
- name: Image
type: string
jsonPath: .spec.image
- name: Port
type: integer
jsonPath: .spec.port
- name: Ready
type: string
jsonPath: .status.conditions[?(@.type=="Ready")].status
- name: Age
type: date
jsonPath: .metadata.creationTimestamp
schema:
openAPIV3Schema:
type: object
description: How a Grus service runs, independent of what it serves.
required: [spec]
properties:
spec:
type: object
required: [kind]
properties:
kind:
type: string
enum: [jvm, native, container]
image:
type: string
command:
type: array
items: {type: string}
args:
type: array
items: {type: string}
jvm:
type: object
properties:
jar:
type: string
flags:
type: array
items: {type: string}
env:
type: object
additionalProperties: {type: string}
port:
type: integer
minimum: 0
maximum: 65535
readiness:
type: string
enum: [self, tcp]
stopCommand:
type: string
gracePeriod:
type: string
description: Go duration such as 30s.
status:
type: object
properties:
observedGeneration:
type: integer
format: int64
conditions:
type: array
items:
type: object
required: [type, status]
properties:
type: {type: string}
status: {type: string}
reason: {type: string}
message: {type: string}
observedGeneration: {type: integer, format: int64}
lastTransitionTime: {type: string, format: date-time}
72 changes: 72 additions & 0 deletions deploy/crds/groups.grus.onelitefeather.net.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: groups.grus.onelitefeather.net
spec:
group: grus.onelitefeather.net
scope: Namespaced
names:
kind: Group
listKind: GroupList
plural: groups
singular: group
shortNames: [ggroup]
categories: [grus]
versions:
- name: v1alpha1
served: true
storage: true
subresources:
status: {}
additionalPrinterColumns:
- name: Templates
type: string
jsonPath: .spec.templates[*].name
- name: Ready
type: string
jsonPath: .status.conditions[?(@.type=="Ready")].status
- name: Age
type: date
jsonPath: .metadata.creationTimestamp
schema:
openAPIV3Schema:
type: object
description: Templates, env and labels shared by many pools.
required: [spec]
properties:
spec:
type: object
properties:
templates:
type: array
items:
type: object
required: [name]
properties:
name: {type: string}
tag: {type: string}
digest: {type: string}
env:
type: object
additionalProperties: {type: string}
labels:
type: object
additionalProperties: {type: string}
status:
type: object
properties:
observedGeneration:
type: integer
format: int64
conditions:
type: array
items:
type: object
required: [type, status]
properties:
type: {type: string}
status: {type: string}
reason: {type: string}
message: {type: string}
observedGeneration: {type: integer, format: int64}
lastTransitionTime: {type: string, format: date-time}
Loading