|
| 1 | +// Package kubedb is a thin, dependency-free client for the KubeDB Platform API Server, |
| 2 | +// exposing the subset of endpoints needed to provision databases in Helm editor mode. |
| 3 | +// It is shared by the BMC Helix and ServiceNow provisioning adapters. |
| 4 | +package kubedb |
| 5 | + |
| 6 | +import ( |
| 7 | + "bytes" |
| 8 | + "context" |
| 9 | + "crypto/tls" |
| 10 | + "encoding/base64" |
| 11 | + "encoding/json" |
| 12 | + "fmt" |
| 13 | + "io" |
| 14 | + "net" |
| 15 | + "net/http" |
| 16 | + "strings" |
| 17 | + "time" |
| 18 | +) |
| 19 | + |
| 20 | +const defaultUserAgent = "bytebuilders-client-go" |
| 21 | + |
| 22 | +// Client talks to the KubeDB Platform API using a service-account bearer token. |
| 23 | +type Client struct { |
| 24 | + baseURL string |
| 25 | + token string |
| 26 | + userAgent string |
| 27 | + http *http.Client |
| 28 | +} |
| 29 | + |
| 30 | +// NewClient builds a KubeDB Platform API client. userAgent identifies the caller |
| 31 | +// (e.g. "bmchelix-adapter"); an empty value falls back to a default. |
| 32 | +func NewClient(baseURL, token, userAgent string, timeout time.Duration, insecureSkipTLS bool) *Client { |
| 33 | + if userAgent == "" { |
| 34 | + userAgent = defaultUserAgent |
| 35 | + } |
| 36 | + transport := &http.Transport{ |
| 37 | + TLSClientConfig: &tls.Config{InsecureSkipVerify: insecureSkipTLS}, //nolint:gosec // opt-in dev/test only |
| 38 | + DialContext: (&net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}).DialContext, |
| 39 | + TLSHandshakeTimeout: 10 * time.Second, |
| 40 | + MaxIdleConns: 100, |
| 41 | + IdleConnTimeout: 90 * time.Second, |
| 42 | + } |
| 43 | + return &Client{ |
| 44 | + baseURL: strings.TrimRight(baseURL, "/"), |
| 45 | + token: token, |
| 46 | + userAgent: userAgent, |
| 47 | + http: &http.Client{ |
| 48 | + Timeout: timeout, |
| 49 | + Transport: transport, |
| 50 | + }, |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +// APIError is returned for non-2xx responses from the KubeDB API. |
| 55 | +type APIError struct { |
| 56 | + Method string |
| 57 | + URL string |
| 58 | + StatusCode int |
| 59 | + Body string |
| 60 | +} |
| 61 | + |
| 62 | +func (e *APIError) Error() string { |
| 63 | + return fmt.Sprintf("kubedb api %s %s: status %d: %s", e.Method, e.URL, e.StatusCode, truncate(e.Body, 512)) |
| 64 | +} |
| 65 | + |
| 66 | +// NotFound reports whether the error is a 404 from the KubeDB API. |
| 67 | +func (e *APIError) NotFound() bool { return e.StatusCode == http.StatusNotFound } |
| 68 | + |
| 69 | +// GenerateModel calls PUT /helm/options/model, expanding the given options into a |
| 70 | +// full editor model (returned opaquely). |
| 71 | +func (c *Client) GenerateModel(ctx context.Context, owner, cluster string, req OptionsModelRequest) (EditorModel, error) { |
| 72 | + var model json.RawMessage |
| 73 | + if err := c.do(ctx, http.MethodPut, c.clusterPath(owner, cluster, "/helm/options/model"), req, &model); err != nil { |
| 74 | + return nil, err |
| 75 | + } |
| 76 | + return EditorModel(model), nil |
| 77 | +} |
| 78 | + |
| 79 | +// ApplyEditor calls PUT /helm/editor/, submitting the model as an async apply task. |
| 80 | +func (c *Client) ApplyEditor(ctx context.Context, owner, cluster string, model EditorModel) (*TaskResponse, error) { |
| 81 | + var task TaskResponse |
| 82 | + if err := c.do(ctx, http.MethodPut, c.clusterPath(owner, cluster, "/helm/editor/"), model, &task); err != nil { |
| 83 | + return nil, err |
| 84 | + } |
| 85 | + return &task, nil |
| 86 | +} |
| 87 | + |
| 88 | +// DeleteEditor calls DELETE /helm/editor/, removing the release and companion objects. |
| 89 | +func (c *Client) DeleteEditor(ctx context.Context, owner, cluster string, meta OptionsMetadata) (*TaskResponse, error) { |
| 90 | + var task TaskResponse |
| 91 | + if err := c.do(ctx, http.MethodDelete, c.clusterPath(owner, cluster, "/helm/editor/"), DeleteEditorRequest{Metadata: meta}, &task); err != nil { |
| 92 | + return nil, err |
| 93 | + } |
| 94 | + return &task, nil |
| 95 | +} |
| 96 | + |
| 97 | +// GetResource reads a namespaced CR through the Kubernetes proxy. |
| 98 | +func (c *Client) GetResource(ctx context.Context, owner, cluster, group, version, resource, namespace, name string) (*Unstructured, error) { |
| 99 | + suffix := fmt.Sprintf("/proxy/%s/%s/namespaces/%s/%s/%s", group, version, namespace, resource, name) |
| 100 | + var obj Unstructured |
| 101 | + if err := c.do(ctx, http.MethodGet, c.clusterPath(owner, cluster, suffix), nil, &obj); err != nil { |
| 102 | + return nil, err |
| 103 | + } |
| 104 | + return &obj, nil |
| 105 | +} |
| 106 | + |
| 107 | +// GetSecret reads a namespaced core/v1 Secret through the proxy and returns its |
| 108 | +// decoded (base64) string values. |
| 109 | +func (c *Client) GetSecret(ctx context.Context, owner, cluster, namespace, name string) (map[string]string, error) { |
| 110 | + suffix := fmt.Sprintf("/proxy/core/v1/namespaces/%s/secrets/%s", namespace, name) |
| 111 | + var s Secret |
| 112 | + if err := c.do(ctx, http.MethodGet, c.clusterPath(owner, cluster, suffix), nil, &s); err != nil { |
| 113 | + return nil, err |
| 114 | + } |
| 115 | + out := make(map[string]string, len(s.Data)) |
| 116 | + for k, v := range s.Data { |
| 117 | + if dec, err := base64.StdEncoding.DecodeString(v); err == nil { |
| 118 | + out[k] = string(dec) |
| 119 | + } else { |
| 120 | + out[k] = v |
| 121 | + } |
| 122 | + } |
| 123 | + return out, nil |
| 124 | +} |
| 125 | + |
| 126 | +// AvailableTypes returns the raw JSON of GET /available-types for a cluster. |
| 127 | +func (c *Client) AvailableTypes(ctx context.Context, owner, cluster string) (json.RawMessage, error) { |
| 128 | + var raw json.RawMessage |
| 129 | + if err := c.do(ctx, http.MethodGet, c.clusterPath(owner, cluster, "/available-types"), nil, &raw); err != nil { |
| 130 | + return nil, err |
| 131 | + } |
| 132 | + return raw, nil |
| 133 | +} |
| 134 | + |
| 135 | +func (c *Client) clusterPath(owner, cluster, suffix string) string { |
| 136 | + return fmt.Sprintf("%s/api/v1/clusters/%s/%s%s", c.baseURL, owner, cluster, suffix) |
| 137 | +} |
| 138 | + |
| 139 | +func (c *Client) do(ctx context.Context, method, url string, body, out any) error { |
| 140 | + var reqBody io.Reader |
| 141 | + if body != nil { |
| 142 | + b, err := json.Marshal(body) |
| 143 | + if err != nil { |
| 144 | + return fmt.Errorf("marshal request: %w", err) |
| 145 | + } |
| 146 | + reqBody = bytes.NewReader(b) |
| 147 | + } |
| 148 | + |
| 149 | + req, err := http.NewRequestWithContext(ctx, method, url, reqBody) |
| 150 | + if err != nil { |
| 151 | + return err |
| 152 | + } |
| 153 | + req.Header.Set("Authorization", "token "+c.token) |
| 154 | + req.Header.Set("Accept", "application/json") |
| 155 | + req.Header.Set("User-Agent", c.userAgent) |
| 156 | + if body != nil { |
| 157 | + req.Header.Set("Content-Type", "application/json") |
| 158 | + } |
| 159 | + |
| 160 | + resp, err := c.http.Do(req) |
| 161 | + if err != nil { |
| 162 | + return fmt.Errorf("%s %s: %w", method, url, err) |
| 163 | + } |
| 164 | + defer resp.Body.Close() |
| 165 | + |
| 166 | + data, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20)) |
| 167 | + if err != nil { |
| 168 | + return fmt.Errorf("read response: %w", err) |
| 169 | + } |
| 170 | + if resp.StatusCode < 200 || resp.StatusCode >= 300 { |
| 171 | + return &APIError{Method: method, URL: url, StatusCode: resp.StatusCode, Body: string(data)} |
| 172 | + } |
| 173 | + if out != nil && len(data) > 0 { |
| 174 | + if err := json.Unmarshal(data, out); err != nil { |
| 175 | + return fmt.Errorf("decode response: %w", err) |
| 176 | + } |
| 177 | + } |
| 178 | + return nil |
| 179 | +} |
| 180 | + |
| 181 | +func truncate(s string, n int) string { |
| 182 | + if len(s) <= n { |
| 183 | + return s |
| 184 | + } |
| 185 | + return s[:n] + "…" |
| 186 | +} |
0 commit comments