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
package controller
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"sync"
"time"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
policyv1alpha1 "github.com/johnandersen777/socialweb-computer-kcp/api/policy/v1alpha1"
"github.com/johnandersen777/socialweb-computer-kcp/internal/contract/sandbox"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/opt"
policyengine "github.com/johnandersen777/socialweb-computer-kcp/internal/policyengine/status"
)
type EngineFactory func(ctx context.Context, engine *policyv1alpha1.PolicyEngine) (*Engine, error)
type managedEngine struct {
engine *Engine
hash string
fence *sandbox.Fence
}
type EngineManager struct {
mu sync.Mutex
factory EngineFactory
engines map[string]*managedEngine
failed map[string]string
}
func NewEngineManager(factory EngineFactory) *EngineManager {
return &EngineManager{factory: factory, engines: make(map[string]*managedEngine), failed: make(map[string]string)}
}
func NewDefaultEngineFactory(base Config) EngineFactory {
return func(ctx context.Context, engineCR *policyv1alpha1.PolicyEngine) (*Engine, error) {
config := EngineConfigFromCR(engineCR, base)
var spec *policyv1alpha1.PolicySandboxConfig
if engineCR != nil {
spec = engineCR.Spec.Sandbox
}
switch {
case base.OpenSandbox != nil:
runner, err := base.OpenSandbox(ctx, spec)
if err != nil {
return nil, fmt.Errorf("opening the %s policy sandbox: %w", spec.ProviderName(), err)
}
config.Sandbox = runner
case spec.ProviderName() != policyv1alpha1.PolicySandboxProviderDeno:
return nil, fmt.Errorf("the %s policy sandbox is not available on this host", spec.ProviderName())
}
return NewEngine(config), nil
}
}
func probeFence(ctx context.Context, runner sandbox.Runner) *sandbox.Fence {
prober, ok := runner.(sandbox.Prober)
if !ok {
return nil
}
if !runner.Available() {
return &sandbox.Fence{Reason: policyv1alpha1.PolicyEngineFencedNotProbed, Message: fmt.Sprintf("the %s sandbox runtime is unavailable", runner.Kind())}
}
fence, err := prober.Probe(ctx)
if err != nil {
return &sandbox.Fence{Reason: policyv1alpha1.PolicyEngineFencedProbeFailed, Message: err.Error()}
}
if fence.Reason == "" {
fence.Reason = policyv1alpha1.PolicyEngineFencedProbeFailed
if fence.Fenced {
fence.Reason = policyv1alpha1.PolicyEngineFencedProbePassed
}
}
return &fence
}
func (m *EngineManager) ReconcilePolicyEngine(ctx context.Context, key string, engineCR *policyv1alpha1.PolicyEngine) (EngineReconcileState, error) {
if engineCR == nil {
return EngineReconcileState{}, fmt.Errorf("policy engine is required")
}
if engineCR.DeletionTimestamp != nil {
m.stop(ctx, key)
state := EngineReconcileState{Phase: policyv1alpha1.PolicyEnginePending}
meta.SetStatusCondition(&state.Conditions, metav1.Condition{
Type: policyengine.ConditionReady,
Status: metav1.ConditionFalse,
Reason: "Terminating",
Message: "the policy engine is being deleted",
})
return state, nil
}
if engineCR.Spec.Suspend {
m.stop(ctx, key)
state := EngineReconcileState{Phase: policyv1alpha1.PolicyEnginePending}
meta.SetStatusCondition(&state.Conditions, metav1.Condition{
Type: policyengine.ConditionSuspended,
Status: metav1.ConditionTrue,
Reason: "Suspended",
Message: "the policy engine is suspended",
})
return state, nil
}
spec, err := json.Marshal(engineCR.Spec)
if err != nil {
return EngineReconcileState{}, err
}
hash := string(spec)
m.mu.Lock()
managed := m.engines[key]
if managed == nil || managed.hash != hash {
m.mu.Unlock()
m.stop(ctx, key)
if m.factory == nil {
return EngineReconcileState{Phase: policyv1alpha1.PolicyEngineFailed}, fmt.Errorf("policy engine factory is not configured")
}
engine, factoryErr := m.factory(ctx, engineCR)
if factoryErr != nil {
m.mu.Lock()
m.failed[key] = factoryErr.Error()
m.mu.Unlock()
state := EngineReconcileState{Phase: policyv1alpha1.PolicyEngineFailed}
meta.SetStatusCondition(&state.Conditions, metav1.Condition{
Type: policyengine.ConditionReady,
Status: metav1.ConditionFalse,
Reason: "CreateFailed",
Message: factoryErr.Error(),
})
return state, factoryErr
}
if engine == nil {
return EngineReconcileState{Phase: policyv1alpha1.PolicyEngineFailed}, fmt.Errorf("policy engine factory returned nil")
}
if startErr := engine.Start(context.WithoutCancel(ctx)); startErr != nil {
return EngineReconcileState{Phase: policyv1alpha1.PolicyEngineFailed}, startErr
}
fence := probeFence(ctx, engine.Sandbox())
m.mu.Lock()
delete(m.failed, key)
m.engines[key] = &managedEngine{engine: engine, hash: hash, fence: fence}
managed = m.engines[key]
stored := *managed
m.mu.Unlock()
return reconcileState(&stored), nil
}
stored := *managed
m.mu.Unlock()
return reconcileState(&stored), nil
}
func reconcileState(managed *managedEngine) EngineReconcileState {
state := EngineReconcileState{ActiveRuns: managed.engine.ActiveRuns()}
if fence := managed.fence; fence != nil {
status := metav1.ConditionFalse
if fence.Fenced {
status = metav1.ConditionTrue
}
meta.SetStatusCondition(&state.Conditions, metav1.Condition{
Type: policyv1alpha1.PolicyEngineConditionFenced,
Status: status,
Reason: fence.Reason,
Message: fence.Message,
})
}
if managed.engine.Ready() {
state.Phase = policyv1alpha1.PolicyEngineRunning
state.Ready = true
meta.SetStatusCondition(&state.Conditions, metav1.Condition{
Type: policyengine.ConditionReady,
Status: metav1.ConditionTrue,
Reason: "Ready",
Message: "the in-process policy engine is ready",
})
return state
}
state.Phase = policyv1alpha1.PolicyEnginePending
notReady := metav1.Condition{
Type: policyengine.ConditionReady,
Status: metav1.ConditionFalse,
Reason: "RuntimeUnavailable",
Message: "the embedded or system deno runtime is unavailable",
}
if fence := managed.fence; fence != nil {
notReady.Message = fmt.Sprintf("the %s sandbox runtime is unavailable", managed.engine.Sandbox().Kind())
if !fence.Fenced {
notReady.Reason = fence.Reason
notReady.Message = fence.Message
}
}
meta.SetStatusCondition(&state.Conditions, notReady)
return state
}
func (m *EngineManager) EngineFor(name string) (*Engine, bool) {
m.mu.Lock()
defer m.mu.Unlock()
managed, ok := m.engines[name]
if !ok {
return nil, false
}
return managed.engine, true
}
func (m *EngineManager) Only(prefix string) (*Engine, bool) {
m.mu.Lock()
defer m.mu.Unlock()
var found *Engine
for key, managed := range m.engines {
if !strings.HasPrefix(key, prefix) {
continue
}
if found != nil {
return nil, false
}
found = managed.engine
}
return found, found != nil
}
func (m *EngineManager) Shutdown(ctx context.Context) error {
m.mu.Lock()
engines := make([]*Engine, 0, len(m.engines))
for name, managed := range m.engines {
engines = append(engines, managed.engine)
delete(m.engines, name)
}
m.mu.Unlock()
var errs []error
for _, engine := range engines {
if err := engine.Shutdown(ctx); err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}
func (m *EngineManager) Delete(ctx context.Context, name string) error {
m.mu.Lock()
managed := m.engines[name]
delete(m.engines, name)
delete(m.failed, name)
m.mu.Unlock()
if managed == nil {
return nil
}
shutdownCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
return managed.engine.Shutdown(shutdownCtx)
}
func (m *EngineManager) NotReady(key string) (string, bool) {
m.mu.Lock()
defer m.mu.Unlock()
if message, ok := m.failed[key]; ok {
return "the policy engine could not be created: " + message, true
}
if managed, ok := m.engines[key]; ok {
return managed.notReady()
}
return "", false
}
func (m *EngineManager) OnlyNotReady(prefix string) (string, bool) {
m.mu.Lock()
keys := map[string]struct{}{}
for key := range m.engines {
if strings.HasPrefix(key, prefix) {
keys[key] = struct{}{}
}
}
for key := range m.failed {
if strings.HasPrefix(key, prefix) {
keys[key] = struct{}{}
}
}
m.mu.Unlock()
if len(keys) != 1 {
return "", false
}
for key := range keys {
return m.NotReady(key)
}
return "", false
}
func (managed *managedEngine) notReady() (string, bool) {
runner := managed.engine.Sandbox()
switch {
case managed.engine.Ready():
return "", false
case runner == nil:
return "the policy engine has no sandbox runner", true
case !runner.Available():
return fmt.Sprintf("the %s policy sandbox runtime is unavailable", runner.Kind()), true
case managed.fence != nil && !managed.fence.Fenced:
return fmt.Sprintf("the %s policy sandbox is not fenced (%s): %s", runner.Kind(), managed.fence.Reason, managed.fence.Message), true
default:
return fmt.Sprintf("the %s policy sandbox is not fenced", runner.Kind()), true
}
}
func (m *EngineManager) stop(ctx context.Context, name string) {
m.mu.Lock()
managed := m.engines[name]
delete(m.engines, name)
delete(m.failed, name)
m.mu.Unlock()
if managed == nil {
return
}
shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
defer cancel()
managed.engine.Shutdown(shutdownCtx)
}
func EngineConfigFromCR(engineCR *policyv1alpha1.PolicyEngine, base Config) Config {
config := base
if engineCR == nil {
return config
}
limits := engineCR.Spec.Limits
if limits.MaxConcurrentRuns > 0 {
config.Limits.MaxConcurrentRuns = int(limits.MaxConcurrentRuns)
}
if limits.QueueDepth > 0 {
config.Limits.QueueDepth = int(limits.QueueDepth)
}
if limits.ActiveDeadlineSeconds != nil && *limits.ActiveDeadlineSeconds > 0 {
config.Limits.ActiveDeadline = time.Duration(*limits.ActiveDeadlineSeconds) * time.Second
}
if limits.MaxConsoleBytes > 0 {
config.Limits.MaxConsoleBytes = limits.MaxConsoleBytes
}
if limits.MaxOutputBytes > 0 {
config.Limits.MaxOutputBytes = limits.MaxOutputBytes
}
if limits.MaxCacheEntries > 0 {
config.Limits.MaxCacheEntries = int(limits.MaxCacheEntries)
}
if limits.MaxCacheBytes > 0 {
config.Limits.MaxCacheBytes = limits.MaxCacheBytes
}
if engineCR.Spec.Trust.TTLSeconds != nil && *engineCR.Spec.Trust.TTLSeconds > 0 {
config.TrustTTL = time.Duration(*engineCR.Spec.Trust.TTLSeconds) * time.Second
}
cacheConfig := engineCR.Spec.Cache
if cacheConfig.VerdictTTLSeconds != nil && *cacheConfig.VerdictTTLSeconds > 0 {
config.VerdictTTL = time.Duration(*cacheConfig.VerdictTTLSeconds) * time.Second
}
if cacheConfig.ScopeTTLSeconds != nil && *cacheConfig.ScopeTTLSeconds > 0 {
config.ScopeTTL = time.Duration(*cacheConfig.ScopeTTLSeconds) * time.Second
}
if cacheConfig.RecordTTLSeconds != nil && *cacheConfig.RecordTTLSeconds > 0 {
config.RecordTTL = time.Duration(*cacheConfig.RecordTTLSeconds) * time.Second
}
config.VerdictTTL = opt.Positive(config.VerdictTTL, 30*time.Second)
config.ScopeTTL = opt.Positive(config.ScopeTTL, 5*time.Minute)
config.NegativeScopeTTL = min(opt.Positive(config.NegativeScopeTTL, 30*time.Second), config.ScopeTTL)
config.TrustTTL = opt.Positive(config.TrustTTL, 5*time.Minute)
config.DisableActions = false
return config
}
func EngineKey(cluster, name string) string {
return cluster + "/" + name
}