feat: initial gitea-k3s-deployer service, web UI, tests, and K3s/Depot manifests
Build and Push Image / build (push) Failing after 5s
Build and Push Image / build (push) Failing after 5s
This commit is contained in:
commit
bf229aeed2
23 files changed
+2702
No files matched your search
@@ -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[:])
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Gitea -> K3s Deployer</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #0f1419;
|
||||
--surface: #161d24;
|
||||
--border: #28333e;
|
||||
--text: #e6edf3;
|
||||
--muted: #8b98a5;
|
||||
--accent: #3b82f6;
|
||||
--green: #22c55e;
|
||||
--red: #ef4444;
|
||||
--amber: #f59e0b;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
line-height: 1.45;
|
||||
}
|
||||
header {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 16px 24px;
|
||||
background: var(--surface);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.brand { display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 1.1rem; }
|
||||
.pill {
|
||||
display: inline-block;
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
border: 1px solid var(--border);
|
||||
background: rgba(59, 130, 246, 0.12);
|
||||
color: #93c5fd;
|
||||
}
|
||||
.pill.ok { background: rgba(34, 197, 94, 0.14); color: #86efac; border-color: rgba(34,197,94,0.3); }
|
||||
.pill.err { background: rgba(239, 68, 68, 0.14); color: #fca5a5; border-color: rgba(239,68,68,0.3); }
|
||||
.pill.warn { background: rgba(245, 158, 11, 0.14); color: #fcd34d; border-color: rgba(245,158,11,0.3); }
|
||||
main { max-width: 1200px; margin: 0 auto; padding: 20px; display: grid; gap: 20px; }
|
||||
section {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 16px 20px;
|
||||
overflow-x: auto;
|
||||
}
|
||||
h2 { margin: 0 0 12px; font-size: 1rem; display: flex; align-items: center; justify-content: space-between; }
|
||||
form.deploy-form { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; }
|
||||
input, button {
|
||||
font: inherit;
|
||||
padding: 8px 12px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--border);
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
}
|
||||
input { min-width: 180px; flex: 1; }
|
||||
button {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
color: #fff;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
button.secondary { background: transparent; border-color: var(--border); color: var(--text); }
|
||||
button:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
table { width: 100%; border-collapse: collapse; font-size: 0.875rem; }
|
||||
th, td { text-align: left; padding: 10px 8px; border-bottom: 1px solid var(--border); vertical-align: top; }
|
||||
th { color: var(--muted); font-weight: 600; font-size: 0.78rem; text-transform: uppercase; letter-spacing: 0.04em; }
|
||||
code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.82rem; color: #cbd5e1; }
|
||||
a { color: #60a5fa; text-decoration: none; }
|
||||
a:hover { text-decoration: underline; }
|
||||
.logs {
|
||||
margin-top: 8px;
|
||||
padding: 10px;
|
||||
background: #0b0f14;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size: 0.78rem;
|
||||
white-space: pre-wrap;
|
||||
color: #cbd5e1;
|
||||
max-height: 220px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.muted { color: var(--muted); font-size: 0.82rem; }
|
||||
#toast { font-size: 0.85rem; margin-top: 8px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<div class="brand">
|
||||
<span>Gitea → K3s Deployer</span>
|
||||
<span id="kubeMode" class="pill">loading...</span>
|
||||
</div>
|
||||
<div class="muted">
|
||||
<span id="giteaUrl"></span> ·
|
||||
<button class="secondary" onclick="refreshAll()">Refresh</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<section>
|
||||
<h2>Manual Deploy</h2>
|
||||
<form class="deploy-form" onsubmit="triggerDeploy(event)">
|
||||
<input id="repoInput" placeholder="owner/repo (e.g. experiments/my-app)" required>
|
||||
<input id="refInput" placeholder="branch or tag (default: main)" value="main">
|
||||
<input id="tagInput" placeholder="image tag override (optional)">
|
||||
<button id="deployBtn" type="submit">Deploy to K3s</button>
|
||||
</form>
|
||||
<div id="toast" class="muted"></div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Apps <span id="appsCount" class="pill">0</span></h2>
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>App</th><th>Repo</th><th>Namespace</th><th>Host</th><th>Last Ref</th><th>Status</th><th>Action</th></tr>
|
||||
</thead>
|
||||
<tbody id="appsBody"><tr><td colspan="7" class="muted">No apps deployed yet.</td></tr></tbody>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Recent Deployments <span id="depsCount" class="pill">0</span></h2>
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>ID</th><th>App / Repo</th><th>Ref / Tag</th><th>Trigger</th><th>Status</th><th>Time</th><th>Actions</th></tr>
|
||||
</thead>
|
||||
<tbody id="depsBody"><tr><td colspan="7" class="muted">No deployments yet.</td></tr></tbody>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Recent Gitea Webhooks <span id="hooksCount" class="pill">0</span></h2>
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>Event</th><th>Repo</th><th>Ref</th><th>Sig</th><th>Accepted</th><th>Message</th><th>Time</th></tr>
|
||||
</thead>
|
||||
<tbody id="hooksBody"><tr><td colspan="7" class="muted">No webhooks received yet.</td></tr></tbody>
|
||||
</table>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<script>
|
||||
function statusPill(s) {
|
||||
if (s === 'succeeded' || s === true) return `<span class="pill ok">${s}</span>`;
|
||||
if (s === 'failed' || s === false) return `<span class="pill err">${s}</span>`;
|
||||
return `<span class="pill warn">${s || 'unknown'}</span>`;
|
||||
}
|
||||
|
||||
function esc(str) {
|
||||
return String(str ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
}
|
||||
|
||||
async function refreshAll() {
|
||||
const [statusRes, appsRes, depsRes, hooksRes] = await Promise.all([
|
||||
fetch('/healthz').then(r => r.json()),
|
||||
fetch('/api/apps').then(r => r.json()),
|
||||
fetch('/api/deployments?limit=25').then(r => r.json()),
|
||||
fetch('/api/webhooks?limit=25').then(r => r.json()),
|
||||
]);
|
||||
document.getElementById('kubeMode').textContent = 'kube: ' + (statusRes.kube_mode || 'unknown');
|
||||
document.getElementById('giteaUrl').textContent = statusRes.gitea_url || '';
|
||||
|
||||
const apps = appsRes.apps || [];
|
||||
document.getElementById('appsCount').textContent = apps.length;
|
||||
document.getElementById('appsBody').innerHTML = apps.length ? apps.map(a => `
|
||||
<tr>
|
||||
<td><strong>${esc(a.name)}</strong></td>
|
||||
<td><code>${esc(a.repo)}</code></td>
|
||||
<td><code>${esc(a.namespace)}</code></td>
|
||||
<td>${a.host ? `<a href="https://${esc(a.host)}" target="_blank">${esc(a.host)}</a>` : '<span class="muted">-</span>'}</td>
|
||||
<td><code>${esc(a.last_ref || a.branch)}</code></td>
|
||||
<td>${statusPill(a.last_status)}</td>
|
||||
<td><button class="secondary" onclick="quickDeploy('${esc(a.repo)}','${esc(a.last_ref || a.branch || 'main')}')">Redeploy</button></td>
|
||||
</tr>`).join('') : '<tr><td colspan="7" class="muted">No apps deployed yet.</td></tr>';
|
||||
|
||||
const deps = depsRes.deployments || [];
|
||||
document.getElementById('depsCount').textContent = deps.length;
|
||||
document.getElementById('depsBody').innerHTML = deps.length ? deps.map(d => `
|
||||
<tr>
|
||||
<td><code>${esc(d.id)}</code></td>
|
||||
<td><strong>${esc(d.app_name)}</strong><br><span class="muted">${esc(d.repo)}</span></td>
|
||||
<td><code>${esc(d.ref)}</code>${d.image_tag ? ` <span class="muted">(${esc(d.image_tag)})</span>` : ''}</td>
|
||||
<td><code>${esc(d.trigger)}</code></td>
|
||||
<td>${statusPill(d.status)}</td>
|
||||
<td class="muted">${esc(new Date(d.started_at).toLocaleString())}</td>
|
||||
<td>
|
||||
<button class="secondary" onclick="toggleLogs('log-${esc(d.id)}')">Logs</button>
|
||||
<button class="secondary" onclick="rollback('${esc(d.id)}')">Rollback</button>
|
||||
<div id="log-${esc(d.id)}" class="logs" style="display:none">${esc((d.logs || []).join('\n'))}</div>
|
||||
</td>
|
||||
</tr>`).join('') : '<tr><td colspan="7" class="muted">No deployments yet.</td></tr>';
|
||||
|
||||
const hooks = hooksRes.webhooks || [];
|
||||
document.getElementById('hooksCount').textContent = hooks.length;
|
||||
document.getElementById('hooksBody').innerHTML = hooks.length ? hooks.map(h => `
|
||||
<tr>
|
||||
<td><code>${esc(h.event)}</code></td>
|
||||
<td><code>${esc(h.repo)}</code></td>
|
||||
<td><code>${esc(h.ref)}</code></td>
|
||||
<td>${statusPill(h.signature_ok)}</td>
|
||||
<td>${statusPill(h.accepted)}</td>
|
||||
<td>${esc(h.message)}</td>
|
||||
<td class="muted">${esc(new Date(h.received_at).toLocaleString())}</td>
|
||||
</tr>`).join('') : '<tr><td colspan="7" class="muted">No webhooks received yet.</td></tr>';
|
||||
}
|
||||
|
||||
function toggleLogs(id) {
|
||||
const el = document.getElementById(id);
|
||||
if (el) el.style.display = el.style.display === 'none' ? 'block' : 'none';
|
||||
}
|
||||
|
||||
async function triggerDeploy(e) {
|
||||
e.preventDefault();
|
||||
const repo = document.getElementById('repoInput').value.trim();
|
||||
const ref = document.getElementById('refInput').value.trim() || 'main';
|
||||
const image_tag = document.getElementById('tagInput').value.trim();
|
||||
await runDeploy({ repo, ref, image_tag });
|
||||
}
|
||||
|
||||
async function quickDeploy(repo, ref) {
|
||||
await runDeploy({ repo, ref });
|
||||
}
|
||||
|
||||
async function runDeploy(payload) {
|
||||
const toast = document.getElementById('toast');
|
||||
toast.textContent = `Deploying ${payload.repo}@${payload.ref}...`;
|
||||
const res = await fetch('/api/deploy', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
const data = await res.json();
|
||||
toast.textContent = res.ok ? `Deployment ${data.id}: ${data.status}` : `Error: ${data.error || res.status}`;
|
||||
await refreshAll();
|
||||
}
|
||||
|
||||
async function rollback(id) {
|
||||
const toast = document.getElementById('toast');
|
||||
toast.textContent = `Rolling back to ${id}...`;
|
||||
const res = await fetch(`/api/deployments/${encodeURIComponent(id)}/rollback`, { method: 'POST' });
|
||||
const data = await res.json();
|
||||
toast.textContent = res.ok ? `Rollback ${data.id}: ${data.status}` : `Error: ${data.error || res.status}`;
|
||||
await refreshAll();
|
||||
}
|
||||
|
||||
refreshAll();
|
||||
setInterval(refreshAll, 10000);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in new issue
Block a user