1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package kube
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/kcprest"
)
type Doc = map[string]any
type Client struct {
dyn dynamic.Interface
}
func New(cfg *rest.Config) (*Client, error) {
if cfg == nil {
return nil, errors.New("kube: a rest config is required")
}
dyn, err := dynamic.NewForConfig(cfg)
if err != nil {
return nil, fmt.Errorf("kube: the client for %s: %w", cfg.Host, err)
}
return &Client{dyn: dyn}, nil
}
func ForWorkspace(base *rest.Config, workspace string) (*Client, error) {
if base == nil {
return nil, errors.New("kube: a rest config is required")
}
return New(kcprest.ForCluster(base, workspace))
}
type Factory func(workspace string) (*Client, error)
func NewFactory(base *rest.Config) Factory {
return func(workspace string) (*Client, error) { return ForWorkspace(base, workspace) }
}
type Resource struct {
ri dynamic.NamespaceableResourceInterface
gvr schema.GroupVersionResource
ns string
}
func (c *Client) Resource(gvr schema.GroupVersionResource) Resource {
if c == nil || c.dyn == nil {
return Resource{gvr: gvr}
}
return Resource{ri: c.dyn.Resource(gvr), gvr: gvr}
}
func (r Resource) In(namespace string) Resource {
r.ns = namespace
return r
}
func (r Resource) GVR() schema.GroupVersionResource { return r.gvr }
func (r Resource) Namespace() string { return r.ns }
func (r Resource) iface() (dynamic.ResourceInterface, error) {
if r.ri == nil {
return nil, fmt.Errorf("kube: %s has no client", r.gvr.Resource)
}
if r.ns != "" {
return r.ri.Namespace(r.ns), nil
}
return r.ri, nil
}
type ApplyOptions struct {
FieldManager string
Force bool
Status bool
DryRun []string
}
func Get[T any](ctx context.Context, r Resource, name string) (*T, error) {
ri, err := r.iface()
if err != nil {
return nil, err
}
u, err := ri.Get(ctx, name, metav1.GetOptions{})
if err != nil {
return nil, err
}
return Decode[T](u.Object)
}
func List[T any](ctx context.Context, r Resource, opts metav1.ListOptions) ([]T, error) {
ri, err := r.iface()
if err != nil {
return nil, err
}
l, err := ri.List(ctx, opts)
if err != nil {
return nil, err
}
out := make([]T, 0, len(l.Items))
for i := range l.Items {
v, err := Decode[T](l.Items[i].Object)
if err != nil {
return nil, err
}
out = append(out, *v)
}
return out, nil
}
func Create[T any](ctx context.Context, r Resource, obj any, opts metav1.CreateOptions) (*T, error) {
ri, u, err := r.prepare(obj)
if err != nil {
return nil, err
}
got, err := ri.Create(ctx, u, opts)
if err != nil {
return nil, err
}
return Decode[T](got.Object)
}
func Update[T any](ctx context.Context, r Resource, obj any, opts metav1.UpdateOptions) (*T, error) {
ri, u, err := r.prepare(obj)
if err != nil {
return nil, err
}
got, err := ri.Update(ctx, u, opts)
if err != nil {
return nil, err
}
return Decode[T](got.Object)
}
func UpdateStatus[T any](ctx context.Context, r Resource, obj any, opts metav1.UpdateOptions) (*T, error) {
ri, u, err := r.prepare(obj)
if err != nil {
return nil, err
}
got, err := ri.UpdateStatus(ctx, u, opts)
if err != nil {
return nil, err
}
return Decode[T](got.Object)
}
func Apply[T any](ctx context.Context, r Resource, obj any, o ApplyOptions) (*T, error) {
ri, err := r.iface()
if err != nil {
return nil, err
}
doc, err := ApplyBody(obj, o.Status)
if err != nil {
return nil, err
}
name, _, _ := unstructured.NestedString(doc, "metadata", "name")
if strings.TrimSpace(name) == "" {
return nil, fmt.Errorf("kube: applying %s: the object has no name", r.gvr.Resource)
}
body, err := json.Marshal(doc)
if err != nil {
return nil, fmt.Errorf("kube: encoding %s %s: %w", r.gvr.Resource, name, err)
}
opts := metav1.PatchOptions{FieldManager: o.FieldManager, DryRun: o.DryRun}
if o.Force {
opts.Force = new(true)
}
var sub []string
if o.Status {
sub = []string{"status"}
}
got, err := ri.Patch(ctx, name, types.ApplyPatchType, body, opts, sub...)
if err != nil {
return nil, err
}
return Decode[T](got.Object)
}
func Patch[T any](ctx context.Context, r Resource, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (*T, error) {
ri, err := r.iface()
if err != nil {
return nil, err
}
got, err := ri.Patch(ctx, name, pt, data, opts, subresources...)
if err != nil {
return nil, err
}
return Decode[T](got.Object)
}
func (r Resource) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {
ri, err := r.iface()
if err != nil {
return err
}
return ri.Delete(ctx, name, opts)
}
func (r Resource) prepare(obj any) (dynamic.ResourceInterface, *unstructured.Unstructured, error) {
ri, err := r.iface()
if err != nil {
return nil, nil, err
}
doc, err := Encode(obj)
if err != nil {
return nil, nil, err
}
return ri, &unstructured.Unstructured{Object: doc}, nil
}
func ApplyBody(obj any, status bool) (Doc, error) {
if d, ok := asDoc(obj); ok {
av, _ := d["apiVersion"].(string)
kind, _ := d["kind"].(string)
if av == "" || kind == "" {
return nil, errors.New("kube: an applied document needs apiVersion and kind")
}
return d, nil
}
full, err := Encode(obj)
if err != nil {
return nil, err
}
meta, _ := full["metadata"].(map[string]any)
out := Doc{"apiVersion": full["apiVersion"], "kind": full["kind"]}
skeleton := map[string]any{}
keys := []string{"name", "namespace"}
if !status {
keys = append(keys, "labels", "annotations", "ownerReferences", "finalizers")
}
for _, k := range keys {
if v, ok := meta[k]; ok && v != nil {
skeleton[k] = v
}
}
out["metadata"] = skeleton
if status {
st, _ := full["status"].(map[string]any)
if st == nil {
st = map[string]any{}
}
out["status"] = st
return out, nil
}
for k, v := range full {
if k != "apiVersion" && k != "kind" && k != "metadata" && k != "status" {
out[k] = v
}
}
return out, nil
}
func ApplyWith(ctx context.Context, cl client.Client, obj any, o ApplyOptions) error {
if cl == nil {
return errors.New("kube: applying needs a client")
}
doc, err := ApplyBody(obj, o.Status)
if err != nil {
return err
}
ac := client.ApplyConfigurationFromUnstructured(&unstructured.Unstructured{Object: doc})
if o.Status {
opts := []client.SubResourceApplyOption{client.FieldOwner(o.FieldManager)}
if o.Force {
opts = append(opts, client.ForceOwnership)
}
return cl.Status().Apply(ctx, ac, opts...)
}
opts := []client.ApplyOption{client.FieldOwner(o.FieldManager)}
if o.Force {
opts = append(opts, client.ForceOwnership)
}
if len(o.DryRun) > 0 {
opts = append(opts, client.DryRunAll)
}
return cl.Apply(ctx, ac, opts...)
}