-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.go
More file actions
929 lines (766 loc) · 28 KB
/
stack.go
File metadata and controls
929 lines (766 loc) · 28 KB
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
package stack
import (
"bufio"
"errors"
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/ObolNetwork/obol-stack/internal/agent"
"github.com/ObolNetwork/obol-stack/internal/config"
"github.com/ObolNetwork/obol-stack/internal/dns"
"github.com/ObolNetwork/obol-stack/internal/embed"
"github.com/ObolNetwork/obol-stack/internal/model"
"github.com/ObolNetwork/obol-stack/internal/openclaw"
"github.com/ObolNetwork/obol-stack/internal/tunnel"
"github.com/ObolNetwork/obol-stack/internal/ui"
"github.com/ObolNetwork/obol-stack/internal/update"
x402verifier "github.com/ObolNetwork/obol-stack/internal/x402"
petname "github.com/dustinkirkland/golang-petname"
)
const (
kubeconfigFile = "kubeconfig.yaml"
stackIDFile = ".stack-id"
)
// Init initializes the stack configuration
func Init(cfg *config.Config, u *ui.UI, force bool, backendName string) error {
// Check if any stack config already exists
stackIDPath := filepath.Join(cfg.ConfigDir, stackIDFile)
backendFilePath := filepath.Join(cfg.ConfigDir, stackBackendFile)
hasExistingConfig := false
if _, err := os.Stat(stackIDPath); err == nil {
hasExistingConfig = true
}
if _, err := os.Stat(backendFilePath); err == nil {
hasExistingConfig = true
}
// Also check legacy k3d.yaml for backward compatibility
if _, err := os.Stat(filepath.Join(cfg.ConfigDir, k3dConfigFile)); err == nil {
hasExistingConfig = true
}
if hasExistingConfig && !force {
return fmt.Errorf("stack configuration already exists at %s\nUse --force to overwrite", cfg.ConfigDir)
}
if err := os.MkdirAll(cfg.ConfigDir, 0o755); err != nil {
return fmt.Errorf("failed to create stack config dir: %w", err)
}
// Check if stack ID already exists (preserve on --force)
var stackID string
if existingID, err := os.ReadFile(stackIDPath); err == nil {
stackID = strings.TrimSpace(string(existingID))
u.Warnf("Preserving existing stack ID: %s (use purge to reset)", stackID)
} else {
stackID = petname.Generate(2, "-")
}
// Default to k3d if no backend specified
if backendName == "" {
backendName = BackendK3d
}
// If switching backends, destroy the old one first to prevent
// orphaned clusters (e.g., k3d containers still running after
// switching to k3s, or k3s process still alive after switching to k3d).
if hasExistingConfig && force {
destroyOldBackendIfSwitching(cfg, u, backendName, stackID)
}
backend, err := NewBackend(backendName)
if err != nil {
return err
}
u.Info("Initializing cluster configuration")
u.Detail("Cluster ID", stackID)
u.Detail("Backend", backend.Name())
// Check prerequisites
if err := backend.Prerequisites(cfg); err != nil {
return fmt.Errorf("prerequisites check failed: %w", err)
}
// Generate backend-specific config
if err := backend.Init(cfg, u, stackID); err != nil {
return err
}
// Copy embedded defaults (helmfile + charts for infrastructure)
// Resolve {{OLLAMA_HOST}} based on backend:
// - k3d (Docker): host.docker.internal (macOS) or host.k3d.internal (Linux)
// - k3s (bare-metal): 127.0.0.1 (k3s runs directly on the host)
// Resolve {{OLLAMA_HOST_IP}} to a numeric IP for the Endpoints object:
// - Endpoints require an IP, not a hostname (ClusterIP+Endpoints pattern)
ollamaHost := ollamaHostForBackend(backendName)
ollamaHostIP, err := ollamaHostIPForBackend(backendName)
if err != nil {
return fmt.Errorf("failed to resolve Ollama host IP: %w", err)
}
defaultsDir := filepath.Join(cfg.ConfigDir, "defaults")
if err := embed.CopyDefaults(defaultsDir, map[string]string{
"{{OLLAMA_HOST}}": ollamaHost,
"{{OLLAMA_HOST_IP}}": ollamaHostIP,
"{{CLUSTER_ID}}": stackID,
}); err != nil {
return fmt.Errorf("failed to copy defaults: %w", err)
}
// Store stack ID
if err := os.WriteFile(stackIDPath, []byte(stackID), 0o600); err != nil { //nolint:gosec // G703: path from user's local config dir
return fmt.Errorf("failed to write stack ID: %w", err)
}
// Save backend choice
if err := SaveBackend(cfg, backendName); err != nil {
return fmt.Errorf("failed to save backend choice: %w", err)
}
u.Success("Stack initialized")
return nil
}
// destroyOldBackendIfSwitching checks if the backend is changing and tears down
// the old one to prevent orphaned clusters running side by side.
func destroyOldBackendIfSwitching(cfg *config.Config, u *ui.UI, newBackend, stackID string) {
oldBackend, err := LoadBackend(cfg)
if err != nil {
return
}
if oldBackend.Name() == newBackend {
return // same backend, nothing to clean up
}
u.Warnf("Switching backend from %s to %s — destroying old cluster", oldBackend.Name(), newBackend)
// Destroy the old backend's cluster (best-effort, don't block init)
if stackID != "" {
if err := oldBackend.Destroy(cfg, u, stackID); err != nil {
u.Warnf("Failed to destroy old %s cluster: %v", oldBackend.Name(), err)
}
}
// Clean up stale config files from the old backend
cleanupStaleBackendConfigs(cfg, oldBackend.Name())
}
// cleanupStaleBackendConfigs removes config files belonging to the old backend
// that would otherwise linger and confuse detection.
func cleanupStaleBackendConfigs(cfg *config.Config, oldBackend string) {
var staleFiles []string
switch oldBackend {
case BackendK3d:
staleFiles = []string{k3dConfigFile}
case BackendK3s:
staleFiles = []string{k3sConfigFile, k3sPidFile, k3sLogFile}
}
for _, f := range staleFiles {
path := filepath.Join(cfg.ConfigDir, f)
if _, err := os.Stat(path); err == nil {
os.Remove(path)
}
}
}
// ollamaHostForBackend returns the hostname/IP that reaches the host Ollama
// instance from inside the cluster.
func ollamaHostForBackend(backendName string) string {
if backendName == BackendK3s {
return "127.0.0.1"
}
if runtime.GOOS == "darwin" {
return "host.docker.internal"
}
return "host.k3d.internal"
}
// ollamaHostIPForBackend resolves the Ollama host to an IP address.
// ClusterIP+Endpoints requires an IP (not a hostname).
//
// Resolution strategy:
// 1. If already an IP (k3s: 127.0.0.1), return as-is
// 2. Try host-side DNS resolution
// 3. macOS: use Docker Desktop VM gateway (192.168.65.254)
// 4. Linux: fall back to docker0 bridge interface IP
func ollamaHostIPForBackend(backendName string) (string, error) {
host := ollamaHostForBackend(backendName)
// If already an IP, return as-is (k3s: 127.0.0.1)
if net.ParseIP(host) != nil {
return host, nil
}
// Try host-side DNS resolution first.
addrs, err := net.LookupHost(host)
if err == nil && len(addrs) > 0 {
return addrs[0], nil
}
// macOS Docker Desktop: host.docker.internal is only resolvable inside
// containers (Docker injects it via DNS), not on the host. Use the
// well-known VM gateway IP that Docker Desktop exposes to containers.
if runtime.GOOS == "darwin" && backendName == BackendK3d {
return dockerDesktopGatewayIP(), nil
}
// Linux fallback: docker0 bridge interface IP (reachable from all containers).
if runtime.GOOS == "linux" && backendName == BackendK3d {
ip, bridgeErr := dockerBridgeGatewayIP()
if bridgeErr == nil {
return ip, nil
}
return "", fmt.Errorf("cannot resolve Ollama host %q to IP: %w; docker0 fallback also failed: %w", host, err, bridgeErr)
}
return "", fmt.Errorf("cannot resolve Ollama host %q to IP: %w\n\tEnsure Docker Desktop is running", host, err)
}
// dockerDesktopGatewayIP returns the Docker Desktop VM gateway IP.
// On macOS, Docker Desktop runs a LinuxKit VM. The host is reachable from
// containers at this well-known gateway address (192.168.65.254 maps to
// host.docker.internal inside the VM). This has been stable across Docker
// Desktop versions since the transition from HyperKit to Apple Virtualization.
func dockerDesktopGatewayIP() string {
return "192.168.65.254"
}
// dockerBridgeGatewayIP returns the IPv4 address of an active Docker bridge
// interface. It prefers docker0 (the default bridge, typically 172.17.0.1).
// If docker0 is present but DOWN (e.g. when only k3d's custom bridge network
// is active), it falls back to the first UP interface whose name starts with
// "br-" — which is how Docker names per-network bridge interfaces.
func dockerBridgeGatewayIP() (string, error) {
if ip, err := bridgeInterfaceIP("docker0"); err == nil {
return ip, nil
}
// docker0 missing or DOWN — scan for an active br-<network-id> bridge.
ifaces, err := net.Interfaces()
if err != nil {
return "", fmt.Errorf("cannot list network interfaces: %w", err)
}
for _, iface := range ifaces {
if !strings.HasPrefix(iface.Name, "br-") {
continue
}
if ip, err := bridgeInterfaceIP(iface.Name); err == nil {
return ip, nil
}
}
return "", errors.New("no active Docker bridge interface found (docker0 or br-*)")
}
// bridgeInterfaceIP returns the IPv4 address of a named network interface,
// or an error if the interface does not exist, is DOWN, or has no IPv4 address.
func bridgeInterfaceIP(name string) (string, error) {
iface, err := net.InterfaceByName(name)
if err != nil {
return "", fmt.Errorf("interface %s not found: %w", name, err)
}
if iface.Flags&net.FlagUp == 0 {
return "", fmt.Errorf("interface %s is down", name)
}
addrs, err := iface.Addrs()
if err != nil {
return "", fmt.Errorf("cannot get addresses for %s: %w", name, err)
}
for _, addr := range addrs {
if ipNet, ok := addr.(*net.IPNet); ok && ipNet.IP.To4() != nil {
return ipNet.IP.String(), nil
}
}
return "", fmt.Errorf("no IPv4 address found on interface %s", name)
}
// Up starts the cluster using the configured backend
func Up(cfg *config.Config, u *ui.UI, wildcardDNS bool) error {
stackID := getStackID(cfg)
if stackID == "" {
return errors.New("stack ID not found, run 'obol stack init' first")
}
backend, err := LoadBackend(cfg)
if err != nil {
return fmt.Errorf("failed to load backend: %w", err)
}
kubeconfigPath := filepath.Join(cfg.ConfigDir, kubeconfigFile)
u.Infof("Starting stack (id: %s, backend: %s)", stackID, backend.Name())
portsBlocked := checkPortsAvailable([]int{80, 443}) != nil
kubeconfigData, err := backend.Up(cfg, u, stackID)
if err != nil {
return err
}
// Write kubeconfig
if err := os.WriteFile(kubeconfigPath, kubeconfigData, 0o600); err != nil {
return fmt.Errorf("failed to write kubeconfig: %w", err)
}
// Sync defaults with backend-aware dataDir
dataDir := backend.DataDir(cfg)
if err := syncDefaults(cfg, u, kubeconfigPath, dataDir); err != nil {
return err
}
// Ensure obol.stack resolves to localhost via /etc/hosts (works everywhere).
if err := dns.EnsureHostsEntries(nil); err != nil {
u.Warnf("Could not update /etc/hosts for obol.stack: %v", err)
}
// Wildcard *.obol.stack DNS is opt-in (--wildcard-dns) because it
// modifies system DNS config (NetworkManager/resolv.conf on Linux,
// /etc/resolver on macOS) which can break host DNS resolution.
if wildcardDNS {
if err := dns.EnsureRunning(); err != nil {
u.Warnf("DNS resolver failed to start: %v", err)
} else if err := dns.ConfigureSystemResolver(); err != nil {
u.Warnf("Wildcard DNS configuration failed: %v", err)
} else {
u.Success("Wildcard DNS configured (*.obol.stack)")
}
}
u.Blank()
u.Bold("Stack started successfully.")
if portsBlocked {
u.Warnf("Ports 80/443 are in use by another process — use http://obol.stack:8080 instead")
u.Print("Visit http://obol.stack:8080 in your browser to get started.")
} else {
u.Print("Visit http://obol.stack in your browser to get started.")
}
update.HintIfStale(cfg)
return nil
}
// Down stops the cluster and the DNS resolver container.
func Down(cfg *config.Config, u *ui.UI) error {
stackID := getStackID(cfg)
if stackID == "" {
return errors.New("stack ID not found, stack may not be initialized")
}
backend, err := LoadBackend(cfg)
if err != nil {
return fmt.Errorf("failed to load backend: %w", err)
}
// Stop the DNS resolver container
dns.Stop()
return backend.Down(cfg, u, stackID)
}
// Purge deletes the cluster config and optionally data
func Purge(cfg *config.Config, u *ui.UI, force bool) error {
// When --force is set, data dir will be deleted — offer wallet backup.
if force {
openclaw.PromptBackupBeforePurge(cfg, u)
}
stackID := getStackID(cfg)
backend, err := LoadBackend(cfg)
if err != nil {
return fmt.Errorf("failed to load backend: %w", err)
}
// Destroy cluster if we have a stack ID
if stackID != "" {
u.Infof("Destroying cluster (id: %s)", stackID)
if err := backend.Destroy(cfg, u, stackID); err != nil {
u.Warnf("Failed to destroy cluster (may already be deleted): %v", err)
}
}
// Stop DNS resolver and remove system resolver config
dns.Stop()
dns.RemoveSystemResolver()
// Remove stack config directory
if err := os.RemoveAll(cfg.ConfigDir); err != nil {
return fmt.Errorf("failed to remove stack config: %w", err)
}
u.Success("Removed cluster config")
// Remove data directory only if force flag is set.
// Uses Exec instead of RunWithSpinner because sudo may prompt for a password,
// which requires an interactive terminal (stdin connected).
if force {
rmCmd := exec.Command("sudo", "rm", "-rf", cfg.DataDir)
rmCmd.Stdin = os.Stdin
if err := u.Exec(ui.ExecConfig{
Name: "Removing data directory",
Cmd: rmCmd,
Interactive: true,
}); err != nil {
return fmt.Errorf("failed to remove data directory: %w", err)
}
u.Blank()
u.Bold("Cluster fully purged (binaries preserved)")
} else {
u.Success("Cluster purged (config removed, data preserved)")
u.Printf(" To delete persistent data: sudo rm -rf %s", cfg.DataDir)
u.Print(" Or use 'obol stack purge --force' to remove everything")
}
return nil
}
// getStackID reads the stored stack ID
func getStackID(cfg *config.Config) string {
stackIDPath := filepath.Join(cfg.ConfigDir, stackIDFile)
data, err := os.ReadFile(stackIDPath)
if err != nil {
return ""
}
return strings.TrimSpace(string(data))
}
// GetStackID reads the stored stack ID (exported for use in main)
func GetStackID(cfg *config.Config) string {
return getStackID(cfg)
}
// syncDefaults deploys the default infrastructure using helmfile
// If deployment fails, the cluster is automatically stopped via Down()
func syncDefaults(cfg *config.Config, u *ui.UI, kubeconfigPath string, dataDir string) error {
defaultsHelmfilePath := filepath.Join(cfg.ConfigDir, "defaults")
helmfilePath := filepath.Join(defaultsHelmfilePath, "helmfile.yaml")
// Compatibility migration
if err := migrateDefaultsHTTPRouteHostnames(helmfilePath); err != nil {
u.Warnf("Failed to migrate defaults helmfile hostnames: %v", err)
}
helmfileCmd := exec.Command(
filepath.Join(cfg.BinDir, "helmfile"),
"--file", helmfilePath,
"--kubeconfig", kubeconfigPath,
"sync",
)
helmfileCmd.Env = append(os.Environ(),
"KUBECONFIG="+kubeconfigPath,
"STACK_DATA_DIR="+dataDir,
)
// In development mode, build and import local repo images that aren't on a
// public registry yet. Third-party images use the k3d registry-mirror path
// configured during cluster creation.
if os.Getenv("OBOL_DEVELOPMENT") == "true" {
buildAndImportLocalImages(cfg)
}
if err := u.Exec(ui.ExecConfig{
Name: "Deploying default infrastructure",
Cmd: helmfileCmd,
}); err != nil {
u.Warn("Helmfile sync failed, stopping cluster")
if downErr := Down(cfg, u); downErr != nil {
u.Warnf("Failed to stop cluster during cleanup: %v", downErr)
}
return fmt.Errorf("failed to apply defaults helmfile: %w", err)
}
u.Success("Default infrastructure deployed")
// Populate the x402-verifier CA bundle from the host so TLS verification of
// the facilitator works without needing to run `obol sell pricing` first.
// Non-fatal: best-effort, the user can repopulate by running `obol sell pricing`.
x402verifier.PopulateCABundle(cfg)
// Auto-configure LiteLLM with Ollama models and any cloud providers
// whose API keys are found in the environment. This ensures the
// inference path works out of the box — no separate `obol model setup`
// step required. Non-fatal: the user can always run `obol model setup` later.
autoConfigureLLM(cfg, u)
// Deploy default OpenClaw instance (non-fatal on failure).
// Not wrapped in RunWithSpinner because SetupDefault/Onboard produce their
// own UI output (Info, Detail, Print) and run sub-spinners via u.Exec.
// An outer spinner would fight with that output and block any sudo password
// prompt (e.g. EnsureHostsEntries writing /etc/hosts).
u.Blank()
u.Info("Setting up default OpenClaw instance")
if err := openclaw.SetupDefault(cfg, u); err != nil {
u.Warnf("Failed to set up default OpenClaw: %v", err)
u.Dim(" You can manually set up OpenClaw later with: obol openclaw onboard")
}
// Apply agent capabilities (RBAC + heartbeat) to the default instance.
// Non-fatal: the user can always run `obol agent init` later.
u.Blank()
u.Info("Applying agent capabilities")
if err := agent.Init(cfg, u); err != nil {
u.Warnf("Failed to apply agent capabilities: %v", err)
u.Dim(" You can manually apply later with: obol agent init")
}
// Start the Cloudflare tunnel only if a persistent DNS tunnel is provisioned.
// Quick tunnels are dormant by default and activate on first `obol sell`.
u.Blank()
if st, _ := tunnel.LoadTunnelState(cfg); st != nil && st.Mode == "dns" && st.Hostname != "" {
u.Info("Starting persistent Cloudflare tunnel")
if tunnelURL, err := tunnel.EnsureRunning(cfg, u); err != nil {
u.Warnf("Tunnel not started: %v", err)
u.Dim(" Start manually with: obol tunnel restart")
} else {
u.Successf("Tunnel active: %s", tunnelURL)
}
} else {
u.Dim("Tunnel dormant (activates on first 'obol sell http')")
u.Dim(" Start manually with: obol tunnel restart")
u.Dim(" For a persistent URL: obol tunnel login --hostname stack.example.com")
}
return nil
}
// autoConfigureLLM detects host Ollama and imported cloud providers, then
// auto-configures LiteLLM so inference works out of the box.
// Patches all providers first, then does a single restart.
func autoConfigureLLM(cfg *config.Config, u *ui.UI) {
var configured []string // provider names that were patched
// --- Ollama ---
ollamaModels, err := model.ListOllamaModels()
if err == nil && len(ollamaModels) > 0 && !model.HasConfiguredModels(cfg) {
u.Blank()
u.Infof("Ollama detected with %d model(s)", len(ollamaModels))
var names []string
for _, m := range ollamaModels {
name := m.Name
if before, ok := strings.CutSuffix(name, ":latest"); ok {
name = before
}
names = append(names, name)
}
if err := model.PatchLiteLLMProvider(cfg, u, "ollama", "", names); err != nil {
u.Warnf("Auto-configure Ollama failed: %v", err)
} else {
configured = append(configured, "ollama")
}
}
// --- Cloud provider from ~/.openclaw ---
if cloudProvider := autoDetectCloudProvider(cfg, u); cloudProvider != "" {
configured = append(configured, cloudProvider)
}
// --- Single restart for all providers ---
if len(configured) > 0 {
label := strings.Join(configured, " + ")
if err := model.RestartLiteLLM(cfg, u, label); err != nil {
u.Warnf("LiteLLM restart failed: %v", err)
u.Dim(" Run 'obol model setup' to configure manually.")
}
}
}
// autoDetectCloudProvider reads ~/.openclaw config, resolves the cloud
// provider API key, and patches LiteLLM (without restart). Returns the
// provider name on success, or "" if nothing was configured.
func autoDetectCloudProvider(cfg *config.Config, u *ui.UI) string {
imported, err := openclaw.DetectExistingConfig()
if err != nil || imported == nil {
return ""
}
agentModel := imported.AgentModel
if agentModel == "" {
return ""
}
// Extract provider and model name from "anthropic/claude-sonnet-4-6".
provider, modelName := "", agentModel
if before, after, ok := strings.Cut(agentModel, "/"); ok {
provider = before
modelName = after
}
if provider == "" {
provider = model.ProviderFromModelName(agentModel)
}
if provider == "" || provider == "ollama" {
return ""
}
// Already configured — skip.
if model.HasProviderConfigured(cfg, provider) {
return ""
}
// Resolve API key: try primary + alt env vars, then .env in dev mode.
apiKey, envVarUsed := model.ResolveAPIKey(provider)
if apiKey == "" && os.Getenv("OBOL_DEVELOPMENT") == "true" {
envVar := model.ProviderEnvVar(provider)
dotEnv := model.LoadDotEnv(filepath.Join(".", ".env"))
apiKey = dotEnv[envVar]
if apiKey != "" {
envVarUsed = envVar + " (.env)"
}
}
if apiKey == "" {
u.Blank()
primaryEnv := model.ProviderEnvVar(provider)
u.Warnf("Agent model %s detected but %s is not set", agentModel, primaryEnv)
u.Dim(fmt.Sprintf(" Set it in your environment: export %s=...", primaryEnv))
u.Dim(" Or configure after startup: obol model setup --provider " + provider)
return ""
}
u.Blank()
if envVarUsed != model.ProviderEnvVar(provider) {
u.Infof("Cloud model %s detected via %s — configuring %s provider", agentModel, envVarUsed, provider)
} else {
u.Infof("Cloud model %s detected — configuring %s provider", agentModel, provider)
}
if err := model.PatchLiteLLMProvider(cfg, u, provider, apiKey, []string{modelName}); err != nil {
u.Warnf("Auto-configure %s failed: %v", provider, err)
u.Dim(fmt.Sprintf(" Run 'obol model setup --provider %s' to configure manually.", provider))
return ""
}
return provider
}
// localImage describes a Docker image built from source in this repo.
type localImage struct {
tag string // e.g. "ghcr.io/obolnetwork/x402-verifier:latest"
dockerfile string // relative to project root, e.g. "Dockerfile.x402-verifier"
}
// localImages lists images that should be built locally and imported into k3d.
var localImages = []localImage{
{tag: "ghcr.io/obolnetwork/x402-verifier:latest", dockerfile: "Dockerfile.x402-verifier"},
{tag: "ghcr.io/obolnetwork/serviceoffer-controller:latest", dockerfile: "Dockerfile.serviceoffer-controller"},
{tag: "ghcr.io/obolnetwork/x402-buyer:latest", dockerfile: "Dockerfile.x402-buyer"},
}
func devPreloadImages() []string {
var images []string
if ref := openclaw.ImageRef(); ref != "" {
images = append(images, ref)
}
return images
}
// buildAndImportLocalImages builds Docker images from source and imports them
// into the k3d cluster. This ensures images are available even when the GHCR
// publish workflow hasn't run. Non-fatal: logs warnings on failure.
func buildAndImportLocalImages(cfg *config.Config) {
stackID := getStackID(cfg)
if stackID == "" {
return
}
// Find the project root (where go.mod lives).
projectRoot := findProjectRoot()
if projectRoot == "" {
fmt.Println("Warning: could not find project root, skipping local image build")
return
}
clusterName := "obol-stack-" + stackID
k3dBinary := filepath.Join(cfg.BinDir, "k3d")
for _, img := range localImages {
contextDir := projectRoot
dockerfilePath := filepath.Join(projectRoot, img.dockerfile)
if _, err := os.Stat(dockerfilePath); os.IsNotExist(err) {
continue // Dockerfile not present (production install without source)
}
fmt.Printf("Building %s from %s...\n", img.tag, img.dockerfile)
buildCmd := exec.Command("docker", "build",
"-f", dockerfilePath,
"-t", img.tag,
contextDir,
)
buildCmd.Stdout = os.Stdout
buildCmd.Stderr = os.Stderr
if err := buildCmd.Run(); err != nil {
fmt.Printf("Warning: failed to build %s: %v\n", img.tag, err)
continue
}
if err := importImageToCluster(k3dBinary, clusterName, img.tag); err != nil {
fmt.Printf("Warning: failed to import %s into k3d: %v\n", img.tag, err)
}
}
for _, ref := range devPreloadImages() {
fmt.Printf("Preloading %s into cluster %s...\n", ref, clusterName)
pullCmd := exec.Command("docker", "pull", ref)
pullCmd.Stdout = os.Stdout
pullCmd.Stderr = os.Stderr
if err := pullCmd.Run(); err != nil {
fmt.Printf("Warning: failed to pull %s: %v\n", ref, err)
continue
}
if err := importImageToCluster(k3dBinary, clusterName, ref); err != nil {
fmt.Printf("Warning: failed to import %s into k3d: %v\n", ref, err)
}
}
}
func importImageToCluster(k3dBinary, clusterName, tag string) error {
fmt.Printf("Importing %s into cluster %s...\n", tag, clusterName)
importCmd := exec.Command(k3dBinary, "image", "import", tag, "-c", clusterName)
importCmd.Stdout = os.Stdout
importCmd.Stderr = os.Stderr
return importCmd.Run()
}
// findProjectRoot walks up from the current directory to find go.mod.
func findProjectRoot() string {
dir, err := os.Getwd()
if err != nil {
return ""
}
for {
if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
return dir
}
parent := filepath.Dir(dir)
if parent == dir {
return ""
}
dir = parent
}
}
// LocalIngressURL returns the best local HTTP base URL for the current stack.
// For k3d, it prefers the first host port mapped to container port 80 in the
// generated k3d config. For historical/default setups it falls back to
// http://obol.stack or http://obol.stack:8080.
func LocalIngressURL(cfg *config.Config) string {
k3dConfigPath := filepath.Join(cfg.ConfigDir, k3dConfigFile)
if data, err := os.ReadFile(k3dConfigPath); err == nil {
for line := range strings.SplitSeq(string(data), "\n") {
line = strings.TrimSpace(line)
if !strings.HasPrefix(line, "- port:") {
continue
}
portSpec := strings.TrimSpace(strings.TrimPrefix(line, "- port:"))
parts := strings.Split(portSpec, ":")
if len(parts) != 2 || parts[1] != "80" {
continue
}
if parts[0] == "80" {
return "http://obol.stack"
}
return fmt.Sprintf("http://obol.stack:%s", parts[0])
}
}
if checkPortsAvailable([]int{80}) == nil {
return "http://obol.stack"
}
return "http://obol.stack:8080"
}
// checkPortsAvailable verifies that all required ports can be bound.
func checkPortsAvailable(ports []int) error {
var blocked []int
for _, port := range ports {
ln, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err == nil {
ln.Close()
continue
}
if strings.Contains(err.Error(), "permission denied") {
// On Linux, binding privileged ports (< 1024) without root always
// returns "permission denied" — even when the port is free. We
// can't tell "free but needs root" from "occupied" via bind alone.
// Fall back to /proc/net/tcp{,6} which is readable without root.
if runtime.GOOS == "linux" && isPortOccupiedProc(port) {
blocked = append(blocked, port)
}
continue
}
blocked = append(blocked, port)
}
if len(blocked) > 0 {
return fmt.Errorf(
"port(s) %s already in use — "+
"Obol Stack needs these ports for HTTP/HTTPS access; "+
"find what's using them with: sudo lsof -i :%d, "+
"then stop the conflicting service and retry 'obol stack up'",
formatPorts(blocked), blocked[0],
)
}
return nil
}
// isPortOccupiedProc checks whether a TCP port has a listener by scanning
// /proc/net/tcp and /proc/net/tcp6. This works without root and is the only
// reliable way to detect occupancy of privileged ports on Linux where
// net.Listen returns "permission denied" regardless of whether the port is free.
func isPortOccupiedProc(port int) bool {
hexPort := fmt.Sprintf("%04X", port)
for _, path := range []string{"/proc/net/tcp6", "/proc/net/tcp"} {
f, err := os.Open(path)
if err != nil {
continue
}
found := false
scanner := bufio.NewScanner(f)
scanner.Scan() // skip header line
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
// /proc/net/tcp fields: sl local_address rem_address st ...
// state 0A = TCP_LISTEN; local_address = hexIP:hexPort
if len(fields) < 4 || fields[3] != "0A" {
continue
}
parts := strings.SplitN(fields[1], ":", 2)
if len(parts) == 2 && strings.EqualFold(parts[1], hexPort) {
found = true
break
}
}
f.Close()
if found {
return true
}
}
return false
}
func formatPorts(ports []int) string {
strs := make([]string, len(ports))
for i, p := range ports {
strs[i] = strconv.Itoa(p)
}
return strings.Join(strs, ", ")
}
func migrateDefaultsHTTPRouteHostnames(helmfilePath string) error {
data, err := os.ReadFile(helmfilePath)
if err != nil {
return err
}
needle := " hostnames:\n - obol.stack\n"
s := string(data)
if !strings.Contains(s, needle) {
return nil
}
updated := strings.ReplaceAll(s, needle, "")
if updated == s {
return nil
}
return os.WriteFile(helmfilePath, []byte(updated), 0o600) //nolint:gosec // G703: path from user's local config dir
}