commit bf229aeed29167c12b4c59d47a24a711565af787 Author: nandi <78769380+codegod100@users.noreply.github.com> Date: Tue Nov 17 21:11:30 2026 +0000 feat: initial gitea-k3s-deployer service, web UI, tests, and K3s/Depot manifests diff --git a/.gitea/workflows/build.yaml b/.gitea/workflows/build.yaml new file mode 100644 index 0000000..15cc82b --- /dev/null +++ b/.gitea/workflows/build.yaml @@ -0,0 +1,35 @@ +name: Build and Push Image + +on: + push: + branches: + - main + +jobs: + build: + runs-on: ubuntu-latest + env: + DEPOT_TOKEN: ${{ secrets.DEPOT_TOKEN }} + DEPOT_PROJECT_ID: ${{ secrets.DEPOT_PROJECT_ID }} + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Install Depot CLI + run: | + curl -fsSL https://depot.dev/install-cli.sh | sh + echo "$HOME/.depot/bin" >> "$GITHUB_PATH" + + - name: Login to Gitea Container Registry + run: | + echo "${{ secrets.REGISTRY_TOKEN }}" | docker login git.site.latha.org -u "${{ github.actor }}" --password-stdin + + - name: Build and Push with Depot + run: | + SHORT_SHA="${GITHUB_SHA::8}" + depot build \ + --project "$DEPOT_PROJECT_ID" \ + --push \ + -t "git.site.latha.org/experiments/gitea-k3s-deployer:${SHORT_SHA}" \ + -t "git.site.latha.org/experiments/gitea-k3s-deployer:latest" \ + . diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cf69438 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/deployer +/state.json +*.tmp diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..b6bf8df --- /dev/null +++ b/Dockerfile @@ -0,0 +1,12 @@ +FROM golang:1.24-bookworm AS builder +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY . . +RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o /out/deployer ./cmd/deployer + +FROM gcr.io/distroless/static-debian12:nonroot +COPY --from=builder /out/deployer /deployer +EXPOSE 8080 +USER 65532:65532 +ENTRYPOINT ["/deployer"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..6fdb27f --- /dev/null +++ b/README.md @@ -0,0 +1,38 @@ +# gitea-k3s-deployer + +Lightweight Go deployment service that taps into Gitea (`https://git.site.latha.org`) and deploys applications to K3s (`dash.latha.org` / `k3s-kplae-u30796`) via Server-Side Apply. + +## Features + +- **Gitea Webhook Listener (`POST /webhook/gitea`)**: Verifies `X-Gitea-Signature` (HMAC-SHA256) and handles `ping`, `push`, `release`, and `workflow_run` events. +- **Two Deployment Modes**: + 1. **`.latha-deploy.yaml` / `deploy.yaml`**: Declarative app spec that renders `Namespace`, `Deployment` (with safe non-`BestEffort` default `requests`/`limits`), `Service`, and Traefik `Ingress` (`websecure` + `letsencrypt`). + 2. **`k8s/*.yaml` directory**: Syncs raw Kubernetes manifests with `${IMAGE_TAG}`, `${SHORT_SHA}`, `${COMMIT_SHA}`, `${APP_NAME}`, and `${REF}` substitution. +- **Web UI Dashboard (`GET /`)**: Shows registered apps, deployment history + logs, recent webhook deliveries, manual deploy trigger, and one-click rollback. +- **REST API & Observability**: + - `GET /healthz`, `GET /readyz`, `GET /metrics` + - `GET /api/apps`, `POST /api/apps` + - `GET /api/deployments`, `GET /api/deployments/{id}`, `POST /api/deploy`, `POST /api/deployments/{id}/rollback` + - `GET /api/webhooks` + +## Example `.latha-deploy.yaml` + +```yaml +name: my-app +namespace: apps +branch: main +image: git.site.latha.org/experiments/my-app +tagStrategy: sha # sha | latest | release | ref +port: 8080 +host: my-app.site.latha.org +healthPath: /healthz +replicas: 1 +secretRefs: + - my-app-secrets +``` + +## Secrets (OpenBao -> K8s Secret) + +Create `gitea-deployer-secrets` in namespace `gitea-deployer` with: +- `GITEA_WEBHOOK_SECRET`: Shared HMAC-SHA256 secret configured on Gitea webhooks +- `GITEA_TOKEN`: Gitea personal access token for reading private repositories diff --git a/cmd/deployer/main.go b/cmd/deployer/main.go new file mode 100644 index 0000000..2d24833 --- /dev/null +++ b/cmd/deployer/main.go @@ -0,0 +1,60 @@ +package main + +import ( + "context" + "errors" + "log" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/config" + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/deployer" + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/gitea" + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/k8s" + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/server" + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/store" +) + +func main() { + cfg := config.LoadFromEnv() + + st, err := store.New(cfg.DataFile) + if err != nil { + log.Fatalf("init store (%s): %v", cfg.DataFile, err) + } + + ka, err := k8s.NewClient(cfg) + if err != nil { + log.Fatalf("init k8s client (mode=%s): %v", cfg.KubeMode, err) + } + + gc := gitea.NewClient(cfg.GiteaURL, cfg.GiteaToken) + svc := deployer.NewService(cfg, st, gc, ka) + srv := server.New(cfg, st, svc, ka) + + httpServer := &http.Server{ + Addr: ":" + cfg.Port, + Handler: srv.Handler(), + ReadHeaderTimeout: 10 * time.Second, + } + + go func() { + log.Printf("gitea-k3s-deployer listening on :%s (gitea=%s, kube_mode=%s)", cfg.Port, cfg.GiteaURL, ka.Mode()) + if err := httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + log.Fatalf("http server error: %v", err) + } + }() + + stop := make(chan os.Signal, 1) + signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM) + <-stop + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := httpServer.Shutdown(ctx); err != nil { + log.Printf("graceful shutdown error: %v", err) + } +} diff --git a/deploy/k8s/deployment.yaml b/deploy/k8s/deployment.yaml new file mode 100644 index 0000000..7a9c4e1 --- /dev/null +++ b/deploy/k8s/deployment.yaml @@ -0,0 +1,84 @@ +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: gitea-deployer-data + namespace: gitea-deployer +spec: + accessModes: + - ReadWriteOnce + resources: + requests: + storage: 256Mi +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: gitea-k3s-deployer + namespace: gitea-deployer + labels: + app: gitea-k3s-deployer +spec: + replicas: 1 + strategy: + type: Recreate + selector: + matchLabels: + app: gitea-k3s-deployer + template: + metadata: + labels: + app: gitea-k3s-deployer + spec: + serviceAccountName: gitea-k3s-deployer + imagePullSecrets: + - name: gitea-registry-secret + containers: + - name: deployer + image: git.site.latha.org/experiments/gitea-k3s-deployer:latest + imagePullPolicy: Always + ports: + - containerPort: 8080 + name: http + envFrom: + - secretRef: + name: gitea-deployer-secrets + optional: true + env: + - name: PORT + value: "8080" + - name: GITEA_URL + value: "https://git.site.latha.org" + - name: KUBE_MODE + value: "in-cluster" + - name: ALLOWED_OWNERS + value: "experiments,nandi" + - name: DATA_FILE + value: "/data/state.json" + - name: DEFAULT_IMAGE_PULL_SECRET + value: "gitea-registry-secret" + readinessProbe: + httpGet: + path: /readyz + port: http + initialDelaySeconds: 2 + periodSeconds: 5 + livenessProbe: + httpGet: + path: /healthz + port: http + initialDelaySeconds: 5 + periodSeconds: 10 + resources: + requests: + cpu: 50m + memory: 64Mi + limits: + cpu: 500m + memory: 256Mi + volumeMounts: + - name: data + mountPath: /data + volumes: + - name: data + persistentVolumeClaim: + claimName: gitea-deployer-data diff --git a/deploy/k8s/ingress.yaml b/deploy/k8s/ingress.yaml new file mode 100644 index 0000000..20ad752 --- /dev/null +++ b/deploy/k8s/ingress.yaml @@ -0,0 +1,22 @@ +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: gitea-k3s-deployer + namespace: gitea-deployer + annotations: + traefik.ingress.kubernetes.io/router.entrypoints: websecure + traefik.ingress.kubernetes.io/router.tls.certresolver: letsencrypt + traefik.ingress.kubernetes.io/router.tls.domains.0.main: deploy.site.latha.org +spec: + ingressClassName: traefik + rules: + - host: deploy.site.latha.org + http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: gitea-k3s-deployer + port: + number: 80 diff --git a/deploy/k8s/namespace.yaml b/deploy/k8s/namespace.yaml new file mode 100644 index 0000000..bbd0a39 --- /dev/null +++ b/deploy/k8s/namespace.yaml @@ -0,0 +1,6 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: gitea-deployer + labels: + app.kubernetes.io/name: gitea-k3s-deployer diff --git a/deploy/k8s/rbac.yaml b/deploy/k8s/rbac.yaml new file mode 100644 index 0000000..08f88a2 --- /dev/null +++ b/deploy/k8s/rbac.yaml @@ -0,0 +1,33 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: + name: gitea-k3s-deployer + namespace: gitea-deployer +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: gitea-k3s-deployer +rules: + - apiGroups: [""] + resources: ["namespaces", "services", "configmaps", "secrets", "persistentvolumeclaims"] + verbs: ["get", "list", "watch", "create", "update", "patch"] + - apiGroups: ["apps"] + resources: ["deployments", "statefulsets"] + verbs: ["get", "list", "watch", "create", "update", "patch"] + - apiGroups: ["networking.k8s.io"] + resources: ["ingresses"] + verbs: ["get", "list", "watch", "create", "update", "patch"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: gitea-k3s-deployer +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: gitea-k3s-deployer +subjects: + - kind: ServiceAccount + name: gitea-k3s-deployer + namespace: gitea-deployer diff --git a/deploy/k8s/service.yaml b/deploy/k8s/service.yaml new file mode 100644 index 0000000..089ffeb --- /dev/null +++ b/deploy/k8s/service.yaml @@ -0,0 +1,12 @@ +apiVersion: v1 +kind: Service +metadata: + name: gitea-k3s-deployer + namespace: gitea-deployer +spec: + selector: + app: gitea-k3s-deployer + ports: + - port: 80 + targetPort: http + protocol: TCP diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..a811449 --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module git.site.latha.org/experiments/gitea-k3s-deployer + +go 1.27.3 + +require gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..4bc0337 --- /dev/null +++ b/go.sum @@ -0,0 +1,3 @@ +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..8c128f0 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,67 @@ +package config + +import ( + "os" + "strings" +) + +type Config struct { + Port string + GiteaURL string + GiteaToken string + GiteaWebhookSecret string + AllowedOwners []string + AutoDiscoverRepos bool + KubeMode string // "in-cluster", "external", "dry-run" + KubeAPIURL string + KubeToken string + KubeInsecureTLS bool + DataFile string + DefaultImagePullSecret string + DomainSuffix string +} + +func LoadFromEnv() Config { + ownersRaw := getEnv("ALLOWED_OWNERS", "experiments,nandi") + var owners []string + for _, o := range strings.Split(ownersRaw, ",") { + o = strings.TrimSpace(o) + if o != "" { + owners = append(owners, o) + } + } + + kubeMode := getEnv("KUBE_MODE", "auto") + if kubeMode == "auto" { + if _, err := os.Stat("/var/run/secrets/kubernetes.io/serviceaccount/token"); err == nil { + kubeMode = "in-cluster" + } else if os.Getenv("KUBE_API_URL") != "" { + kubeMode = "external" + } else { + kubeMode = "dry-run" + } + } + + return Config{ + Port: getEnv("PORT", "8080"), + GiteaURL: strings.TrimRight(getEnv("GITEA_URL", "https://git.site.latha.org"), "/"), + GiteaToken: os.Getenv("GITEA_TOKEN"), + GiteaWebhookSecret: os.Getenv("GITEA_WEBHOOK_SECRET"), + AllowedOwners: owners, + AutoDiscoverRepos: getEnv("AUTO_DISCOVER_REPOS", "true") == "true", + KubeMode: kubeMode, + KubeAPIURL: strings.TrimRight(os.Getenv("KUBE_API_URL"), "/"), + KubeToken: os.Getenv("KUBE_TOKEN"), + KubeInsecureTLS: getEnv("KUBE_INSECURE_TLS", "false") == "true", + DataFile: getEnv("DATA_FILE", "/data/state.json"), + DefaultImagePullSecret: getEnv("DEFAULT_IMAGE_PULL_SECRET", "gitea-registry-secret"), + DomainSuffix: getEnv("DOMAIN_SUFFIX", "site.latha.org"), + } +} + +func getEnv(key, fallback string) string { + if v := os.Getenv(key); v != "" { + return v + } + return fallback +} diff --git a/internal/deployer/service.go b/internal/deployer/service.go new file mode 100644 index 0000000..ef5bdf3 --- /dev/null +++ b/internal/deployer/service.go @@ -0,0 +1,336 @@ +package deployer + +import ( + "context" + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + "path" + "sort" + "strings" + "sync/atomic" + "time" + + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/config" + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/gitea" + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/k8s" + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/manifest" + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/store" +) + +type DeployRequest struct { + Repo string `json:"repo"` // owner/name + Ref string `json:"ref"` + CommitSHA string `json:"commit_sha,omitempty"` + ImageTag string `json:"image_tag,omitempty"` + Trigger string `json:"trigger,omitempty"` + Actor string `json:"actor,omitempty"` +} + +type Metrics struct { + WebhooksTotal atomic.Int64 + WebhooksRejected atomic.Int64 + DeploymentsTotal atomic.Int64 + DeploymentsSuccess atomic.Int64 + DeploymentsFailed atomic.Int64 +} + +type Service struct { + cfg config.Config + store *store.Store + gitea gitea.Client + k8s k8s.Applier + Metrics Metrics +} + +func NewService(cfg config.Config, st *store.Store, gc gitea.Client, ka k8s.Applier) *Service { + return &Service{ + cfg: cfg, + store: st, + gitea: gc, + k8s: ka, + } +} + +func (s *Service) IsOwnerAllowed(owner string) bool { + if len(s.cfg.AllowedOwners) == 0 { + return true + } + for _, o := range s.cfg.AllowedOwners { + if strings.EqualFold(o, owner) { + return true + } + } + return false +} + +func (s *Service) DeployRepo(ctx context.Context, req DeployRequest) (store.Deployment, error) { + s.Metrics.DeploymentsTotal.Add(1) + + parts := strings.Split(strings.Trim(req.Repo, "/"), "/") + if len(parts) != 2 { + s.Metrics.DeploymentsFailed.Add(1) + return store.Deployment{}, fmt.Errorf("invalid repo %q, expected owner/name", req.Repo) + } + owner, repoName := parts[0], parts[1] + if !s.IsOwnerAllowed(owner) { + s.Metrics.DeploymentsFailed.Add(1) + return store.Deployment{}, fmt.Errorf("repository owner %q is not in ALLOWED_OWNERS", owner) + } + + ref := req.Ref + if ref == "" { + ref = "main" + } + trigger := req.Trigger + if trigger == "" { + trigger = "manual" + } + actor := req.Actor + if actor == "" { + actor = "api" + } + + dep := store.Deployment{ + ID: newID(), + AppName: manifest.SanitizeName(repoName), + Repo: owner + "/" + repoName, + Ref: ref, + CommitSHA: req.CommitSHA, + ImageTag: req.ImageTag, + Trigger: trigger, + Actor: actor, + Namespace: "default", + Status: store.StatusRunning, + Logs: []string{fmt.Sprintf("[%s] Starting deployment for %s@%s (mode=%s)", time.Now().UTC().Format(time.RFC3339), req.Repo, ref, s.k8s.Mode())}, + StartedAt: time.Now().UTC(), + } + s.store.AddDeployment(dep) + + fail := func(err error) (store.Deployment, error) { + now := time.Now().UTC() + dep.Status = store.StatusFailed + dep.Error = err.Error() + dep.FinishedAt = &now + dep.Logs = append(dep.Logs, fmt.Sprintf("[ERROR] %v", err)) + s.store.UpdateDeployment(dep) + s.Metrics.DeploymentsFailed.Add(1) + return dep, err + } + + rctx := manifest.RenderContext{ + Owner: owner, + RepoName: repoName, + Ref: ref, + CommitSHA: req.CommitSHA, + ImageTag: req.ImageTag, + DefaultImagePullSecret: s.cfg.DefaultImagePullSecret, + DomainSuffix: s.cfg.DomainSuffix, + } + + var spec manifest.DeploySpec + var hasSpec bool + for _, specFile := range []string{".latha-deploy.yaml", "deploy.yaml"} { + rawSpec, err := s.gitea.GetFile(ctx, owner, repoName, specFile, ref) + if err == nil { + parsed, err := manifest.ParseSpec(rawSpec, rctx) + if err != nil { + return fail(err) + } + spec = parsed + hasSpec = true + dep.AppName = spec.Name + dep.Namespace = spec.Namespace + dep.ImageTag = manifest.ResolveImageTag(spec, rctx) + dep.Logs = append(dep.Logs, fmt.Sprintf("Loaded %s (app=%s, ns=%s, image=%s:%s)", specFile, spec.Name, spec.Namespace, spec.Image, dep.ImageTag)) + break + } + if !errors.Is(err, gitea.ErrNotFound) { + return fail(fmt.Errorf("fetch %s: %w", specFile, err)) + } + } + + var combinedYAML []byte + var manifestsDir string + if hasSpec && spec.ManifestsDir != "" { + manifestsDir = spec.ManifestsDir + } else if !hasSpec { + manifestsDir = "k8s" + } + + if manifestsDir != "" { + entries, err := s.gitea.ListDir(ctx, owner, repoName, manifestsDir, ref) + if err != nil { + if errors.Is(err, gitea.ErrNotFound) && !hasSpec { + return fail(fmt.Errorf("no .latha-deploy.yaml, deploy.yaml, or %s/ directory found in %s@%s", manifestsDir, req.Repo, ref)) + } + return fail(fmt.Errorf("list %s: %w", manifestsDir, err)) + } + sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name }) + var chunks [][]byte + for _, e := range entries { + if e.Type != "file" { + continue + } + ext := strings.ToLower(path.Ext(e.Name)) + if ext != ".yaml" && ext != ".yml" { + continue + } + raw, err := s.gitea.GetFile(ctx, owner, repoName, e.Path, ref) + if err != nil { + return fail(fmt.Errorf("fetch %s: %w", e.Path, err)) + } + chunks = append(chunks, manifest.SubstituteVars(raw, rctx)) + dep.Logs = append(dep.Logs, fmt.Sprintf("Loaded manifest %s", e.Path)) + } + if len(chunks) == 0 { + return fail(fmt.Errorf("no YAML manifests found in %s/", manifestsDir)) + } + combinedYAML = []byte(joinYAMLDocs(chunks)) + } else { + rendered, err := manifest.RenderFromSpec(spec, rctx) + if err != nil { + return fail(fmt.Errorf("render manifests: %w", err)) + } + combinedYAML = rendered + dep.Logs = append(dep.Logs, "Rendered Kubernetes manifests from deploy spec") + } + + dep.RenderedYAML = string(combinedYAML) + objs, err := manifest.SplitYAMLObjects(combinedYAML, dep.Namespace) + if err != nil { + return fail(err) + } + + // Apply Namespaces before namespaced resources + sort.SliceStable(objs, func(i, j int) bool { + if objs[i].Kind == "Namespace" && objs[j].Kind != "Namespace" { + return true + } + return false + }) + + for _, obj := range objs { + if err := s.k8s.Apply(ctx, obj); err != nil { + return fail(err) + } + label := fmt.Sprintf("%s/%s", obj.Kind, obj.Name) + if obj.Namespace != "" { + label = fmt.Sprintf("%s/%s/%s", obj.Namespace, obj.Kind, obj.Name) + } + dep.AppliedResources = append(dep.AppliedResources, label) + dep.Logs = append(dep.Logs, fmt.Sprintf("Applied %s", label)) + } + + now := time.Now().UTC() + dep.Status = store.StatusSucceeded + dep.FinishedAt = &now + dep.Logs = append(dep.Logs, fmt.Sprintf("Deployment %s succeeded (%d resources applied)", dep.ID, len(dep.AppliedResources))) + s.store.UpdateDeployment(dep) + s.Metrics.DeploymentsSuccess.Add(1) + + app := store.App{ + Name: dep.AppName, + Repo: dep.Repo, + Branch: ref, + Namespace: dep.Namespace, + Host: spec.Host, + Image: spec.Image, + LastDeploymentID: dep.ID, + LastStatus: string(dep.Status), + LastRef: dep.Ref, + LastCommit: dep.CommitSHA, + } + if app.Image == "" { + app.Image = fmt.Sprintf("git.site.latha.org/%s", dep.Repo) + } + s.store.UpsertApp(app) + + return dep, nil +} + +func (s *Service) RollbackDeployment(ctx context.Context, deploymentID, actor string) (store.Deployment, error) { + prev, ok := s.store.GetDeployment(deploymentID) + if !ok { + return store.Deployment{}, fmt.Errorf("deployment %q not found", deploymentID) + } + if prev.RenderedYAML == "" { + return s.DeployRepo(ctx, DeployRequest{ + Repo: prev.Repo, + Ref: prev.Ref, + CommitSHA: prev.CommitSHA, + ImageTag: prev.ImageTag, + Trigger: "rollback", + Actor: actor, + }) + } + + s.Metrics.DeploymentsTotal.Add(1) + dep := store.Deployment{ + ID: newID(), + AppName: prev.AppName, + Repo: prev.Repo, + Ref: prev.Ref, + CommitSHA: prev.CommitSHA, + ImageTag: prev.ImageTag, + Trigger: "rollback:" + prev.ID, + Actor: actor, + Namespace: prev.Namespace, + Status: store.StatusRunning, + RenderedYAML: prev.RenderedYAML, + Logs: []string{fmt.Sprintf("Rolling back %s to snapshot from deployment %s", prev.Repo, prev.ID)}, + StartedAt: time.Now().UTC(), + } + s.store.AddDeployment(dep) + + objs, err := manifest.SplitYAMLObjects([]byte(prev.RenderedYAML), prev.Namespace) + if err != nil { + now := time.Now().UTC() + dep.Status = store.StatusFailed + dep.Error = err.Error() + dep.FinishedAt = &now + s.store.UpdateDeployment(dep) + s.Metrics.DeploymentsFailed.Add(1) + return dep, err + } + + for _, obj := range objs { + if err := s.k8s.Apply(ctx, obj); err != nil { + now := time.Now().UTC() + dep.Status = store.StatusFailed + dep.Error = err.Error() + dep.FinishedAt = &now + dep.Logs = append(dep.Logs, fmt.Sprintf("[ERROR] %v", err)) + s.store.UpdateDeployment(dep) + s.Metrics.DeploymentsFailed.Add(1) + return dep, err + } + dep.AppliedResources = append(dep.AppliedResources, fmt.Sprintf("%s/%s", obj.Kind, obj.Name)) + } + + now := time.Now().UTC() + dep.Status = store.StatusSucceeded + dep.FinishedAt = &now + dep.Logs = append(dep.Logs, "Rollback succeeded") + s.store.UpdateDeployment(dep) + s.Metrics.DeploymentsSuccess.Add(1) + return dep, nil +} + +func joinYAMLDocs(chunks [][]byte) string { + var parts []string + for _, c := range chunks { + s := strings.TrimSpace(string(c)) + if s != "" { + parts = append(parts, s) + } + } + return strings.Join(parts, "\n---\n") + "\n" +} + +func newID() string { + var b [6]byte + _, _ = rand.Read(b[:]) + return hex.EncodeToString(b[:]) +} diff --git a/internal/gitea/client.go b/internal/gitea/client.go new file mode 100644 index 0000000..39e1962 --- /dev/null +++ b/internal/gitea/client.go @@ -0,0 +1,209 @@ +package gitea + +import ( + "context" + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" +) + +var ErrNotFound = errors.New("gitea resource not found") + +type DirEntry struct { + Name string `json:"name"` + Path string `json:"path"` + Type string `json:"type"` // "file" or "dir" + DownloadURL string `json:"download_url"` +} + +type Client interface { + GetFile(ctx context.Context, owner, repo, path, ref string) ([]byte, error) + ListDir(ctx context.Context, owner, repo, path, ref string) ([]DirEntry, error) +} + +type HTTPClient struct { + BaseURL string + Token string + HTTPClient *http.Client +} + +func NewClient(baseURL, token string) *HTTPClient { + return &HTTPClient{ + BaseURL: strings.TrimRight(baseURL, "/"), + Token: token, + HTTPClient: &http.Client{ + Timeout: 15 * time.Second, + }, + } +} + +func (c *HTTPClient) doRequest(ctx context.Context, reqURL string) ([]byte, int, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil) + if err != nil { + return nil, 0, err + } + if c.Token != "" { + req.Header.Set("Authorization", "token "+c.Token) + } + req.Header.Set("Accept", "application/json") + + resp, err := c.HTTPClient.Do(req) + if err != nil { + return nil, 0, err + } + defer resp.Body.Close() + + body, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) // 4 MiB max + if err != nil { + return nil, resp.StatusCode, err + } + return body, resp.StatusCode, nil +} + +func (c *HTTPClient) GetFile(ctx context.Context, owner, repo, filePath, ref string) ([]byte, error) { + escapedPath := escapePathSegments(filePath) + u := fmt.Sprintf("%s/api/v1/repos/%s/%s/raw/%s", c.BaseURL, url.PathEscape(owner), url.PathEscape(repo), escapedPath) + if ref != "" { + u += "?ref=" + url.QueryEscape(ref) + } + + body, status, err := c.doRequest(ctx, u) + if err != nil { + return nil, err + } + if status == http.StatusNotFound { + return nil, ErrNotFound + } + if status < 200 || status >= 300 { + return nil, fmt.Errorf("gitea GET %s returned HTTP %d: %s", u, status, string(body)) + } + return body, nil +} + +func (c *HTTPClient) ListDir(ctx context.Context, owner, repo, dirPath, ref string) ([]DirEntry, error) { + escapedPath := escapePathSegments(dirPath) + u := fmt.Sprintf("%s/api/v1/repos/%s/%s/contents/%s", c.BaseURL, url.PathEscape(owner), url.PathEscape(repo), escapedPath) + if ref != "" { + u += "?ref=" + url.QueryEscape(ref) + } + + body, status, err := c.doRequest(ctx, u) + if err != nil { + return nil, err + } + if status == http.StatusNotFound { + return nil, ErrNotFound + } + if status < 200 || status >= 300 { + return nil, fmt.Errorf("gitea GET %s returned HTTP %d: %s", u, status, string(body)) + } + + var entries []DirEntry + if err := json.Unmarshal(body, &entries); err != nil { + return nil, fmt.Errorf("decode gitea contents: %w", err) + } + return entries, nil +} + +func escapePathSegments(p string) string { + p = strings.TrimPrefix(p, "/") + parts := strings.Split(p, "/") + for i := range parts { + parts[i] = url.PathEscape(parts[i]) + } + return strings.Join(parts, "/") +} + +// VerifySignature validates Gitea's X-Gitea-Signature HMAC-SHA256 hex digest. +func VerifySignature(secret string, payload []byte, signature string) bool { + if secret == "" { + return true + } + signature = strings.TrimSpace(signature) + signature = strings.TrimPrefix(signature, "sha256=") + if signature == "" { + return false + } + gotMAC, err := hex.DecodeString(signature) + if err != nil { + return false + } + mac := hmac.New(sha256.New, []byte(secret)) + mac.Write(payload) + expectedMAC := mac.Sum(nil) + return hmac.Equal(gotMAC, expectedMAC) +} + +// Webhook Payload Models + +type Repository struct { + FullName string `json:"full_name"` + Name string `json:"name"` + DefaultBranch string `json:"default_branch"` + Owner struct { + Username string `json:"username"` + Login string `json:"login"` + } `json:"owner"` +} + +type User struct { + Username string `json:"username"` + Login string `json:"login"` + Email string `json:"email"` +} + +type PushEvent struct { + Ref string `json:"ref"` + After string `json:"after"` + Before string `json:"before"` + Repository Repository `json:"repository"` + Pusher User `json:"pusher"` + Sender User `json:"sender"` + HeadCommit struct { + ID string `json:"id"` + Message string `json:"message"` + } `json:"head_commit"` +} + +type ReleaseEvent struct { + Action string `json:"action"` + Release struct { + TagName string `json:"tag_name"` + TargetCommitish string `json:"target_commitish"` + Name string `json:"name"` + Draft bool `json:"draft"` + Prerelease bool `json:"prerelease"` + } `json:"release"` + Repository Repository `json:"repository"` + Sender User `json:"sender"` +} + +type WorkflowRunEvent struct { + Action string `json:"action"` + WorkflowRun struct { + ID int64 `json:"id"` + Name string `json:"name"` + HeadBranch string `json:"head_branch"` + HeadSHA string `json:"head_sha"` + Status string `json:"status"` + Conclusion string `json:"conclusion"` + } `json:"workflow_run"` + Repository Repository `json:"repository"` + Sender User `json:"sender"` +} + +func BranchFromRef(ref string) string { + const prefix = "refs/heads/" + if strings.HasPrefix(ref, prefix) { + return strings.TrimPrefix(ref, prefix) + } + return ref +} diff --git a/internal/k8s/client.go b/internal/k8s/client.go new file mode 100644 index 0000000..3c0a0b9 --- /dev/null +++ b/internal/k8s/client.go @@ -0,0 +1,149 @@ +package k8s + +import ( + "bytes" + "context" + "crypto/tls" + "crypto/x509" + "fmt" + "io" + "net/http" + "os" + "strings" + "time" + + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/config" + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/manifest" +) + +type Applier interface { + Apply(ctx context.Context, obj manifest.K8sObject) error + Mode() string +} + +type RESTClient struct { + baseURL string + token string + mode string + httpClient *http.Client +} + +func NewClient(cfg config.Config) (*RESTClient, error) { + if cfg.KubeMode == "dry-run" { + return &RESTClient{mode: "dry-run"}, nil + } + + if cfg.KubeMode == "in-cluster" { + tokenBytes, err := os.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/token") + if err != nil { + return nil, fmt.Errorf("read serviceaccount token: %w", err) + } + caBytes, err := os.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/ca.crt") + if err != nil { + return nil, fmt.Errorf("read serviceaccount ca.crt: %w", err) + } + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(caBytes) { + return nil, fmt.Errorf("failed to parse serviceaccount ca.crt") + } + tr := &http.Transport{ + TLSClientConfig: &tls.Config{RootCAs: pool}, + } + return &RESTClient{ + baseURL: "https://kubernetes.default.svc", + token: strings.TrimSpace(string(tokenBytes)), + mode: "in-cluster", + httpClient: &http.Client{Transport: tr, Timeout: 20 * time.Second}, + }, nil + } + + // external mode (e.g. Headlamp API proxy https://dash.latha.org/clusters/main) + if cfg.KubeAPIURL == "" { + return nil, fmt.Errorf("KUBE_API_URL is required in external mode") + } + tr := &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: cfg.KubeInsecureTLS}, //nolint:gosec + } + return &RESTClient{ + baseURL: cfg.KubeAPIURL, + token: cfg.KubeToken, + mode: "external", + httpClient: &http.Client{Transport: tr, Timeout: 20 * time.Second}, + }, nil +} + +func (c *RESTClient) Mode() string { + return c.mode +} + +func (c *RESTClient) Apply(ctx context.Context, obj manifest.K8sObject) error { + if c.mode == "dry-run" { + return nil + } + + path := ResourcePath(obj.APIVersion, obj.Kind, obj.Namespace, obj.Name) + reqURL := fmt.Sprintf("%s%s?fieldManager=gitea-k3s-deployer&force=true", c.baseURL, path) + + req, err := http.NewRequestWithContext(ctx, http.MethodPatch, reqURL, bytes.NewReader(obj.RawYAML)) + if err != nil { + return err + } + req.Header.Set("Content-Type", "application/apply-patch+yaml") + req.Header.Set("Accept", "application/json") + if c.token != "" { + req.Header.Set("Authorization", "Bearer "+c.token) + } + + resp, err := c.httpClient.Do(req) + if err != nil { + return fmt.Errorf("k8s apply %s/%s: %w", obj.Kind, obj.Name, err) + } + defer resp.Body.Close() + + body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return fmt.Errorf("k8s apply %s %s/%s failed (HTTP %d): %s", obj.Kind, obj.Namespace, obj.Name, resp.StatusCode, strings.TrimSpace(string(body))) + } + return nil +} + +func ResourcePath(apiVersion, kind, namespace, name string) string { + plural := kindToPlural(kind) + var prefix string + if apiVersion == "v1" { + prefix = "/api/v1" + } else { + prefix = "/apis/" + apiVersion + } + + if namespace == "" || isClusterScoped(kind) { + return fmt.Sprintf("%s/%s/%s", prefix, plural, name) + } + return fmt.Sprintf("%s/namespaces/%s/%s/%s", prefix, namespace, plural, name) +} + +func kindToPlural(kind string) string { + lower := strings.ToLower(kind) + switch lower { + case "ingress": + return "ingresses" + case "networkpolicy": + return "networkpolicies" + case "endpoints": + return "endpoints" + default: + if strings.HasSuffix(lower, "s") { + return lower + "es" + } + return lower + "s" + } +} + +func isClusterScoped(kind string) bool { + switch kind { + case "Namespace", "ClusterRole", "ClusterRoleBinding", "PersistentVolume", "StorageClass", "CustomResourceDefinition", "IngressClass": + return true + default: + return false + } +} diff --git a/internal/k8s/client_test.go b/internal/k8s/client_test.go new file mode 100644 index 0000000..83e032e --- /dev/null +++ b/internal/k8s/client_test.go @@ -0,0 +1,84 @@ +package k8s + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/config" + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/manifest" +) + +func TestResourcePath(t *testing.T) { + cases := []struct { + apiVersion string + kind string + ns string + name string + want string + }{ + {"v1", "Namespace", "", "apps", "/api/v1/namespaces/apps"}, + {"v1", "Service", "default", "web", "/api/v1/namespaces/default/services/web"}, + {"apps/v1", "Deployment", "apps", "web", "/apis/apps/v1/namespaces/apps/deployments/web"}, + {"networking.k8s.io/v1", "Ingress", "apps", "web", "/apis/networking.k8s.io/v1/namespaces/apps/ingresses/web"}, + } + for _, tc := range cases { + got := ResourcePath(tc.apiVersion, tc.kind, tc.ns, tc.name) + if got != tc.want { + t.Errorf("ResourcePath(%q,%q,%q,%q) = %q, want %q", tc.apiVersion, tc.kind, tc.ns, tc.name, got, tc.want) + } + } +} + +func TestExternalApplyServerSidePatch(t *testing.T) { + var gotMethod, gotPath, gotContentType, gotAuth, gotBody string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotMethod = r.Method + gotPath = r.URL.Path + "?" + r.URL.RawQuery + gotContentType = r.Header.Get("Content-Type") + gotAuth = r.Header.Get("Authorization") + b, _ := io.ReadAll(r.Body) + gotBody = string(b) + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"kind":"Service"}`)) + })) + defer srv.Close() + + client, err := NewClient(config.Config{ + KubeMode: "external", + KubeAPIURL: srv.URL, + KubeToken: "test-token", + }) + if err != nil { + t.Fatalf("NewClient error: %v", err) + } + + err = client.Apply(context.Background(), manifest.K8sObject{ + APIVersion: "v1", + Kind: "Service", + Namespace: "default", + Name: "demo", + RawYAML: []byte("apiVersion: v1\nkind: Service\n"), + }) + if err != nil { + t.Fatalf("Apply error: %v", err) + } + if gotMethod != http.MethodPatch { + t.Errorf("method = %s, want PATCH", gotMethod) + } + if !strings.Contains(gotPath, "/api/v1/namespaces/default/services/demo?fieldManager=gitea-k3s-deployer&force=true") { + t.Errorf("unexpected path: %s", gotPath) + } + if gotContentType != "application/apply-patch+yaml" { + t.Errorf("Content-Type = %s", gotContentType) + } + if gotAuth != "Bearer test-token" { + t.Errorf("Authorization = %s", gotAuth) + } + if !strings.Contains(gotBody, "kind: Service") { + t.Errorf("unexpected body: %s", gotBody) + } +} diff --git a/internal/manifest/renderer.go b/internal/manifest/renderer.go new file mode 100644 index 0000000..f119b5a --- /dev/null +++ b/internal/manifest/renderer.go @@ -0,0 +1,423 @@ +package manifest + +import ( + "bytes" + "errors" + "fmt" + "io" + "regexp" + "strings" + + "gopkg.in/yaml.v3" +) + +type ResourceRequirements struct { + Requests ResourceList `yaml:"requests" json:"requests"` + Limits ResourceList `yaml:"limits" json:"limits"` +} + +type ResourceList struct { + CPU string `yaml:"cpu" json:"cpu"` + Memory string `yaml:"memory" json:"memory"` +} + +type DeploySpec struct { + Name string `yaml:"name" json:"name"` + Namespace string `yaml:"namespace" json:"namespace"` + Branch string `yaml:"branch" json:"branch"` + Image string `yaml:"image" json:"image"` + TagStrategy string `yaml:"tagStrategy" json:"tagStrategy"` // sha, latest, release, ref + Port int `yaml:"port" json:"port"` + Host string `yaml:"host" json:"host"` + Replicas int `yaml:"replicas" json:"replicas"` + HealthPath string `yaml:"healthPath" json:"healthPath"` + Env map[string]string `yaml:"env" json:"env"` + SecretRefs []string `yaml:"secretRefs" json:"secretRefs"` + ImagePullSecrets []string `yaml:"imagePullSecrets" json:"imagePullSecrets"` + Resources ResourceRequirements `yaml:"resources" json:"resources"` + ManifestsDir string `yaml:"manifestsDir" json:"manifestsDir"` +} + +type RenderContext struct { + Owner string + RepoName string + Ref string + CommitSHA string + ImageTag string + DefaultImagePullSecret string + DomainSuffix string +} + +type K8sObject struct { + APIVersion string + Kind string + Namespace string + Name string + RawYAML []byte +} + +var nonAlnumDash = regexp.MustCompile(`[^a-z0-9-]+`) + +func SanitizeName(s string) string { + s = strings.ToLower(s) + s = nonAlnumDash.ReplaceAllString(s, "-") + s = strings.Trim(s, "-") + if len(s) > 63 { + s = strings.TrimRight(s[:63], "-") + } + if s == "" { + return "app" + } + return s +} + +func ParseSpec(raw []byte, ctx RenderContext) (DeploySpec, error) { + var spec DeploySpec + if err := yaml.Unmarshal(raw, &spec); err != nil { + return spec, fmt.Errorf("parse .latha-deploy.yaml: %w", err) + } + if spec.Name == "" { + spec.Name = SanitizeName(ctx.RepoName) + } else { + spec.Name = SanitizeName(spec.Name) + } + if spec.Namespace == "" { + spec.Namespace = "default" + } + if spec.Branch == "" { + spec.Branch = "main" + } + if spec.Image == "" { + spec.Image = fmt.Sprintf("git.site.latha.org/%s/%s", ctx.Owner, ctx.RepoName) + } + if spec.Port <= 0 { + spec.Port = 8080 + } + if spec.Replicas <= 0 { + spec.Replicas = 1 + } + if len(spec.ImagePullSecrets) == 0 && ctx.DefaultImagePullSecret != "" { + spec.ImagePullSecrets = []string{ctx.DefaultImagePullSecret} + } + // Enforce non-BestEffort resource defaults for the 7.75 GiB K3s node + if spec.Resources.Requests.CPU == "" { + spec.Resources.Requests.CPU = "50m" + } + if spec.Resources.Requests.Memory == "" { + spec.Resources.Requests.Memory = "64Mi" + } + if spec.Resources.Limits.CPU == "" { + spec.Resources.Limits.CPU = "500m" + } + if spec.Resources.Limits.Memory == "" { + spec.Resources.Limits.Memory = "256Mi" + } + return spec, nil +} + +func ResolveImageTag(spec DeploySpec, ctx RenderContext) string { + if ctx.ImageTag != "" { + return ctx.ImageTag + } + switch spec.TagStrategy { + case "latest": + return "latest" + case "release", "ref": + if ctx.Ref != "" { + return SanitizeName(ctx.Ref) + } + return "latest" + case "sha", "": + if len(ctx.CommitSHA) >= 8 { + return ctx.CommitSHA[:8] + } + if ctx.CommitSHA != "" { + return ctx.CommitSHA + } + return "latest" + default: + return "latest" + } +} + +func RenderFromSpec(spec DeploySpec, ctx RenderContext) ([]byte, error) { + tag := ResolveImageTag(spec, ctx) + fullImage := fmt.Sprintf("%s:%s", spec.Image, tag) + + var docs [][]byte + + if spec.Namespace != "default" && spec.Namespace != "kube-system" { + nsObj := map[string]any{ + "apiVersion": "v1", + "kind": "Namespace", + "metadata": map[string]any{ + "name": spec.Namespace, + "labels": map[string]any{ + "app.kubernetes.io/managed-by": "gitea-k3s-deployer", + }, + }, + } + b, err := yaml.Marshal(nsObj) + if err != nil { + return nil, err + } + docs = append(docs, b) + } + + container := map[string]any{ + "name": spec.Name, + "image": fullImage, + "imagePullPolicy": "Always", + "ports": []map[string]any{ + {"containerPort": spec.Port, "name": "http"}, + }, + "resources": map[string]any{ + "requests": map[string]any{ + "cpu": spec.Resources.Requests.CPU, + "memory": spec.Resources.Requests.Memory, + }, + "limits": map[string]any{ + "cpu": spec.Resources.Limits.CPU, + "memory": spec.Resources.Limits.Memory, + }, + }, + } + + if len(spec.Env) > 0 { + var envList []map[string]any + for k, v := range spec.Env { + envList = append(envList, map[string]any{"name": k, "value": v}) + } + container["env"] = envList + } + + if len(spec.SecretRefs) > 0 { + var envFrom []map[string]any + for _, s := range spec.SecretRefs { + envFrom = append(envFrom, map[string]any{ + "secretRef": map[string]any{"name": s}, + }) + } + container["envFrom"] = envFrom + } + + if spec.HealthPath != "" { + probe := map[string]any{ + "httpGet": map[string]any{ + "path": spec.HealthPath, + "port": "http", + }, + "initialDelaySeconds": 3, + "periodSeconds": 10, + } + container["readinessProbe"] = probe + container["livenessProbe"] = map[string]any{ + "httpGet": map[string]any{ + "path": spec.HealthPath, + "port": "http", + }, + "initialDelaySeconds": 10, + "periodSeconds": 15, + } + } + + podSpec := map[string]any{ + "containers": []map[string]any{container}, + } + if len(spec.ImagePullSecrets) > 0 { + var ips []map[string]any + for _, s := range spec.ImagePullSecrets { + ips = append(ips, map[string]any{"name": s}) + } + podSpec["imagePullSecrets"] = ips + } + + labels := map[string]any{ + "app": spec.Name, + "app.kubernetes.io/managed-by": "gitea-k3s-deployer", + } + + deployObj := map[string]any{ + "apiVersion": "apps/v1", + "kind": "Deployment", + "metadata": map[string]any{ + "name": spec.Name, + "namespace": spec.Namespace, + "labels": labels, + }, + "spec": map[string]any{ + "replicas": spec.Replicas, + "selector": map[string]any{ + "matchLabels": map[string]any{"app": spec.Name}, + }, + "template": map[string]any{ + "metadata": map[string]any{ + "labels": labels, + "annotations": map[string]any{ + "latha.org/commit": ctx.CommitSHA, + "latha.org/ref": ctx.Ref, + }, + }, + "spec": podSpec, + }, + }, + } + b, err := yaml.Marshal(deployObj) + if err != nil { + return nil, err + } + docs = append(docs, b) + + svcObj := map[string]any{ + "apiVersion": "v1", + "kind": "Service", + "metadata": map[string]any{ + "name": spec.Name, + "namespace": spec.Namespace, + "labels": labels, + }, + "spec": map[string]any{ + "selector": map[string]any{"app": spec.Name}, + "ports": []map[string]any{ + { + "port": 80, + "targetPort": "http", + "protocol": "TCP", + }, + }, + }, + } + b, err = yaml.Marshal(svcObj) + if err != nil { + return nil, err + } + docs = append(docs, b) + + if spec.Host != "" { + ingObj := map[string]any{ + "apiVersion": "networking.k8s.io/v1", + "kind": "Ingress", + "metadata": map[string]any{ + "name": spec.Name, + "namespace": spec.Namespace, + "labels": labels, + "annotations": map[string]any{ + "traefik.ingress.kubernetes.io/router.entrypoints": "websecure", + "traefik.ingress.kubernetes.io/router.tls.certresolver": "letsencrypt", + "traefik.ingress.kubernetes.io/router.tls.domains.0.main": spec.Host, + }, + }, + "spec": map[string]any{ + "ingressClassName": "traefik", + "rules": []map[string]any{ + { + "host": spec.Host, + "http": map[string]any{ + "paths": []map[string]any{ + { + "path": "/", + "pathType": "Prefix", + "backend": map[string]any{ + "service": map[string]any{ + "name": spec.Name, + "port": map[string]any{"number": 80}, + }, + }, + }, + }, + }, + }, + }, + }, + } + b, err = yaml.Marshal(ingObj) + if err != nil { + return nil, err + } + docs = append(docs, b) + } + + return bytes.Join(docs, []byte("---\n")), nil +} + +func SubstituteVars(raw []byte, ctx RenderContext) []byte { + shortSHA := ctx.CommitSHA + if len(shortSHA) > 8 { + shortSHA = shortSHA[:8] + } + tag := ctx.ImageTag + if tag == "" { + if shortSHA != "" { + tag = shortSHA + } else { + tag = "latest" + } + } + replacer := strings.NewReplacer( + "${IMAGE_TAG}", tag, + "{{ .Tag }}", tag, + "${COMMIT_SHA}", ctx.CommitSHA, + "${SHORT_SHA}", shortSHA, + "${APP_NAME}", SanitizeName(ctx.RepoName), + "${REF}", ctx.Ref, + ) + return []byte(replacer.Replace(string(raw))) +} + +func SplitYAMLObjects(raw []byte, defaultNamespace string) ([]K8sObject, error) { + dec := yaml.NewDecoder(bytes.NewReader(raw)) + var objs []K8sObject + for { + var doc map[string]any + err := dec.Decode(&doc) + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return nil, fmt.Errorf("decode yaml manifest: %w", err) + } + if len(doc) == 0 { + continue + } + apiVersion, _ := doc["apiVersion"].(string) + kind, _ := doc["kind"].(string) + if apiVersion == "" || kind == "" { + return nil, fmt.Errorf("manifest missing apiVersion or kind") + } + meta, _ := doc["metadata"].(map[string]any) + name, _ := meta["name"].(string) + ns, _ := meta["namespace"].(string) + if name == "" { + return nil, fmt.Errorf("manifest %s/%s missing metadata.name", apiVersion, kind) + } + if ns == "" && !isClusterScoped(kind) { + if defaultNamespace != "" { + ns = defaultNamespace + } else { + ns = "default" + } + meta["namespace"] = ns + } + encoded, err := yaml.Marshal(doc) + if err != nil { + return nil, err + } + objs = append(objs, K8sObject{ + APIVersion: apiVersion, + Kind: kind, + Namespace: ns, + Name: name, + RawYAML: encoded, + }) + } + return objs, nil +} + +func isClusterScoped(kind string) bool { + switch kind { + case "Namespace", "ClusterRole", "ClusterRoleBinding", "PersistentVolume", "StorageClass", "CustomResourceDefinition", "IngressClass": + return true + default: + return false + } +} diff --git a/internal/manifest/renderer_test.go b/internal/manifest/renderer_test.go new file mode 100644 index 0000000..81129fd --- /dev/null +++ b/internal/manifest/renderer_test.go @@ -0,0 +1,78 @@ +package manifest + +import ( + "strings" + "testing" +) + +func TestParseSpecDefaultsAndRender(t *testing.T) { + raw := []byte(` +name: sample-web +namespace: apps +host: sample.site.latha.org +port: 3000 +healthPath: /healthz +env: + LOG_LEVEL: info +`) + ctx := RenderContext{ + Owner: "experiments", + RepoName: "sample-web", + Ref: "main", + CommitSHA: "abcdef1234567890", + DefaultImagePullSecret: "gitea-registry-secret", + } + + spec, err := ParseSpec(raw, ctx) + if err != nil { + t.Fatalf("ParseSpec error: %v", err) + } + if spec.Resources.Requests.CPU != "50m" || spec.Resources.Requests.Memory != "64Mi" { + t.Fatalf("expected non-BestEffort default requests, got %+v", spec.Resources.Requests) + } + if spec.Resources.Limits.CPU != "500m" || spec.Resources.Limits.Memory != "256Mi" { + t.Fatalf("expected default limits, got %+v", spec.Resources.Limits) + } + if spec.Image != "git.site.latha.org/experiments/sample-web" { + t.Fatalf("unexpected default image: %s", spec.Image) + } + + rendered, err := RenderFromSpec(spec, ctx) + if err != nil { + t.Fatalf("RenderFromSpec error: %v", err) + } + s := string(rendered) + for _, want := range []string{ + "kind: Namespace", + "kind: Deployment", + "git.site.latha.org/experiments/sample-web:abcdef12", + "kind: Service", + "kind: Ingress", + "sample.site.latha.org", + "traefik.ingress.kubernetes.io/router.tls.certresolver: letsencrypt", + } { + if !strings.Contains(s, want) { + t.Errorf("rendered YAML missing %q\n%s", want, s) + } + } + + objs, err := SplitYAMLObjects(rendered, spec.Namespace) + if err != nil { + t.Fatalf("SplitYAMLObjects error: %v", err) + } + if len(objs) != 4 { + t.Fatalf("expected 4 k8s objects, got %d", len(objs)) + } +} + +func TestSubstituteVars(t *testing.T) { + raw := []byte("image: git.site.latha.org/experiments/foo:${IMAGE_TAG}\nsha: ${SHORT_SHA}\n") + out := string(SubstituteVars(raw, RenderContext{ + RepoName: "foo", + CommitSHA: "1234567890abcdef", + Ref: "main", + })) + if !strings.Contains(out, ":12345678") || !strings.Contains(out, "sha: 12345678") { + t.Fatalf("unexpected substitution output:\n%s", out) + } +} diff --git a/internal/server/server.go b/internal/server/server.go new file mode 100644 index 0000000..99e2035 --- /dev/null +++ b/internal/server/server.go @@ -0,0 +1,381 @@ +package server + +import ( + "crypto/rand" + "embed" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "net/http" + "strconv" + "strings" + "time" + + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/config" + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/deployer" + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/gitea" + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/k8s" + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/store" +) + +//go:embed web/index.html +var webFS embed.FS + +type Server struct { + cfg config.Config + store *store.Store + svc *deployer.Service + k8s k8s.Applier + mux *http.ServeMux +} + +func New(cfg config.Config, st *store.Store, svc *deployer.Service, ka k8s.Applier) *Server { + s := &Server{ + cfg: cfg, + store: st, + svc: svc, + k8s: ka, + mux: http.NewServeMux(), + } + s.routes() + return s +} + +func (s *Server) Handler() http.Handler { + return s.mux +} + +func (s *Server) routes() { + s.mux.HandleFunc("GET /", s.handleIndex) + s.mux.HandleFunc("GET /healthz", s.handleHealthz) + s.mux.HandleFunc("GET /readyz", s.handleReadyz) + s.mux.HandleFunc("GET /metrics", s.handleMetrics) + + s.mux.HandleFunc("POST /webhook/gitea", s.handleGiteaWebhook) + + s.mux.HandleFunc("GET /api/apps", s.handleListApps) + s.mux.HandleFunc("POST /api/apps", s.handleUpsertApp) + s.mux.HandleFunc("GET /api/deployments", s.handleListDeployments) + s.mux.HandleFunc("GET /api/deployments/{id}", s.handleGetDeployment) + s.mux.HandleFunc("POST /api/deploy", s.handleDeploy) + s.mux.HandleFunc("POST /api/deployments/{id}/rollback", s.handleRollback) + s.mux.HandleFunc("GET /api/webhooks", s.handleListWebhooks) +} + +func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/" { + http.NotFound(w, r) + return + } + b, err := webFS.ReadFile("web/index.html") + if err != nil { + http.Error(w, "dashboard unavailable", http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + _, _ = w.Write(b) +} + +func (s *Server) handleHealthz(w http.ResponseWriter, r *http.Request) { + writeJSON(w, http.StatusOK, map[string]any{ + "status": "ok", + "kube_mode": s.k8s.Mode(), + "gitea_url": s.cfg.GiteaURL, + }) +} + +func (s *Server) handleReadyz(w http.ResponseWriter, r *http.Request) { + writeJSON(w, http.StatusOK, map[string]any{ + "status": "ready", + "kube_mode": s.k8s.Mode(), + }) +} + +func (s *Server) handleMetrics(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/plain; version=0.0.4; charset=utf-8") + fmt.Fprintf(w, "# TYPE deployer_webhooks_total counter\n") + fmt.Fprintf(w, "deployer_webhooks_total %d\n", s.svc.Metrics.WebhooksTotal.Load()) + fmt.Fprintf(w, "# TYPE deployer_webhooks_rejected_total counter\n") + fmt.Fprintf(w, "deployer_webhooks_rejected_total %d\n", s.svc.Metrics.WebhooksRejected.Load()) + fmt.Fprintf(w, "# TYPE deployer_deployments_total counter\n") + fmt.Fprintf(w, "deployer_deployments_total %d\n", s.svc.Metrics.DeploymentsTotal.Load()) + fmt.Fprintf(w, "# TYPE deployer_deployments_succeeded_total counter\n") + fmt.Fprintf(w, "deployer_deployments_succeeded_total %d\n", s.svc.Metrics.DeploymentsSuccess.Load()) + fmt.Fprintf(w, "# TYPE deployer_deployments_failed_total counter\n") + fmt.Fprintf(w, "deployer_deployments_failed_total %d\n", s.svc.Metrics.DeploymentsFailed.Load()) +} + +func (s *Server) handleGiteaWebhook(w http.ResponseWriter, r *http.Request) { + s.svc.Metrics.WebhooksTotal.Add(1) + + body, err := io.ReadAll(io.LimitReader(r.Body, 2<<20)) + if err != nil { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "failed to read body"}) + return + } + + event := r.Header.Get("X-Gitea-Event") + if event == "" { + event = r.Header.Get("X-GitHub-Event") + } + sig := r.Header.Get("X-Gitea-Signature") + sigOK := gitea.VerifySignature(s.cfg.GiteaWebhookSecret, body, sig) + + delivery := store.WebhookDelivery{ + ID: shortID(), + Event: event, + SignatureOK: sigOK, + ReceivedAt: time.Now().UTC(), + } + + if !sigOK { + s.svc.Metrics.WebhooksRejected.Add(1) + delivery.Accepted = false + delivery.Message = "invalid X-Gitea-Signature" + s.store.AddWebhook(delivery) + writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "invalid signature"}) + return + } + + if event == "ping" { + delivery.Accepted = true + delivery.Message = "pong" + s.store.AddWebhook(delivery) + writeJSON(w, http.StatusOK, map[string]string{"status": "pong"}) + return + } + + var req deployer.DeployRequest + switch event { + case "push": + var p gitea.PushEvent + if err := json.Unmarshal(body, &p); err != nil { + delivery.Message = "invalid push payload" + s.store.AddWebhook(delivery) + writeJSON(w, http.StatusBadRequest, map[string]string{"error": delivery.Message}) + return + } + branch := gitea.BranchFromRef(p.Ref) + delivery.Repo = p.Repository.FullName + delivery.Ref = branch + delivery.CommitSHA = p.After + + // Ignore tag pushes on push event (handled by release) or branch deletions + if strings.HasPrefix(p.Ref, "refs/tags/") || p.After == "0000000000000000000000000000000000000000" { + delivery.Accepted = false + delivery.Message = "ignored tag/delete push" + s.store.AddWebhook(delivery) + writeJSON(w, http.StatusOK, map[string]string{"status": "ignored", "reason": delivery.Message}) + return + } + + // Check target branch if app is already registered + targetBranch := p.Repository.DefaultBranch + if targetBranch == "" { + targetBranch = "main" + } + if app, ok := s.store.GetApp(p.Repository.FullName); ok && app.Branch != "" { + targetBranch = app.Branch + } + if branch != targetBranch { + delivery.Accepted = false + delivery.Message = fmt.Sprintf("branch %q != target %q", branch, targetBranch) + s.store.AddWebhook(delivery) + writeJSON(w, http.StatusOK, map[string]string{"status": "ignored", "reason": delivery.Message}) + return + } + + actor := p.Pusher.Username + if actor == "" { + actor = p.Sender.Username + } + req = deployer.DeployRequest{ + Repo: p.Repository.FullName, + Ref: branch, + CommitSHA: p.After, + Trigger: "webhook:push", + Actor: actor, + } + + case "release": + var rel gitea.ReleaseEvent + if err := json.Unmarshal(body, &rel); err != nil { + delivery.Message = "invalid release payload" + s.store.AddWebhook(delivery) + writeJSON(w, http.StatusBadRequest, map[string]string{"error": delivery.Message}) + return + } + delivery.Repo = rel.Repository.FullName + delivery.Ref = rel.Release.TagName + if rel.Action != "published" && rel.Action != "released" { + delivery.Accepted = false + delivery.Message = fmt.Sprintf("ignored release action %q", rel.Action) + s.store.AddWebhook(delivery) + writeJSON(w, http.StatusOK, map[string]string{"status": "ignored", "reason": delivery.Message}) + return + } + req = deployer.DeployRequest{ + Repo: rel.Repository.FullName, + Ref: rel.Release.TagName, + ImageTag: rel.Release.TagName, + Trigger: "webhook:release", + Actor: rel.Sender.Username, + } + + case "workflow_run": + var wf gitea.WorkflowRunEvent + if err := json.Unmarshal(body, &wf); err != nil { + delivery.Message = "invalid workflow_run payload" + s.store.AddWebhook(delivery) + writeJSON(w, http.StatusBadRequest, map[string]string{"error": delivery.Message}) + return + } + delivery.Repo = wf.Repository.FullName + delivery.Ref = wf.WorkflowRun.HeadBranch + delivery.CommitSHA = wf.WorkflowRun.HeadSHA + if wf.Action != "completed" || wf.WorkflowRun.Conclusion != "success" { + delivery.Accepted = false + delivery.Message = fmt.Sprintf("ignored workflow_run (%s/%s)", wf.Action, wf.WorkflowRun.Conclusion) + s.store.AddWebhook(delivery) + writeJSON(w, http.StatusOK, map[string]string{"status": "ignored", "reason": delivery.Message}) + return + } + req = deployer.DeployRequest{ + Repo: wf.Repository.FullName, + Ref: wf.WorkflowRun.HeadBranch, + CommitSHA: wf.WorkflowRun.HeadSHA, + Trigger: "webhook:workflow_run", + Actor: wf.Sender.Username, + } + + default: + delivery.Accepted = false + delivery.Message = fmt.Sprintf("unsupported event %q", event) + s.store.AddWebhook(delivery) + writeJSON(w, http.StatusOK, map[string]string{"status": "ignored", "reason": delivery.Message}) + return + } + + dep, err := s.svc.DeployRepo(r.Context(), req) + if err != nil { + delivery.Accepted = false + delivery.DeploymentID = dep.ID + delivery.Message = err.Error() + s.store.AddWebhook(delivery) + writeJSON(w, http.StatusUnprocessableEntity, map[string]any{ + "status": "failed", + "deployment_id": dep.ID, + "error": err.Error(), + }) + return + } + + delivery.Accepted = true + delivery.DeploymentID = dep.ID + delivery.Message = fmt.Sprintf("deployed %s (%d resources)", dep.AppName, len(dep.AppliedResources)) + s.store.AddWebhook(delivery) + writeJSON(w, http.StatusOK, map[string]any{ + "status": "deployed", + "deployment_id": dep.ID, + "app": dep.AppName, + }) +} + +func (s *Server) handleListApps(w http.ResponseWriter, r *http.Request) { + writeJSON(w, http.StatusOK, map[string]any{"apps": s.store.ListApps()}) +} + +func (s *Server) handleUpsertApp(w http.ResponseWriter, r *http.Request) { + var app store.App + if err := json.NewDecoder(r.Body).Decode(&app); err != nil { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid json"}) + return + } + if app.Repo == "" { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "repo is required"}) + return + } + if app.Branch == "" { + app.Branch = "main" + } + if app.Namespace == "" { + app.Namespace = "default" + } + s.store.UpsertApp(app) + writeJSON(w, http.StatusOK, app) +} + +func (s *Server) handleListDeployments(w http.ResponseWriter, r *http.Request) { + limit := 50 + if v := r.URL.Query().Get("limit"); v != "" { + if n, err := strconv.Atoi(v); err == nil && n > 0 { + limit = n + } + } + writeJSON(w, http.StatusOK, map[string]any{"deployments": s.store.ListDeployments(limit)}) +} + +func (s *Server) handleGetDeployment(w http.ResponseWriter, r *http.Request) { + id := r.PathValue("id") + dep, ok := s.store.GetDeployment(id) + if !ok { + writeJSON(w, http.StatusNotFound, map[string]string{"error": "deployment not found"}) + return + } + writeJSON(w, http.StatusOK, dep) +} + +func (s *Server) handleDeploy(w http.ResponseWriter, r *http.Request) { + var req deployer.DeployRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid json"}) + return + } + if req.Repo == "" { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "repo is required"}) + return + } + dep, err := s.svc.DeployRepo(r.Context(), req) + if err != nil { + writeJSON(w, http.StatusUnprocessableEntity, map[string]any{ + "id": dep.ID, + "status": dep.Status, + "error": err.Error(), + }) + return + } + writeJSON(w, http.StatusOK, dep) +} + +func (s *Server) handleRollback(w http.ResponseWriter, r *http.Request) { + id := r.PathValue("id") + dep, err := s.svc.RollbackDeployment(r.Context(), id, "dashboard") + if err != nil { + writeJSON(w, http.StatusUnprocessableEntity, map[string]string{"error": err.Error()}) + return + } + writeJSON(w, http.StatusOK, dep) +} + +func (s *Server) handleListWebhooks(w http.ResponseWriter, r *http.Request) { + limit := 50 + if v := r.URL.Query().Get("limit"); v != "" { + if n, err := strconv.Atoi(v); err == nil && n > 0 { + limit = n + } + } + writeJSON(w, http.StatusOK, map[string]any{"webhooks": s.store.ListWebhooks(limit)}) +} + +func writeJSON(w http.ResponseWriter, status int, v any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(v) +} + +func shortID() string { + var b [4]byte + _, _ = rand.Read(b[:]) + return hex.EncodeToString(b[:]) +} diff --git a/internal/server/server_test.go b/internal/server/server_test.go new file mode 100644 index 0000000..ddf229e --- /dev/null +++ b/internal/server/server_test.go @@ -0,0 +1,176 @@ +package server + +import ( + "bytes" + "context" + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/config" + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/deployer" + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/gitea" + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/manifest" + "git.site.latha.org/experiments/gitea-k3s-deployer/internal/store" +) + +type fakeGitea struct { + files map[string][]byte + dirs map[string][]gitea.DirEntry +} + +func (f *fakeGitea) GetFile(_ context.Context, owner, repo, path, _ string) ([]byte, error) { + key := owner + "/" + repo + ":" + path + b, ok := f.files[key] + if !ok { + return nil, gitea.ErrNotFound + } + return b, nil +} + +func (f *fakeGitea) ListDir(_ context.Context, owner, repo, path, _ string) ([]gitea.DirEntry, error) { + key := owner + "/" + repo + ":" + path + d, ok := f.dirs[key] + if !ok { + return nil, gitea.ErrNotFound + } + return d, nil +} + +type fakeApplier struct { + applied []manifest.K8sObject +} + +func (f *fakeApplier) Apply(_ context.Context, obj manifest.K8sObject) error { + f.applied = append(f.applied, obj) + return nil +} + +func (f *fakeApplier) Mode() string { return "mock" } + +func signPayload(secret string, body []byte) string { + mac := hmac.New(sha256.New, []byte(secret)) + mac.Write(body) + return hex.EncodeToString(mac.Sum(nil)) +} + +func TestWebhookAndAPIFlow(t *testing.T) { + cfg := config.Config{ + GiteaURL: "https://git.site.latha.org", + GiteaWebhookSecret: "super-secret", + AllowedOwners: []string{"experiments"}, + DefaultImagePullSecret: "gitea-registry-secret", + } + st, err := store.New(filepath.Join(t.TempDir(), "state.json")) + if err != nil { + t.Fatalf("store.New: %v", err) + } + fg := &fakeGitea{ + files: map[string][]byte{ + "experiments/hello-app:.latha-deploy.yaml": []byte("name: hello-app\nnamespace: apps\nhost: hello.site.latha.org\nport: 8080\nhealthPath: /healthz\n"), + "experiments/k8s-app:k8s/deploy.yaml": []byte("apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: k8s-app\nspec:\n replicas: 1\n"), + }, + dirs: map[string][]gitea.DirEntry{ + "experiments/k8s-app:k8s": { + {Name: "deploy.yaml", Path: "k8s/deploy.yaml", Type: "file"}, + }, + }, + } + fa := &fakeApplier{} + svc := deployer.NewService(cfg, st, fg, fa) + srv := New(cfg, st, svc, fa) + ts := httptest.NewServer(srv.Handler()) + defer ts.Close() + + // 1. Invalid signature -> 401 + req, _ := http.NewRequest(http.MethodPost, ts.URL+"/webhook/gitea", strings.NewReader(`{}`)) + req.Header.Set("X-Gitea-Event", "push") + req.Header.Set("X-Gitea-Signature", "bad") + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("post bad sig: %v", err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusUnauthorized { + t.Fatalf("expected 401, got %d", resp.StatusCode) + } + + // 2. Ping event -> 200 + pingBody := []byte(`{"zen":"keep it simple"}`) + req, _ = http.NewRequest(http.MethodPost, ts.URL+"/webhook/gitea", bytes.NewReader(pingBody)) + req.Header.Set("X-Gitea-Event", "ping") + req.Header.Set("X-Gitea-Signature", signPayload(cfg.GiteaWebhookSecret, pingBody)) + resp, err = http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("post ping: %v", err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("expected 200 for ping, got %d", resp.StatusCode) + } + + // 3. Push event -> deploys .latha-deploy.yaml + pushBody := []byte(`{ + "ref": "refs/heads/main", + "after": "deadbeef12345678", + "repository": {"full_name": "experiments/hello-app", "name": "hello-app", "default_branch": "main"}, + "pusher": {"username": "nandi"} + }`) + req, _ = http.NewRequest(http.MethodPost, ts.URL+"/webhook/gitea", bytes.NewReader(pushBody)) + req.Header.Set("X-Gitea-Event", "push") + req.Header.Set("X-Gitea-Signature", signPayload(cfg.GiteaWebhookSecret, pushBody)) + resp, err = http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("post push: %v", err) + } + var pushOut map[string]any + _ = json.NewDecoder(resp.Body).Decode(&pushOut) + resp.Body.Close() + if resp.StatusCode != http.StatusOK || pushOut["status"] != "deployed" { + t.Fatalf("expected deployed, got %d %v", resp.StatusCode, pushOut) + } + if len(fa.applied) != 4 { + t.Fatalf("expected 4 applied k8s objects, got %d", len(fa.applied)) + } + depID := pushOut["deployment_id"].(string) + + // 4. Manual deploy for k8s/ directory repo + manualBody := []byte(`{"repo":"experiments/k8s-app","ref":"main"}`) + resp, err = http.Post(ts.URL+"/api/deploy", "application/json", bytes.NewReader(manualBody)) + if err != nil { + t.Fatalf("post manual deploy: %v", err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("expected 200 manual deploy, got %d", resp.StatusCode) + } + + // 5. Rollback first deployment + resp, err = http.Post(ts.URL+"/api/deployments/"+depID+"/rollback", "application/json", nil) + if err != nil { + t.Fatalf("post rollback: %v", err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("expected 200 rollback, got %d", resp.StatusCode) + } + + // 6. Verify dashboard & metrics + resp, err = http.Get(ts.URL + "/") + if err != nil || resp.StatusCode != http.StatusOK { + t.Fatalf("GET / failed: %v %d", err, resp.StatusCode) + } + resp.Body.Close() + + resp, err = http.Get(ts.URL + "/metrics") + if err != nil || resp.StatusCode != http.StatusOK { + t.Fatalf("GET /metrics failed: %v %d", err, resp.StatusCode) + } + resp.Body.Close() +} diff --git a/internal/server/web/index.html b/internal/server/web/index.html new file mode 100644 index 0000000..1a168f6 --- /dev/null +++ b/internal/server/web/index.html @@ -0,0 +1,265 @@ + + + + + + Gitea -> K3s Deployer + + + +
+
+ Gitea → K3s Deployer + loading... +
+
+ · + +
+
+ +
+
+

