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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
package clusterkcp
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
kcpv1alpha1 "github.com/kcp-dev/sdk/apis/tenancy/v1alpha1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/rest"
"github.com/johnandersen777/socialweb-computer-kcp/api/v1alpha1"
"github.com/johnandersen777/socialweb-computer-kcp/internal/clusterprovider"
"github.com/johnandersen777/socialweb-computer-kcp/internal/contract/clusterhome"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kcpclient"
"github.com/johnandersen777/socialweb-computer-kcp/internal/materialiser"
)
var (
socialwebResource = v1alpha1.GroupVersion
tenancyResource = kcpv1alpha1.SchemeGroupVersion
)
var _ clusterprovider.Clusters = (*Registry)(nil)
type RegistryOptions struct {
Host string
StateDir string
RestConfig *rest.Config
Transport http.RoundTripper
Account string
}
type Registry struct {
cfg *rest.Config
http *http.Client
codecs runtime.NegotiatedSerializer
stateDir string
account string
}
func NewRegistry(opts RegistryOptions) (*Registry, error) {
if opts.Host == "" {
return nil, errors.New("clusterprovider: Host is required")
}
cfg := &rest.Config{}
if opts.RestConfig != nil {
cfg = rest.CopyConfig(opts.RestConfig)
}
cfg.Host = strings.TrimSuffix(opts.Host, "/")
cfg.ContentType = "application/json"
cfg.AcceptContentTypes = "application/json"
if opts.Transport != nil {
cfg.Transport = opts.Transport
}
httpClient, err := rest.HTTPClientFor(cfg)
if err != nil {
return nil, fmt.Errorf("clusterprovider: %w", err)
}
scheme, err := newScheme()
if err != nil {
return nil, err
}
return &Registry{
cfg: cfg,
http: httpClient,
codecs: serializer.NewCodecFactory(scheme).WithoutConversion(),
stateDir: opts.StateDir,
account: strings.TrimSpace(opts.Account),
}, nil
}
func (r *Registry) Refs(ctx context.Context) ([]clusterprovider.Ref, error) {
accounts, _, err := r.workspaces(ctx, clusterhome.RootWorkspace)
if err != nil {
return nil, err
}
var out []clusterprovider.Ref
for _, account := range accounts {
path := clusterhome.RootWorkspace + ":" + account
if r.account != "" && path != clusterhome.AccountPath(r.account) {
continue
}
homes, deleting, err := r.workspaces(ctx, path)
if apierrors.IsNotFound(err) {
continue
}
if err != nil {
return nil, err
}
for _, home := range homes {
ref := clusterprovider.Ref{Account: path, Home: path + ":" + home}
list, err := r.listClusters(ctx, ref.Home)
if apierrors.IsNotFound(err) || (err != nil && (deleting[home] || r.goneOrDeleting(ctx, path, home))) {
continue
}
if err != nil {
return nil, err
}
for i := range list.Items {
cr := list.Items[i]
out = append(out, clusterprovider.Ref{
Account: path,
DID: cr.Spec.Account,
Home: ref.Home,
Name: cr.Name,
})
}
}
}
return out, nil
}
func (r *Registry) AccountClusters(ctx context.Context, account string) ([]v1alpha1.Cluster, error) {
if r.account != "" && account != clusterhome.AccountPath(r.account) {
return nil, nil
}
homes, deleting, err := r.workspaces(ctx, account)
if apierrors.IsNotFound(err) {
return nil, nil
}
if err != nil {
return nil, err
}
var out []v1alpha1.Cluster
for _, home := range homes {
list, err := r.listClusters(ctx, account+":"+home)
if apierrors.IsNotFound(err) || (err != nil && (deleting[home] || r.goneOrDeleting(ctx, account, home))) {
continue
}
if err != nil {
return nil, err
}
out = append(out, list.Items...)
}
return out, nil
}
func (r *Registry) listClusters(ctx context.Context, home string) (*v1alpha1.ClusterList, error) {
c, err := r.clusters(ctx, home)
if err != nil {
return nil, err
}
var list v1alpha1.ClusterList
if err := c.Get().Resource("clusters").Do(ctx).Into(&list); err != nil {
return nil, fmt.Errorf("clusterprovider: list clusters in %s: %w", home, err)
}
for i := range list.Items {
if list.Items[i].Spec.Account == "" {
return nil, fmt.Errorf(
"clusterprovider: Cluster %s in %s has no spec.account, so no mount path can be derived for it",
list.Items[i].Name, home)
}
}
return &list, nil
}
func (r *Registry) Read(ctx context.Context, ref clusterprovider.Ref) (*v1alpha1.Cluster, error) {
c, err := r.clusters(ctx, ref.Home)
if err != nil {
return nil, err
}
var cl v1alpha1.Cluster
if err := c.Get().Resource("clusters").Name(ref.Name).Do(ctx).Into(&cl); err != nil {
return nil, fmt.Errorf("clusterprovider: read cluster %s in %s: %w", ref.Name, ref.Home, err)
}
return &cl, nil
}
func (r *Registry) Nodes(ctx context.Context, ref clusterprovider.Ref) ([]v1alpha1.Node, error) {
c, err := r.clusters(ctx, ref.Home)
if err != nil {
return nil, err
}
var list v1alpha1.NodeList
if err := c.Get().Resource("nodes").Do(ctx).Into(&list); err != nil {
if apierrors.IsNotFound(err) {
return nil, nil
}
return nil, fmt.Errorf("clusterprovider: list nodes in %s: %w", ref.Home, err)
}
out := make([]v1alpha1.Node, 0, len(list.Items))
for i := range list.Items {
if list.Items[i].Spec.ClusterRef.Name == ref.Name {
out = append(out, list.Items[i])
}
}
return out, nil
}
func (r *Registry) WriteNode(ctx context.Context, ref clusterprovider.Ref, nodeName string, status v1alpha1.NodeStatus) error {
c, err := r.clusters(ctx, ref.Home)
if err != nil {
return err
}
if err := kcpclient.WriteNodeTo(ctx, c, ref.Name, nodeName, status); err != nil {
return fmt.Errorf("clusterprovider: node %s in %s: %w", nodeName, ref.Home, err)
}
return nil
}
func (r *Registry) WriteStatus(ctx context.Context, ref clusterprovider.Ref, st v1alpha1.ClusterStatus) error {
c, err := r.clusters(ctx, ref.Home)
if err != nil {
return err
}
body, err := statusPatch(st)
if err != nil {
return err
}
if err := c.Patch(types.MergePatchType).SubResource("status").Resource("clusters").
Name(ref.Name).Body(body).Do(ctx).Into(&v1alpha1.Cluster{}); err != nil {
return fmt.Errorf("clusterprovider: write status for %s in %s: %w", ref.Name, ref.Home, err)
}
return nil
}
func (r *Registry) RemoveFinalizer(ctx context.Context, ref clusterprovider.Ref) error {
c, err := r.clusters(ctx, ref.Home)
if err != nil {
return err
}
var cl v1alpha1.Cluster
if err := c.Get().Resource("clusters").Name(ref.Name).Do(ctx).Into(&cl); err != nil {
return fmt.Errorf("clusterprovider: reading %s in %s to release its finalizer: %w", ref.Name, ref.Home, err)
}
remaining := make([]string, 0, len(cl.Finalizers))
for _, f := range cl.Finalizers {
if f != v1alpha1.FinalizerCluster {
remaining = append(remaining, f)
}
}
if len(remaining) == len(cl.Finalizers) {
return nil
}
body, err := json.Marshal([]map[string]any{
{"op": "test", "path": "/metadata/finalizers", "value": cl.Finalizers},
{"op": "add", "path": "/metadata/finalizers", "value": remaining},
})
if err != nil {
return fmt.Errorf("clusterprovider: releasing the finalizer of %s: %w", ref.Name, err)
}
if err := c.Patch(types.JSONPatchType).Resource("clusters").Name(ref.Name).
Body(body).Do(ctx).Into(&v1alpha1.Cluster{}); err != nil {
return fmt.Errorf("clusterprovider: releasing the finalizer of %s in %s: %w", ref.Name, ref.Home, err)
}
return nil
}
func (r *Registry) TenantPath(ctx context.Context, ref clusterprovider.Ref) materialiser.PathProbe {
if r.stateDir == "" {
return materialiser.PathProbe{Err: "no cluster state dir to find the tenant front in"}
}
key, err := ref.Key()
if err != nil {
return materialiser.PathProbe{Err: err.Error()}
}
dir, err := clusterprovider.ClusterDataDir(r.stateDir, key)
if err != nil {
return materialiser.PathProbe{Err: err.Error()}
}
return clusterprovider.ProbeTenantFront(ctx, dir)
}
func (r *Registry) IdentityState(ctx context.Context, ref clusterprovider.Ref) (v1alpha1.IdentityState, error) {
c, err := r.resource(ref.Account, socialwebResource)
if err != nil {
return "", err
}
var list v1alpha1.AtprotoIdentityList
if err := c.Get().Resource("atprotoidentities").Do(ctx).Into(&list); err != nil {
if apierrors.IsNotFound(err) {
return "", nil
}
return "", fmt.Errorf("clusterprovider: list identities in %s: %w", ref.Account, err)
}
for i := range list.Items {
if list.Items[i].Spec.Scope != v1alpha1.IdentityScopeAccount {
continue
}
if list.Items[i].Spec.Revoked && list.Items[i].Status.State == "" {
return v1alpha1.IdentityRevocationPending, nil
}
return list.Items[i].Status.State, nil
}
return "", nil
}
func (r *Registry) workspaces(ctx context.Context, logicalCluster string) ([]string, map[string]bool, error) {
c, err := r.resource(logicalCluster, tenancyResource)
if err != nil {
return nil, nil, err
}
var list kcpv1alpha1.WorkspaceList
if err := c.Get().Resource("workspaces").Do(ctx).Into(&list); err != nil {
return nil, nil, fmt.Errorf("clusterprovider: list workspaces in %s: %w", logicalCluster, err)
}
var out []string
deleting := map[string]bool{}
for i := range list.Items {
if list.Items[i].Spec.Mount == nil {
out = append(out, list.Items[i].Name)
deleting[list.Items[i].Name] = list.Items[i].DeletionTimestamp != nil
}
}
return out, deleting, nil
}
func (r *Registry) goneOrDeleting(ctx context.Context, parent, name string) bool {
c, err := r.resource(parent, tenancyResource)
if err != nil {
return false
}
var ws kcpv1alpha1.Workspace
err = c.Get().Resource("workspaces").Name(name).Do(ctx).Into(&ws)
return apierrors.IsNotFound(err) || (err == nil && ws.DeletionTimestamp != nil)
}
func (r *Registry) clusters(ctx context.Context, logicalCluster string) (rest.Interface, error) {
return r.resource(logicalCluster, socialwebResource)
}
func (r *Registry) resource(logicalCluster string, gv schema.GroupVersion) (rest.Interface, error) {
cfg := rest.CopyConfig(r.cfg)
cfg.GroupVersion = &gv
cfg.APIPath = "/clusters/" + logicalCluster + "/apis"
cfg.NegotiatedSerializer = r.codecs
c, err := rest.RESTClientForConfigAndClient(cfg, r.http)
if err != nil {
return nil, fmt.Errorf("clusterprovider: %s: %w", logicalCluster, err)
}
return c, nil
}
func newScheme() (*runtime.Scheme, error) {
s := runtime.NewScheme()
if err := v1alpha1.AddToScheme(s); err != nil {
return nil, fmt.Errorf("clusterprovider: %w", err)
}
if err := kcpv1alpha1.AddToScheme(s); err != nil {
return nil, fmt.Errorf("clusterprovider: %w", err)
}
metav1.AddToGroupVersion(s, schema.GroupVersion{Version: "v1"})
return s, nil
}
type clusterStatusPatch struct {
Phase v1alpha1.ClusterPhase `json:"phase,omitempty"`
URL string `json:"URL,omitempty"`
Instance string `json:"instance,omitempty"`
NodeExpiry *int64 `json:"nodeExpiry"`
Conditions []metav1.Condition `json:"conditions,omitempty"`
}
func statusPatch(st v1alpha1.ClusterStatus) ([]byte, error) {
body, err := json.Marshal(map[string]any{"status": clusterStatusPatch{
Phase: st.Phase,
URL: st.URL,
Instance: st.Instance,
NodeExpiry: st.NodeExpiry,
Conditions: st.Conditions,
}})
if err != nil {
return nil, fmt.Errorf("clusterprovider: status patch: %w", err)
}
return body, nil
}