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
package guestcontrolplane
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"strings"
"sync"
"time"
"k8s.io/utils/ptr"
"github.com/johnandersen777/socialweb-computer-kcp/api/v1alpha1"
"github.com/johnandersen777/socialweb-computer-kcp/internal/atproto/ingress"
reporemote "github.com/johnandersen777/socialweb-computer-kcp/internal/atprotorepo/remote"
"github.com/johnandersen777/socialweb-computer-kcp/internal/bus"
"github.com/johnandersen777/socialweb-computer-kcp/internal/component"
"github.com/johnandersen777/socialweb-computer-kcp/internal/contract/guestcp"
guestplane "github.com/johnandersen777/socialweb-computer-kcp/internal/guestcp/openbao"
guestrelay "github.com/johnandersen777/socialweb-computer-kcp/internal/guestcp/relay"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/kcp"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/pinneddownloads"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/supervise"
)
type Service struct {
spec v1alpha1.GuestControlPlaneSpec
deps Deps
log *slog.Logger
trust *component.Trust
stateDir string
grantSync time.Duration
issuerRetry time.Duration
downloads *pinneddownloads.Set
mu sync.Mutex
started bool
registered bool
readiness component.ReadySignal
mux *http.ServeMux
cancel context.CancelFunc
wg sync.WaitGroup
stopOnce sync.Once
stopErr error
cleanupMu sync.Mutex
plane *guestplane.Plane
relay *guestrelay.Relay
queue guestcp.Queue
unwatchQueue func()
}
func (s *Service) Start(ctx context.Context) error {
runCtx, cancel := context.WithCancel(ctx)
s.mu.Lock()
if s.started {
s.mu.Unlock()
cancel()
return errors.New("guestcontrolplane: the service is already started")
}
s.started = true
s.cancel = cancel
s.mu.Unlock()
defer s.shutdown(ctx)
stopTrust, err := s.trust.Follow(runCtx, s.deps.Instance)
if err != nil {
cancel()
return err
}
defer stopTrust()
if err := s.prepare(runCtx); err != nil {
cancel()
return err
}
s.mu.Lock()
plane := s.plane
s.mu.Unlock()
if plane.Ready() != nil {
s.readiness.Fail(errors.New("guestcontrolplane: the guest identity proxy is not configured"))
} else {
s.readiness.Signal()
}
<-runCtx.Done()
return nil
}
func (s *Service) Ready() component.Readiness {
return &s.readiness
}
func (s *Service) Endpoints() []component.Endpoint {
s.mu.Lock()
registered := s.registered
plane := s.plane
s.mu.Unlock()
if !registered {
return nil
}
out := []component.Endpoint{{Name: "http", Protocol: component.ProtocolHTTP, URL: s.logicalURL()}}
if raw := s.relayURL(); raw != "" {
protocol := component.ProtocolHTTPS
if strings.HasPrefix(raw, "http://") {
protocol = component.ProtocolHTTP
}
out = append(out, component.Endpoint{Name: "relay", Protocol: protocol, URL: raw})
}
if plane != nil {
if issuer := plane.OIDCIssuer(); issuer != "" {
out = append(out, component.Endpoint{Name: "issuer", Protocol: component.ProtocolHTTPS, URL: issuer})
}
}
return out
}
func (s *Service) Stop(ctx context.Context) error {
return s.shutdownWith(ctx)
}
func (s *Service) shutdown(ctx context.Context) error {
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), component.DefaultStopTimeout)
defer cancel()
return s.shutdownWith(ctx)
}
func (s *Service) shutdownWith(ctx context.Context) error {
s.stopOnce.Do(func() {
s.cleanupMu.Lock()
defer s.cleanupMu.Unlock()
s.mu.Lock()
cancel := s.cancel
relay := s.relay
plane := s.plane
unwatchQueue := s.unwatchQueue
s.started = false
s.registered = false
s.mu.Unlock()
if cancel != nil {
cancel()
}
if unwatchQueue != nil {
unwatchQueue()
}
if relay != nil {
relay.Close()
}
if plane != nil {
plane.Close()
}
if err := supervise.Join(ctx, s.wg.Wait); err != nil && s.stopErr == nil {
s.stopErr = err
}
})
return s.stopErr
}
func (s *Service) prepare(ctx context.Context) error {
if s.stateDir != "" {
if err := os.MkdirAll(s.stateDir, 0o700); err != nil {
return fmt.Errorf("guestcontrolplane: creating the state dir: %w", err)
}
}
if s.deps.Bus == nil {
return errors.New("guestcontrolplane: the handler registry is not available")
}
inputs, guests, grants, err := s.handles(ctx)
if err != nil {
return err
}
plane, err := guestplane.New(guestplane.Config{
Handle: s.handle(),
DID: s.did(),
Mount: s.spec.GuestLoginMount,
Timeout: DefaultOpenBaoTimeout,
GrantSync: s.grantSync,
IssuerRetry: s.issuerRetry,
HostKeyAttempts: int(ptr.Deref(s.spec.HostKeyAttempts, 0)),
}, guestplane.Deps{
Inputs: inputs,
Guests: guests,
Grants: grants,
RBAC: reporemote.NewNetwork(reporemote.NetworkConfig{Directory: ingress.NewDirectory(s.network().PLCDirectoryURL),
HTTP: networkHTTPClient(s.deps.Hosts, s.network(), s.trust, DefaultOpenBaoTimeout)}),
FallbackIssuer: s.relayURL,
Publish: s.publishGuestEvent,
Log: s.log,
})
if err != nil {
return err
}
if err := plane.Start(ctx); err != nil {
return err
}
s.mu.Lock()
s.plane = plane
s.mu.Unlock()
if err := s.openQueue(ctx, inputs); err != nil {
s.log.Warn("the guest event queue is not open; guest events are refused", "err", err)
}
s.mux = s.routes()
if err := s.register(); err != nil {
return err
}
if err := s.startRelay(ctx, plane); err != nil {
s.log.Warn("the guest relay did not start", "err", err)
}
s.log.Info("the guest control plane serves guests", "handler", s.logicalURL(), "handle", s.handle(),
"issuer", plane.IssuerURL(), "mount", s.spec.GuestLoginMount, "downloads", len(s.downloads.List()))
return nil
}
func (s *Service) handles(ctx context.Context) (guestcp.Source, guestcp.Guests, guestcp.Grants, error) {
self := s.self()
ctx = bus.WithCallerLabels(ctx, self, s.deps.Labels)
inputs, err := bus.Resolve[guestcp.Source](ctx, s.deps.Bus, self, self, bus.Capability{Name: guestcp.CapabilityInputs})
if err != nil {
return nil, nil, nil, fmt.Errorf("guestcontrolplane: resolving the guest inputs: %w", err)
}
guests, err := bus.Resolve[guestcp.Guests](ctx, s.deps.Bus, self, self, bus.Capability{Name: guestcp.CapabilityGuests})
if err != nil {
return nil, nil, nil, fmt.Errorf("guestcontrolplane: resolving the guest report writer: %w", err)
}
grants, err := bus.Resolve[guestcp.Grants](ctx, s.deps.Bus, self, self, bus.Capability{Name: guestcp.CapabilityGrants})
if err != nil {
return nil, nil, nil, fmt.Errorf("guestcontrolplane: resolving the grant writer: %w", err)
}
return inputs, guests, grants, nil
}
func (s *Service) startRelay(ctx context.Context, plane *guestplane.Plane) error {
if !ptr.Deref(s.spec.RelayEnabled, false) {
return nil
}
target, err := s.pdsRef()
if err != nil {
return err
}
keyFile := ""
if s.stateDir != "" {
keyFile = s.stateDir + "/guest-relay.jwk"
}
relay, err := guestrelay.New(guestrelay.Config{
Label: "guest-" + s.spec.Role,
KeyFile: keyFile,
IngressProxyHost: s.relayHost(),
TLS: s.relayTLS(),
}, guestrelay.Deps{
Handler: s.mux,
Subscribe: s.subscribeDirect(ctx),
ServiceAuth: busServiceAuth{bus: s.deps.Bus, self: s.self(), labels: s.deps.Labels, pds: target},
DID: plane.DID,
Log: s.log,
})
if err != nil {
return err
}
s.mu.Lock()
s.relay = relay
s.mu.Unlock()
s.wg.Go(func() {
if err := relay.Run(ctx, plane.Recheck); err != nil && ctx.Err() == nil {
s.log.Warn("the guest relay did not start", "err", err)
}
})
return nil
}
func (s *Service) relayURL() string {
s.mu.Lock()
relay := s.relay
s.mu.Unlock()
if relay == nil {
return ""
}
return relay.URL()
}
func (s *Service) register() error {
key := component.Key{Workspace: s.workspace(), Kind: Kind, Name: s.deps.Self.Name}
if err := s.deps.Bus.RegisterHTTP(key, s.mux); err != nil {
return err
}
s.mu.Lock()
s.registered = true
s.mu.Unlock()
return nil
}
func (s *Service) logicalURL() string {
return kcp.HandlerURL(s.workspace(), Kind, s.deps.Self.Name)
}
var _ component.Service = (*Service)(nil)