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
58 changes: 45 additions & 13 deletions cmd/deployment-tracker/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"context"
"flag"
"fmt"
"log"
"log/slog"
"net/http"
Expand Down Expand Up @@ -44,6 +45,13 @@ func main() {
flag.StringVar(&metricsPort, "metrics-port", "9090", "port to listen to for metrics")
flag.Parse()

// Validate worker count
if workers < 1 || workers > 100 {
slog.Error("Invalid worker count, must be between 1 and 100",
"workers", workers)
os.Exit(1)
}

// init logging
log.SetFlags(log.LstdFlags | log.Lshortfile | log.LUTC)
opts := slog.HandlerOptions{Level: slog.LevelInfo}
Expand All @@ -59,6 +67,13 @@ func main() {
Organization: os.Getenv("GITHUB_ORG"),
}

if !controller.ValidTemplate(cntrlCfg.Template) {
slog.Error("Template must contain at least one placeholder",
"template", cntrlCfg.Template,
"valid_placeholders", []string{controller.TmplNS, controller.TmplDN, controller.TmplCN})
os.Exit(1)
}

if cntrlCfg.LogicalEnvironment == "" {
slog.Error("Logical environment is required")
os.Exit(1)
Expand Down Expand Up @@ -87,20 +102,20 @@ func main() {
}

// Start the metrics server
var promSrv = &http.Server{
Addr: ":" + metricsPort,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
ReadHeaderTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
Handler: http.NewServeMux(),
}
promSrv.Handler.(*http.ServeMux).Handle("/metrics", promhttp.Handler())

go func() {
var mm = http.NewServeMux()
mm.Handle("/metrics", promhttp.Handler())

var promSrv = &http.Server{
Addr: ":" + metricsPort,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
ReadHeaderTimeout: 10 * time.Second,
Handler: mm,
}
slog.Info("starting Prometheus metrics server",
"url", promSrv.Addr)
if err := promSrv.ListenAndServe(); err != nil {
if err := promSrv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
slog.Error("failed to start metrics server",
"error", err)
}
Expand All @@ -113,10 +128,24 @@ func main() {
go func() {
<-sigCh
slog.Info("Shutting down...")

// Gracefully shutdown the metrics server
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
defer shutdownCancel()
if err := promSrv.Shutdown(shutdownCtx); err != nil {
slog.Error("failed to shutdown metrics server gracefully",
"error", err)
}

cancel()
}()

cntrl := controller.New(clientset, namespace, &cntrlCfg)
cntrl, err := controller.New(clientset, namespace, &cntrlCfg)
if err != nil {
slog.Error("Failed to create controller",
"error", err)
os.Exit(1)
}

slog.Info("Starting deployment-tracker controller")
if err := cntrl.Run(ctx, workers); err != nil {
Expand Down Expand Up @@ -144,6 +173,9 @@ func createK8sConfig(kubeconfig string) (*rest.Config, error) {
}

// Fall back to default kubeconfig location
homeDir, _ := os.UserHomeDir()
homeDir, err := os.UserHomeDir()
if err != nil {
return nil, fmt.Errorf("failed to get user home directory: %w", err)
}
return clientcmd.BuildConfigFromFlags("", homeDir+"/.kube/config")
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ require (
golang.org/x/sys v0.38.0 // indirect
golang.org/x/term v0.37.0 // indirect
golang.org/x/text v0.31.0 // indirect
golang.org/x/time v0.9.0 // indirect
golang.org/x/time v0.14.0 // indirect
google.golang.org/protobuf v1.36.8 // indirect
gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@ golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY=
golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ=
golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs=
google.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc=
Expand Down
14 changes: 14 additions & 0 deletions internal/controller/config.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package controller

import (
"strings"
)

const (
// TmplNS is the meta variable for the k8s namespace.
TmplNS = "{{namespace}}"
Expand All @@ -19,3 +23,13 @@ type Config struct {
BaseURL string
Organization string
}

// ValidTemplate verifies that at least one placeholder is present
// in the provided template t.
func ValidTemplate(t string) bool {
hasPlaceholder := strings.Contains(t, TmplNS) ||
strings.Contains(t, TmplDN) ||
strings.Contains(t, TmplCN)

return hasPlaceholder
}
113 changes: 113 additions & 0 deletions internal/controller/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
package controller

import (
"testing"
)

func TestValidTemplate(t *testing.T) {
tests := []struct {
name string
template string
expected bool
}{
{
name: "empty string",
template: "",
expected: false,
},
{
name: "static string without placeholders",
template: "static-deployment-name",
expected: false,
},
{
name: "namespace placeholder only",
template: "{{namespace}}",
expected: true,
},
{
name: "deployment name placeholder only",
template: "{{deploymentName}}",
expected: true,
},
{
name: "container name placeholder only",
template: "{{containerName}}",
expected: true,
},
{
name: "all three placeholders",
template: "{{namespace}}/{{deploymentName}}/{{containerName}}",
expected: true,
},
{
name: "namespace and deployment name",
template: "{{namespace}}-{{deploymentName}}",
expected: true,
},
{
name: "mixed static and placeholders",
template: "prefix-{{namespace}}-suffix",
expected: true,
},
{
name: "placeholder with surrounding text",
template: "app/{{containerName}}/prod",
expected: true,
},
{
name: "similar but invalid placeholder",
template: "{{namespaces}}",
expected: false,
},
{
name: "partial placeholder - missing closing braces",
template: "{{namespace",
expected: false,
},
{
name: "partial placeholder - missing opening braces",
template: "namespace}}",
expected: false,
},
{
name: "wrong case placeholder",
template: "{{Namespace}}",
expected: false,
},
{
name: "placeholder with extra space",
template: "{{ namespace }}",
expected: false,
},
{
name: "default template format",
template: TmplNS + "/" + TmplDN + "/" + TmplCN,
expected: true,
},
{
name: "complex valid template",
template: "org/{{namespace}}/env/{{deploymentName}}/container/{{containerName}}",
expected: true,
},
{
name: "whitespace only",
template: " ",
expected: false,
},
{
name: "special characters without placeholders",
template: "app-name_v1.2.3",
expected: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := ValidTemplate(tt.template)
if result != tt.expected {
t.Errorf("ValidTemplate(%q) = %v, expected %v", tt.template, result, tt.expected)
}
})
}
}
22 changes: 16 additions & 6 deletions internal/controller/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package controller
import (
"context"
"errors"
"fmt"
"log/slog"
"strings"
"time"
Expand Down Expand Up @@ -36,7 +37,7 @@ type Controller struct {
}

// New creates a new deployment tracker controller.
func New(clientset kubernetes.Interface, namespace string, cfg *Config) *Controller {
func New(clientset kubernetes.Interface, namespace string, cfg *Config) (*Controller, error) {
// Create informer factory
var factory informers.SharedInformerFactory
if namespace == "" {
Expand All @@ -63,11 +64,14 @@ func New(clientset kubernetes.Interface, namespace string, cfg *Config) *Control
if cfg.APIToken != "" {
clientOpts = append(clientOpts, deploymentrecord.WithAPIToken(cfg.APIToken))
}
apiClient := deploymentrecord.NewClient(
apiClient, err := deploymentrecord.NewClient(
cfg.BaseURL,
cfg.Organization,
clientOpts...,
)
if err != nil {
return nil, fmt.Errorf("failed to create API client: %w", err)
}

cntrl := &Controller{
clientset: clientset,
Expand All @@ -78,7 +82,7 @@ func New(clientset kubernetes.Interface, namespace string, cfg *Config) *Control
}

// Add event handlers to the informer
_, err := podInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
_, err = podInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj any) {
pod, ok := obj.(*corev1.Pod)
if !ok {
Expand Down Expand Up @@ -172,11 +176,10 @@ func New(clientset kubernetes.Interface, namespace string, cfg *Config) *Control
})

if err != nil {
slog.Error("Failed to add event handlers",
"error", err)
return nil, fmt.Errorf("failed to add event handlers: %w", err)
}

return cntrl
return cntrl, nil
}

// Run starts the controller.
Expand Down Expand Up @@ -304,6 +307,13 @@ func (c *Controller) recordContainer(ctx context.Context, pod *corev1.Pod, conta
digest := getContainerDigest(pod, container.Name)

if dn == "" || digest == "" {
slog.Debug("Skipping container: missing deployment name or digest",
"namespace", pod.Namespace,
"pod", pod.Name,
"container", container.Name,
"deployment_name", dn,
"has_digest", digest != "",
)
return nil
}

Expand Down
Loading