Manual Deploy

+
+ + + + +
+
+
+ +
+

Apps 0

+ + + + + +
AppRepoNamespaceHostLast RefStatusAction
No apps deployed yet.
+
+ +
+

Recent Deployments 0

+ + + + + +
IDApp / RepoRef / TagTriggerStatusTimeActions
No deployments yet.
+
+ +
+

Recent Gitea Webhooks 0

+ + + + + +
EventRepoRefSigAcceptedMessageTime
No webhooks received yet.
+
+
+ + + + diff --git a/internal/store/store.go b/internal/store/store.go new file mode 100644 index 0000000..68c7760 --- /dev/null +++ b/internal/store/store.go @@ -0,0 +1,221 @@ +package store + +import ( + "encoding/json" + "os" + "path/filepath" + "sync" + "time" +) + +type DeploymentStatus string + +const ( + StatusPending DeploymentStatus = "pending" + StatusRunning DeploymentStatus = "running" + StatusSucceeded DeploymentStatus = "succeeded" + StatusFailed DeploymentStatus = "failed" +) + +type App struct { + Name string `json:"name"` + Repo string `json:"repo"` // owner/name + Branch string `json:"branch"` + Namespace string `json:"namespace"` + Host string `json:"host,omitempty"` + Image string `json:"image,omitempty"` + LastDeploymentID string `json:"last_deployment_id,omitempty"` + LastStatus string `json:"last_status,omitempty"` + LastRef string `json:"last_ref,omitempty"` + LastCommit string `json:"last_commit,omitempty"` + UpdatedAt time.Time `json:"updated_at"` +} + +type Deployment struct { + ID string `json:"id"` + AppName string `json:"app_name"` + Repo string `json:"repo"` + Ref string `json:"ref"` + CommitSHA string `json:"commit_sha"` + ImageTag string `json:"image_tag"` + Trigger string `json:"trigger"` // webhook:push, webhook:release, manual, rollback + Actor string `json:"actor"` + Namespace string `json:"namespace"` + Status DeploymentStatus `json:"status"` + AppliedResources []string `json:"applied_resources,omitempty"` + RenderedYAML string `json:"rendered_yaml,omitempty"` + Logs []string `json:"logs"` + Error string `json:"error,omitempty"` + StartedAt time.Time `json:"started_at"` + FinishedAt *time.Time `json:"finished_at,omitempty"` +} + +type WebhookDelivery struct { + ID string `json:"id"` + Event string `json:"event"` + Repo string `json:"repo"` + Ref string `json:"ref"` + CommitSHA string `json:"commit_sha,omitempty"` + SignatureOK bool `json:"signature_ok"` + Accepted bool `json:"accepted"` + Message string `json:"message"` + DeploymentID string `json:"deployment_id,omitempty"` + ReceivedAt time.Time `json:"received_at"` +} + +type persistedState struct { + Apps map[string]App `json:"apps"` + Deployments []Deployment `json:"deployments"` + Webhooks []WebhookDelivery `json:"webhooks"` +} + +type Store struct { + mu sync.RWMutex + dataFile string + apps map[string]App + deployments []Deployment + webhooks []WebhookDelivery + maxHistory int +} + +func New(dataFile string) (*Store, error) { + s := &Store{ + dataFile: dataFile, + apps: make(map[string]App), + maxHistory: 200, + } + if dataFile != "" { + if err := s.load(); err != nil && !os.IsNotExist(err) { + return nil, err + } + } + return s, nil +} + +func (s *Store) load() error { + b, err := os.ReadFile(s.dataFile) + if err != nil { + return err + } + var st persistedState + if err := json.Unmarshal(b, &st); err != nil { + return err + } + if st.Apps != nil { + s.apps = st.Apps + } + s.deployments = st.Deployments + s.webhooks = st.Webhooks + return nil +} + +func (s *Store) saveLocked() { + if s.dataFile == "" { + return + } + dir := filepath.Dir(s.dataFile) + _ = os.MkdirAll(dir, 0o755) + st := persistedState{ + Apps: s.apps, + Deployments: s.deployments, + Webhooks: s.webhooks, + } + b, err := json.MarshalIndent(st, "", " ") + if err != nil { + return + } + tmp := s.dataFile + ".tmp" + if err := os.WriteFile(tmp, b, 0o644); err == nil { + _ = os.Rename(tmp, s.dataFile) + } +} + +func (s *Store) UpsertApp(app App) { + s.mu.Lock() + defer s.mu.Unlock() + app.UpdatedAt = time.Now().UTC() + s.apps[app.Repo] = app + s.saveLocked() +} + +func (s *Store) GetApp(repo string) (App, bool) { + s.mu.RLock() + defer s.mu.RUnlock() + a, ok := s.apps[repo] + return a, ok +} + +func (s *Store) ListApps() []App { + s.mu.RLock() + defer s.mu.RUnlock() + out := make([]App, 0, len(s.apps)) + for _, a := range s.apps { + out = append(out, a) + } + return out +} + +func (s *Store) AddDeployment(d Deployment) { + s.mu.Lock() + defer s.mu.Unlock() + s.deployments = append([]Deployment{d}, s.deployments...) + if len(s.deployments) > s.maxHistory { + s.deployments = s.deployments[:s.maxHistory] + } + s.saveLocked() +} + +func (s *Store) UpdateDeployment(d Deployment) { + s.mu.Lock() + defer s.mu.Unlock() + for i := range s.deployments { + if s.deployments[i].ID == d.ID { + s.deployments[i] = d + break + } + } + s.saveLocked() +} + +func (s *Store) GetDeployment(id string) (Deployment, bool) { + s.mu.RLock() + defer s.mu.RUnlock() + for _, d := range s.deployments { + if d.ID == id { + return d, true + } + } + return Deployment{}, false +} + +func (s *Store) ListDeployments(limit int) []Deployment { + s.mu.RLock() + defer s.mu.RUnlock() + if limit <= 0 || limit > len(s.deployments) { + limit = len(s.deployments) + } + out := make([]Deployment, limit) + copy(out, s.deployments[:limit]) + return out +} + +func (s *Store) AddWebhook(w WebhookDelivery) { + s.mu.Lock() + defer s.mu.Unlock() + s.webhooks = append([]WebhookDelivery{w}, s.webhooks...) + if len(s.webhooks) > s.maxHistory { + s.webhooks = s.webhooks[:s.maxHistory] + } + s.saveLocked() +} + +func (s *Store) ListWebhooks(limit int) []WebhookDelivery { + s.mu.RLock() + defer s.mu.RUnlock() + if limit <= 0 || limit > len(s.webhooks) { + limit = len(s.webhooks) + } + out := make([]WebhookDelivery, limit) + copy(out, s.webhooks[:limit]) + return out +}