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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
package providermain
import (
"cmp"
"errors"
"fmt"
"log/slog"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/johnandersen777/socialweb-computer-kcp/internal/eso"
"github.com/johnandersen777/socialweb-computer-kcp/internal/foldmain"
"github.com/johnandersen777/socialweb-computer-kcp/internal/hostprocess"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kcpclient"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/logx"
"github.com/johnandersen777/socialweb-computer-kcp/internal/portallocator"
"github.com/johnandersen777/socialweb-computer-kcp/internal/scale"
)
const (
envKCPHost = "SOCIALWEB_KCP_HOST"
envKCPKubeconfig = "SOCIALWEB_KCP_KUBECONFIG"
envMountContext = "SOCIALWEB_CLUSTERPROVIDER_MOUNT_CONTEXT"
envGrant = "SOCIALWEB_CLUSTERPROVIDER_GRANT"
envLeasePath = "SOCIALWEB_CLUSTERPROVIDER_LEASE_PATH"
envJoin = "SOCIALWEB_CLUSTERPROVIDER_JOIN"
envAccount = "SOCIALWEB_CLUSTERPROVIDER_ACCOUNT"
envDatastore = "SOCIALWEB_CLUSTERPROVIDER_DATASTORE"
envStateDir = "SOCIALWEB_CLUSTERPROVIDER_STATE_DIR"
envVaultStateDir = "SOCIALWEB_CLUSTERPROVIDER_VAULT_STATE_DIR"
envUnitPrefix = "SOCIALWEB_CLUSTERPROVIDER_UNIT_PREFIX"
envHostProcessWorkspace = "SOCIALWEB_CLUSTERPROVIDER_HOSTPROCESS_WORKSPACE"
envDatastoreHasRow = "SOCIALWEB_CLUSTERPROVIDER_DATASTORE_HAS_ROW"
envAdvertiseAddress = "SOCIALWEB_CLUSTERPROVIDER_ADVERTISE_ADDRESS"
envStoreEndpoint = "SOCIALWEB_CLUSTERPROVIDER_STORE_ENDPOINT"
envAuditPolicy = "SOCIALWEB_CLUSTERPROVIDER_AUDIT_POLICY"
envMarketAdvertiseAddress = "SOCIALWEB_CLUSTERPROVIDER_MARKET_ADVERTISE_ADDRESS"
envMarketDenyBidderDids = "SOCIALWEB_CLUSTERPROVIDER_MARKET_DENY_BIDDER_DIDS"
envMarketReleaseTimeout = "SOCIALWEB_CLUSTERPROVIDER_MARKET_RELEASE_TIMEOUT"
envScaleHold = "SOCIALWEB_CLUSTERPROVIDER_SCALE_HOLD"
envNodeJoinGrace = "SOCIALWEB_CLUSTERPROVIDER_NODE_JOIN_GRACE"
envScaleMaxNodes = "SOCIALWEB_CLUSTERPROVIDER_SCALE_MAX_NODES"
envScalePodsPerNode = "SOCIALWEB_CLUSTERPROVIDER_SCALE_PODS_PER_NODE"
EnvScaleHold = envScaleHold
EnvScaleMaxNodes = envScaleMaxNodes
EnvScalePodsPerNode = envScalePodsPerNode
envHost = "SOCIALWEB_CLUSTERPROVIDER_HOST"
envCloudControllerManager = "SOCIALWEB_CLUSTERPROVIDER_CLOUD_CONTROLLER_MANAGER"
envDumbpipe = "SOCIALWEB_CLUSTERPROVIDER_DUMBPIPE"
envLogLevel = "SOCIALWEB_CLUSTERPROVIDER_LOG_LEVEL"
envESOManifestDir = "SOCIALWEB_CLUSTERPROVIDER_ESO_MANIFEST_DIR"
envESONamespace = "SOCIALWEB_CLUSTERPROVIDER_ESO_NAMESPACE"
envExternalSecrets = "SOCIALWEB_CLUSTERPROVIDER_EXTERNAL_SECRETS"
envESOBundle = "SOCIALWEB_CLUSTERPROVIDER_ESO_BUNDLE"
envK3s = "SOCIALWEB_CLUSTERPROVIDER_K3S"
envKine = "SOCIALWEB_CLUSTERPROVIDER_KINE"
envBao = "SOCIALWEB_CLUSTERPROVIDER_BAO"
envPgDump = "SOCIALWEB_CLUSTERPROVIDER_PG_DUMP"
envNodeClaimAgent = "SOCIALWEB_GATEWAY_NODECLAIM_AGENT"
)
const DefaultESOManifestDir = "/opt/socialweb/deploy/eso"
const DefaultGrantPath = "deploy/tenant-grant.yaml"
const DefaultUnitPrefix = "socialweb-"
const DefaultReclaimGrace = 5 * time.Minute
type Config struct {
KCPHost string
KCPKubeconfig string
MountContext string
GrantPath string
LeasePath string
Join string
Account string
Datastore string
StateDir string
VaultStateDir string
UnitPrefix string
HostProcessWorkspace string
AdvertiseAddress string
MarketAdvertiseAddress string
MarketDenyBidderDids []string
MarketReleaseTimeout time.Duration
StoreEndpoint string
AuditPolicyPath string
Host string
CloudControllerManager string
CloudControllerManagerExec []string
FrontExec []string
HostnameExec []string
Dumbpipe string
ESOManifestDir string
ESONamespace string
ExternalSecrets string
ESOBundle string
K3s string
Kine string
Bao string
PgDump string
NodeClaimAgent *kcpclient.ServiceAccountRef
DatastoreHasRow bool
ScaleHold time.Duration
NodeJoinGrace time.Duration
ScaleMaxNodes int
ScalePodsPerNode int
LogLevel slog.Level
}
func loadFor(get func(string) string, inv foldmain.Invocation) (Config, error) {
cfg := Config{
KCPHost: strings.TrimSpace(get(envKCPHost)),
KCPKubeconfig: strings.TrimSpace(get(envKCPKubeconfig)),
MountContext: strings.TrimSpace(get(envMountContext)),
LeasePath: strings.TrimSpace(get(envLeasePath)),
Join: strings.TrimSpace(get(envJoin)),
Account: strings.TrimSpace(get(envAccount)),
Datastore: strings.TrimSpace(get(envDatastore)),
StateDir: strings.TrimSpace(get(envStateDir)),
VaultStateDir: strings.TrimSpace(get(envVaultStateDir)),
UnitPrefix: strings.TrimSpace(get(envUnitPrefix)),
HostProcessWorkspace: strings.TrimSpace(get(envHostProcessWorkspace)),
AdvertiseAddress: strings.TrimSpace(get(envAdvertiseAddress)),
MarketAdvertiseAddress: strings.TrimSpace(get(envMarketAdvertiseAddress)),
StoreEndpoint: strings.TrimSpace(get(envStoreEndpoint)),
AuditPolicyPath: strings.TrimSpace(get(envAuditPolicy)),
Host: strings.TrimSpace(get(envHost)),
CloudControllerManager: strings.TrimSpace(get(envCloudControllerManager)),
Dumbpipe: strings.TrimSpace(get(envDumbpipe)),
ESOManifestDir: strings.TrimSpace(get(envESOManifestDir)),
ESONamespace: strings.TrimSpace(get(envESONamespace)),
ExternalSecrets: strings.TrimSpace(get(envExternalSecrets)),
ESOBundle: strings.TrimSpace(get(envESOBundle)),
K3s: strings.TrimSpace(get(envK3s)),
Kine: strings.TrimSpace(get(envKine)),
Bao: strings.TrimSpace(get(envBao)),
PgDump: strings.TrimSpace(get(envPgDump)),
GrantPath: strings.TrimSpace(get(envGrant)),
LogLevel: slog.LevelInfo,
ScaleMaxNodes: scale.DefaultMaxNodes,
ScalePodsPerNode: scale.DefaultPodsPerNode,
}
cfg.GrantPath = cmp.Or(cfg.GrantPath, DefaultGrantPath)
cfg.UnitPrefix = cmp.Or(cfg.UnitPrefix, DefaultUnitPrefix)
cfg.HostProcessWorkspace = cmp.Or(cfg.HostProcessWorkspace, hostprocess.DefaultWorkspace)
cfg.MountContext = cmp.Or(cfg.MountContext, kcpclient.ShardAdminContext)
cfg.CloudControllerManagerExec = inv.Reexec("internal", "cloud-controller-manager")
cfg.FrontExec = inv.Reexec("internal", "apiserver-front")
cfg.HostnameExec = inv.Reexec("internal", "ns-exec")
if cfg.CloudControllerManager != "" {
cfg.CloudControllerManagerExec = []string{cfg.CloudControllerManager}
}
cfg.ESOManifestDir = cmp.Or(cfg.ESOManifestDir, DefaultESOManifestDir)
cfg.ESONamespace = cmp.Or(cfg.ESONamespace, eso.DefaultControllerNamespace)
cfg.MarketAdvertiseAddress = cmp.Or(cfg.MarketAdvertiseAddress, portallocator.MarketAdvertiseAddress)
cfg.MarketDenyBidderDids = splitList(get(envMarketDenyBidderDids))
switch {
case cfg.StoreEndpoint != "" && cfg.Datastore != "" && cfg.StoreEndpoint != cfg.Datastore:
return Config{}, fmt.Errorf(
"%s is %q and %s is %q. They name ONE thing -- the store kine writes this cluster's "+
"objects into -- and two answers to one question are not a preference to be "+
"resolved silently: whichever lost would be a cluster whose objects went somewhere "+
"nobody is looking", envStoreEndpoint, cfg.StoreEndpoint, envDatastore, cfg.Datastore)
case cfg.StoreEndpoint == "":
cfg.StoreEndpoint = cfg.Datastore
}
if raw := strings.TrimSpace(get(envScaleHold)); raw != "" {
d, err := time.ParseDuration(raw)
if err != nil {
return Config{}, fmt.Errorf("%s is not a duration: %w", envScaleHold, err)
}
if d < 0 {
return Config{}, fmt.Errorf("%s must not be negative", envScaleHold)
}
d = cmp.Or(d, scale.NoHold)
cfg.ScaleHold = d
}
if raw := strings.TrimSpace(get(envNodeJoinGrace)); raw != "" {
d, err := time.ParseDuration(raw)
if err != nil {
return Config{}, fmt.Errorf("%s is not a duration: %w", envNodeJoinGrace, err)
}
if d <= 0 {
return Config{}, fmt.Errorf("%s must be positive", envNodeJoinGrace)
}
cfg.NodeJoinGrace = d
}
if raw := strings.TrimSpace(get(envScaleMaxNodes)); raw != "" {
n, err := strconv.Atoi(raw)
if err != nil {
return Config{}, fmt.Errorf("%s is not a whole number: %w", envScaleMaxNodes, err)
}
if n < 1 {
return Config{}, fmt.Errorf(
"%s is %d, and a ceiling below one node is not a smaller cluster: it is a cluster "+
"that can never place the work it has intent for. Leave it unset for the default "+
"of %d", envScaleMaxNodes, n, scale.DefaultMaxNodes)
}
cfg.ScaleMaxNodes = n
}
if raw := strings.TrimSpace(get(envScalePodsPerNode)); raw != "" {
n, err := strconv.Atoi(raw)
if err != nil {
return Config{}, fmt.Errorf("%s is not a whole number: %w", envScalePodsPerNode, err)
}
if n < 1 {
return Config{}, fmt.Errorf(
"%s is %d, and a node that holds fewer than one pod is not a capacity to divide by. "+
"Leave it unset for the default of %d", envScalePodsPerNode, n,
scale.DefaultPodsPerNode)
}
cfg.ScalePodsPerNode = n
}
for _, req := range []struct{ name, value string }{
{envKCPHost, cfg.KCPHost},
{envKCPKubeconfig, cfg.KCPKubeconfig},
{envLeasePath, cfg.LeasePath},
} {
if req.value == "" {
return Config{}, fmt.Errorf("%s is not set", req.name)
}
}
if cfg.Join != "" {
raw := strings.TrimSpace(get(envDatastoreHasRow))
if raw == "" {
return Config{}, fmt.Errorf(
"%s is not set. Whether the datastore already holds a bootstrap row is the "+
"caller's OBSERVATION and has no default: a wrong \"false\" makes k3s exit "+
"at boot with \"bootstrap data already found and encrypted with different "+
"token\" (ADR 0023)", envDatastoreHasRow)
}
has, err := parseBool(raw)
if err != nil {
return Config{}, fmt.Errorf("%s: %w", envDatastoreHasRow, err)
}
cfg.DatastoreHasRow = has
if cfg.StateDir == "" {
return Config{}, fmt.Errorf(
"%s is not set. It holds this cluster's node records, its instance token, its "+
"audit log and its identity bundle, and without it a gateway that restarts "+
"can neither find nor reap the agent the last one started -- so it is required "+
"whether or not %s names an external store", envStateDir, envStoreEndpoint)
}
if !filepath.IsAbs(cfg.StateDir) {
return Config{}, fmt.Errorf(
"%s is %q, which is relative. A node's identity IS the absolute socket path under "+
"this directory -- that string is what a running VMM is recognised by, what a "+
"reap compares against, and what a record written by an earlier gateway names. "+
"A relative path makes that identity depend on the working directory the gateway "+
"was started from, so the same node started from two directories yields two "+
"identities, and the second one is invisible to the check that exists to stop two "+
"VMMs running behind one node name", envStateDir, cfg.StateDir)
}
if err := cfg.checkMarketPlacement(); err != nil {
return Config{}, err
}
if len(cfg.CloudControllerManagerExec) == 0 {
return Config{}, fmt.Errorf(
"%s is not set. Every joined cluster's process group carries the cloud controller "+
"manager, which is what stamps a Node's providerID and the labels an autoscaler "+
"groups by, and nothing else names that binary: a join that accepted an empty one "+
"would lease, config and spawn everything else and silently drop the component "+
"that gives a joined node its cloud identity", envCloudControllerManager)
}
if len(cfg.FrontExec) == 0 {
return Config{}, errors.New(
"the cluster provider is not running from the socialweb-computer binary, so no executable " +
"carries `internal apiserver-front`: every joined cluster's apiserver port is owned by that " +
"front, and k3s sits behind it on a slot port")
}
if cfg.ExternalSecrets == "" || cfg.ESOBundle == "" {
return Config{}, fmt.Errorf(
"%s and %s must both be set. Every joined cluster's process group carries the External "+
"Secrets controller and its webhook beside the control plane: the first names the "+
"pinned external-secrets binary, the second the pinned upstream bundle whose CRDs, "+
"ClusterRoles and webhook registration the group installs into the tenant before "+
"the pair starts. A join that accepted either empty would spawn a pair with nothing "+
"to run or a tenant serving none of its kinds", envExternalSecrets, envESOBundle)
}
for env, p := range cfg.pinnedExecutables() {
if p != "" && !filepath.IsAbs(p) {
return Config{}, fmt.Errorf("%s is %q, which is relative; it names a pinned executable by its absolute path, never by PATH", env, p)
}
}
}
var err error
if cfg.NodeClaimAgent, err = kcpclient.ParseServiceAccountRef(strings.TrimSpace(get(envNodeClaimAgent))); err != nil {
return Config{}, fmt.Errorf("%s: %w", envNodeClaimAgent, err)
}
if cfg.MarketReleaseTimeout, err = optionalDuration(get, envMarketReleaseTimeout); err != nil {
return Config{}, err
}
if cfg.LogLevel, err = logx.ParseLevel(get(envLogLevel)); err != nil {
return Config{}, fmt.Errorf("%s: %w", envLogLevel, err)
}
return cfg, nil
}
const JoinAllClusters = "*"
func (c Config) ObserveOnly() bool { return c.Join == "" }
func (c Config) AllClusters() bool { return c.Join == JoinAllClusters }
func (c *Config) checkMarketPlacement() error {
if c.AdvertiseAddress != "" {
return fmt.Errorf(
"%s is %q. A node is a VM rented from the compute market, and the address it dials its "+
"cluster's apiserver on is put on the guest's OWN loopback and reverse-forwarded to "+
"this host by the market's door. That address comes from %s, not from here, so a "+
"value in this variable cannot be in force: it is refused rather than accepted and "+
"ignored, because an operator who set one and saw no complaint would believe it was "+
"carrying it",
envAdvertiseAddress, c.AdvertiseAddress, envMarketAdvertiseAddress)
}
if err := c.checkHost(); err != nil {
return err
}
if err := portallocator.AssertMarketAdvertiseAddress(c.MarketAdvertiseAddress); err != nil {
return fmt.Errorf("%s: %w", envMarketAdvertiseAddress, err)
}
c.AdvertiseAddress = c.MarketAdvertiseAddress
return nil
}
func (c Config) checkHost() error {
host, err := os.Hostname()
if err != nil {
return fmt.Errorf(
"%s is %q and this host's own name cannot be read (%w), so the comparison that "+
"keeps a gateway from placing nodes on a machine it is not cannot be made. An "+
"uncompared host is worse than an absent one: it would be accepted as a match",
envHost, c.Host, err)
}
switch {
case c.Host == "":
return fmt.Errorf(
"%s is not set. A gateway that places nodes has to be told which host it is, so that "+
"the answer can be checked against os.Hostname() (%q); nothing here may assume, "+
"because the assumption is accepted on the one machine where it is wrong",
envHost, host)
case c.Host != host:
return fmt.Errorf(
"%s is %q and this host calls itself %q. The mismatch is refused rather than "+
"reconciled: a gateway told it is a host it is not would place nodes on the wrong "+
"machine -- the node records and the tenant registrations would both name a "+
"cluster running somewhere else, and every later pass would read that "+
"other machine's state as its own",
envHost, c.Host, host)
}
return nil
}
func splitList(raw string) []string {
out := []string{}
for part := range strings.SplitSeq(raw, ",") {
if trimmed := strings.TrimSpace(part); trimmed != "" {
out = append(out, trimmed)
}
}
return out
}
func parseBool(raw string) (bool, error) {
switch strings.ToLower(raw) {
case "true", "1", "yes":
return true, nil
case "false", "0", "no":
return false, nil
}
return false, fmt.Errorf("%q is not one of true, false", raw)
}
func optionalDuration(get func(string) string, name string) (time.Duration, error) {
raw := strings.TrimSpace(get(name))
if raw == "" {
return 0, nil
}
d, err := time.ParseDuration(raw)
if err != nil {
return 0, fmt.Errorf("%s: %q is not a duration", name, raw)
}
if d <= 0 {
return 0, fmt.Errorf("%s: %q must be positive", name, raw)
}
return d, nil
}