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 } }