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,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
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user