-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathvibebin.go
More file actions
4579 lines (4093 loc) · 171 KB
/
vibebin.go
File metadata and controls
4579 lines (4093 loc) · 171 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
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"database/sql"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"time"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
_ "modernc.org/sqlite"
)
// Configuration
const (
CaddyConfDir = "/etc/caddy/conf.d"
SSHPiperRoot = "/var/lib/sshpiper"
DBPath = "/var/lib/vibebin/containers.db"
PIDFile = "/var/run/vibebin.pid"
DefaultAppPort = 8000
CodeUIPort = 9999 // opencode/nanocode web UI port
AdminPort = 8099 // AI tools admin app port
)
// Container image options
type containerImage int
const (
imageUbuntu containerImage = iota
imageDebian
)
func (i containerImage) String() string {
switch i {
case imageUbuntu:
return "images:ubuntu/noble" // Ubuntu 24.04 LTS
case imageDebian:
return "images:debian/13" // Debian 13 (Trixie)
}
return "images:ubuntu/noble"
}
func (i containerImage) User() string {
switch i {
case imageUbuntu:
return "ubuntu"
case imageDebian:
return "debian"
}
return "ubuntu"
}
func (i containerImage) DisplayName() string {
switch i {
case imageUbuntu:
return "Ubuntu 24.04 LTS (Noble)"
case imageDebian:
return "Debian 13 (Trixie)"
}
return "Ubuntu 24.04 LTS (Noble)"
}
// State machine for TUI
type viewState int
const (
stateLoading viewState = iota
stateInstalling
stateList
stateCreateDomain
stateCreateImage // Select container image (Ubuntu/Debian)
stateCreateDNSProvider
stateCreateDNSToken
stateCreateCFProxy
stateCreateAppPort
stateCreateSSHKey
stateCreateAuthUser
stateCreateAuthPass
stateContainerDetail
stateEditAppPort
stateEditAuthUser
stateEditAuthPass
stateUpdateTools // Update opencode/nanocode
stateLogs
stateUntracked
stateImportContainer
stateImportImage // Select image for imported container
stateImportAuthUser
stateImportAuthPass
stateSnapshots // View/manage snapshots
stateSnapshotCreate // Create new snapshot (name input)
stateSnapshotRestore // Confirm restore from snapshot
stateSnapshotDelete // Confirm delete snapshot
stateDNSTokens // View/manage DNS API tokens
stateDNSTokenEdit // Edit/add DNS token
stateCreating // Container creation in progress
stateConfirmDelete // Confirm container deletion
)
// DNS Provider types
type dnsProvider int
const (
dnsNone dnsProvider = iota
dnsCloudflare
dnsDesec
)
// Container entry from database
type containerEntry struct {
ID int
Name string
Domain string
AppPort int
Status string
IP string
CPU string
Memory string
CreatedAt time.Time
}
// Snapshot entry from Incus
type snapshotEntry struct {
Name string
CreatedAt time.Time
Stateful bool
}
// Messages for async operations
type (
bootstrapDoneMsg struct{ db *sql.DB; err error }
installNeededMsg []string
installDoneMsg struct{ err error }
containersMsg []containerEntry
logMsg string
errorMsg string
successMsg string
tickMsg time.Time
createDoneMsg struct{ err error; name string; output string } // Container creation completed
clearStatusMsg struct{} // Clear status message
toolsUpdateMsg struct{ output string; success bool } // opencode/nanocode update result
)
// TUI Model
type model struct {
state viewState
db *sql.DB
containers []containerEntry
cursor int
textInput textinput.Model
status string
logContent string
currentSvc string
missing []string
updateOutput string // Output from opencode/nanocode update command
updateSuccess bool // Whether tools update succeeded
// Create flow state
newDomain string
newImage containerImage // Selected container image
newDNSProvider dnsProvider
newDNSToken string
newCFProxy bool // Cloudflare proxy enabled
newAppPort int
newSSHKey string
newAuthUser string
newAuthPass string
// Untracked containers
untrackedContainers []string
// Edit state
editingContainer *containerEntry
// Snapshot management
snapshots []snapshotEntry
snapshotCursor int
newSnapshotName string
// DNS token editing
editingDNSProvider dnsProvider
// Container creation progress
createOutput string
}
func initialModel() model {
ti := textinput.New()
ti.Width = 60
return model{
state: stateLoading,
textInput: ti,
}
}
// isInputState returns true if the current state requires text input
func (m model) isInputState() bool {
switch m.state {
case stateCreateDomain, stateCreateDNSToken, stateCreateAppPort, stateCreateSSHKey,
stateCreateAuthUser, stateCreateAuthPass,
stateEditAppPort, stateEditAuthUser, stateEditAuthPass,
stateImportContainer, stateImportAuthUser, stateImportAuthPass,
stateSnapshotCreate, stateDNSTokenEdit:
return true
}
return false
}
func (m model) Init() tea.Cmd {
return checkPrerequisitesCmd()
}
// isVersionAtLeast checks if version string (e.g., "6.20") is >= major.minor
func isVersionAtLeast(ver string, major, minor int) bool {
parts := strings.Split(ver, ".")
if len(parts) < 1 {
return false
}
var verMajor, verMinor int
fmt.Sscanf(parts[0], "%d", &verMajor)
if len(parts) > 1 {
fmt.Sscanf(parts[1], "%d", &verMinor)
}
if verMajor > major {
return true
}
if verMajor == major && verMinor >= minor {
return true
}
return false
}
func clearStatusAfterDelay() tea.Cmd {
return tea.Tick(4*time.Second, func(t time.Time) tea.Msg {
return clearStatusMsg{}
})
}
func tickCmd() tea.Cmd {
return tea.Every(2*time.Second, func(t time.Time) tea.Msg { return tickMsg(t) })
}
// Check what needs to be installed
func checkPrerequisitesCmd() tea.Cmd {
return func() tea.Msg {
var missing []string
// Check incus (need 6.3+ from zabbly for OCI support)
out, err := exec.Command("incus", "version").CombinedOutput()
if err != nil || strings.Contains(string(out), "unreachable") || strings.Contains(string(out), "Error") {
missing = append(missing, "incus")
} else {
// Check version - need 6.3+ for OCI image support
lines := strings.Split(string(out), "\n")
for _, line := range lines {
if strings.HasPrefix(line, "Client version:") {
ver := strings.TrimSpace(strings.TrimPrefix(line, "Client version:"))
if !isVersionAtLeast(ver, 6, 3) {
missing = append(missing, "incus")
}
break
}
}
}
// Check caddy
if _, err := exec.LookPath("caddy"); err != nil {
missing = append(missing, "caddy")
}
// Check sshpiperd
if _, err := exec.LookPath("sshpiperd"); err != nil {
if _, err := os.Stat("/usr/local/bin/sshpiperd"); os.IsNotExist(err) {
missing = append(missing, "sshpiperd")
}
}
if len(missing) > 0 {
return installNeededMsg(missing)
}
return bootstrapCmd()()
}
}
// Install missing dependencies
func installDependenciesCmd(missing []string) tea.Cmd {
return func() tea.Msg {
for _, dep := range missing {
switch dep {
case "incus":
if err := installIncus(); err != nil {
return installDoneMsg{err: fmt.Errorf("incus install failed: %w", err)}
}
case "caddy":
if err := installCaddy(); err != nil {
return installDoneMsg{err: fmt.Errorf("caddy install failed: %w", err)}
}
case "sshpiperd":
if err := installSSHPiper(); err != nil {
return installDoneMsg{err: fmt.Errorf("sshpiperd install failed: %w", err)}
}
}
}
return installDoneMsg{}
}
}
func installIncus() error {
// Add Zabbly GPG key
if err := os.MkdirAll("/etc/apt/keyrings", 0755); err != nil {
return err
}
resp, err := http.Get("https://pkgs.zabbly.com/key.asc")
if err != nil {
return err
}
defer resp.Body.Close()
keyData, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
if err := os.WriteFile("/etc/apt/keyrings/zabbly.asc", keyData, 0644); err != nil {
return err
}
// Get OS codename
osRelease, _ := os.ReadFile("/etc/os-release")
codename := "noble" // default
for _, line := range strings.Split(string(osRelease), "\n") {
if strings.HasPrefix(line, "VERSION_CODENAME=") {
codename = strings.TrimPrefix(line, "VERSION_CODENAME=")
break
}
}
// Get architecture
arch := "amd64"
out, _ := exec.Command("dpkg", "--print-architecture").Output()
if len(out) > 0 {
arch = strings.TrimSpace(string(out))
}
// Add Zabbly stable repository
repoContent := fmt.Sprintf(`Enabled: yes
Types: deb
URIs: https://pkgs.zabbly.com/incus/stable
Suites: %s
Components: main
Architectures: %s
Signed-By: /etc/apt/keyrings/zabbly.asc
`, codename, arch)
if err := os.WriteFile("/etc/apt/sources.list.d/zabbly-incus-stable.sources", []byte(repoContent), 0644); err != nil {
return err
}
// Update and install
if err := exec.Command("apt-get", "update").Run(); err != nil {
return err
}
if err := exec.Command("apt-get", "install", "-y", "incus").Run(); err != nil {
return err
}
// Initialize incus
exec.Command("systemctl", "enable", "--now", "incus").Run()
time.Sleep(2 * time.Second)
exec.Command("incus", "admin", "init", "--minimal").Run()
// Add current user to incus-admin group
user := os.Getenv("SUDO_USER")
if user == "" {
user = os.Getenv("USER")
}
if user != "" && user != "root" {
exec.Command("usermod", "-aG", "incus-admin", user).Run()
}
return nil
}
func installCaddy() error {
// Install caddy via apt
exec.Command("apt-get", "update").Run()
if err := exec.Command("apt-get", "install", "-y", "caddy").Run(); err != nil {
return err
}
exec.Command("systemctl", "enable", "--now", "caddy").Run()
return nil
}
func installSSHPiper() error {
// Download sshpiperd from GitHub releases
arch := "x86_64"
out, _ := exec.Command("uname", "-m").Output()
if strings.Contains(string(out), "aarch64") || strings.Contains(string(out), "arm64") {
arch = "arm64"
}
url := fmt.Sprintf("https://github.com/tg123/sshpiper/releases/latest/download/sshpiperd_with_plugins_linux_%s.tar.gz", arch)
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
tmpFile := "/tmp/sshpiperd.tar.gz"
f, err := os.Create(tmpFile)
if err != nil {
return err
}
io.Copy(f, resp.Body)
f.Close()
// Extract to temp directory first
tmpDir := "/tmp/sshpiper-extract"
os.RemoveAll(tmpDir)
os.MkdirAll(tmpDir, 0755)
if err := exec.Command("tar", "-xzf", tmpFile, "-C", tmpDir).Run(); err != nil {
return err
}
// Copy main binary
os.MkdirAll("/usr/local/bin", 0755)
exec.Command("cp", tmpDir+"/sshpiperd", "/usr/local/bin/sshpiperd").Run()
os.Chmod("/usr/local/bin/sshpiperd", 0755)
// Copy plugins to /usr/local/bin so they're in PATH
plugins, _ := filepath.Glob(tmpDir + "/plugins/*")
for _, p := range plugins {
dest := "/usr/local/bin/" + filepath.Base(p)
exec.Command("cp", p, dest).Run()
os.Chmod(dest, 0755)
}
// Cleanup
os.RemoveAll(tmpDir)
os.Remove(tmpFile)
return nil
}
// Bootstrap: setup services, init DB
func bootstrapCmd() tea.Cmd {
return func() tea.Msg {
// Check incus daemon is running
out, err := exec.Command("incus", "version").CombinedOutput()
if err != nil || strings.Contains(string(out), "unreachable") {
// Try to start it
exec.Command("systemctl", "start", "incus").Run()
time.Sleep(2 * time.Second)
out, err = exec.Command("incus", "version").CombinedOutput()
if err != nil || strings.Contains(string(out), "unreachable") {
return bootstrapDoneMsg{err: fmt.Errorf("incus daemon not running")}
}
}
// Ensure directories exist
for _, dir := range []string{CaddyConfDir, SSHPiperRoot, filepath.Dir(DBPath), "/etc/sshpiper"} {
os.MkdirAll(dir, 0755)
}
// Setup Caddy import
setupCaddy()
// Setup SSHPiper service
setupSSHPiperService()
// Setup sync daemon
setupSyncDaemon()
// Open database
db, err := sql.Open("sqlite", DBPath)
if err != nil {
return bootstrapDoneMsg{err: err}
}
_, err = db.Exec(`CREATE TABLE IF NOT EXISTS containers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE NOT NULL,
domain TEXT UNIQUE NOT NULL,
app_port INTEGER DEFAULT 8000,
auth_user TEXT DEFAULT '',
auth_hash TEXT DEFAULT '',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)`)
if err != nil {
return bootstrapDoneMsg{err: err}
}
// Migration for existing DBs
db.Exec(`ALTER TABLE containers ADD COLUMN auth_user TEXT DEFAULT ''`)
db.Exec(`ALTER TABLE containers ADD COLUMN auth_hash TEXT DEFAULT ''`)
// DNS tokens table
db.Exec(`CREATE TABLE IF NOT EXISTS dns_tokens (
provider TEXT PRIMARY KEY,
token TEXT NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)`)
// Sync configs for all running containers (handles IP changes after reboot)
syncRunningContainers(db)
return bootstrapDoneMsg{db: db}
}
}
// syncRunningContainers updates Caddy and SSHPiper configs for all running containers
// This handles the case where container IPs changed after a reboot
func syncRunningContainers(db *sql.DB) {
rows, err := db.Query("SELECT name, domain, app_port, auth_user, auth_hash FROM containers")
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
var name, domain string
var appPort int
var authUser, authHash sql.NullString
if err := rows.Scan(&name, &domain, &appPort, &authUser, &authHash); err != nil {
continue
}
status, ip, _, _ := getContainerStatus(name)
if status == "running" && ip != "" {
updateCaddyConfig(name, domain, ip, appPort, authUser.String, authHash.String)
updateSSHPiperUpstream(name, ip)
}
}
}
func setupCaddy() {
// Ensure Caddy is running (API-based config management)
exec.Command("systemctl", "enable", "--now", "caddy").Run()
// Configure Caddy server with both HTTP and HTTPS listeners for automatic TLS
configureCaddyHTTPS()
}
func configureCaddyHTTPS() {
client := &http.Client{Timeout: 10 * time.Second}
caddyAPI := "http://localhost:2019"
// Check if server already has proper listen addresses
resp, err := client.Get(caddyAPI + "/config/apps/http/servers/srv0")
if err != nil {
return
}
defer resp.Body.Close()
var serverConfig map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&serverConfig); err != nil {
return
}
// Check if listen addresses include HTTPS (443)
listen, ok := serverConfig["listen"].([]interface{})
hasHTTPS := false
if ok {
for _, addr := range listen {
if addrStr, ok := addr.(string); ok && (strings.Contains(addrStr, ":443") || strings.Contains(addrStr, "https")) {
hasHTTPS = true
break
}
}
}
// If already configured with HTTPS, no changes needed
if hasHTTPS {
return
}
// Set up proper listen addresses for both HTTP and HTTPS
// This enables automatic HTTPS certificate provisioning
listenAddrs := []string{":80", ":443"}
body, _ := json.Marshal(listenAddrs)
req, _ := http.NewRequest("PATCH", caddyAPI+"/config/apps/http/servers/srv0/listen", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
resp2, err := client.Do(req)
if err != nil {
return
}
resp2.Body.Close()
}
func setupSSHPiperService() {
// Generate server key if not exists
keyPath := "/etc/sshpiper/server_key"
if _, err := os.Stat(keyPath); os.IsNotExist(err) {
exec.Command("ssh-keygen", "-t", "ed25519", "-f", keyPath, "-N", "").Run()
}
// Write systemd service
service := `[Unit]
Description=SSHPiper SSH Proxy
After=network.target
[Service]
Type=simple
ExecStart=/usr/local/bin/sshpiperd -p 2222 -i /etc/sshpiper/server_key workingdir --root /var/lib/sshpiper --no-check-perm
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
`
os.WriteFile("/etc/systemd/system/sshpiperd.service", []byte(service), 0644)
exec.Command("systemctl", "daemon-reload").Run()
exec.Command("systemctl", "enable", "--now", "sshpiperd").Run()
}
func setupSyncDaemon() {
// Check if sync daemon binary exists at the expected location
binaryPath := "/usr/local/bin/vibebin_sync_daemon"
if _, err := os.Stat(binaryPath); os.IsNotExist(err) {
// Try alternate name
binaryPath = "/usr/local/bin/vibebin-sync-daemon"
if _, err := os.Stat(binaryPath); os.IsNotExist(err) {
// Try to copy from current directory
execPath, _ := os.Executable()
syncPath := filepath.Join(filepath.Dir(execPath), "vibebin_sync_daemon")
if _, err := os.Stat(syncPath); err == nil {
input, _ := os.ReadFile(syncPath)
os.WriteFile("/usr/local/bin/vibebin_sync_daemon", input, 0755)
binaryPath = "/usr/local/bin/vibebin_sync_daemon"
}
}
}
// Only write/update service file if it doesn't exist yet
serviceFile := "/etc/systemd/system/vibebin-sync.service"
if _, err := os.Stat(serviceFile); os.IsNotExist(err) {
service := `[Unit]
Description=Incus Container Sync Daemon
After=network.target incus.service
Wants=incus.service
[Service]
Type=simple
ExecStart=/usr/local/bin/vibebin_sync_daemon
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
`
os.WriteFile(serviceFile, []byte(service), 0644)
exec.Command("systemctl", "daemon-reload").Run()
}
// Always ensure the service is enabled and started
exec.Command("systemctl", "enable", "vibebin-sync").Run()
exec.Command("systemctl", "start", "vibebin-sync").Run()
}
// Container management functions
func (m *model) refreshContainers() tea.Cmd {
return func() tea.Msg {
if m.db == nil {
return containersMsg{}
}
rows, err := m.db.Query("SELECT id, name, domain, app_port, COALESCE(created_at, datetime('now')) FROM containers ORDER BY created_at DESC")
if err != nil {
return containersMsg{}
}
defer rows.Close()
var containers []containerEntry
for rows.Next() {
var c containerEntry
var createdAt string
if err := rows.Scan(&c.ID, &c.Name, &c.Domain, &c.AppPort, &createdAt); err != nil {
continue
}
// Try multiple date formats
if t, err := time.Parse("2006-01-02 15:04:05", createdAt); err == nil {
c.CreatedAt = t
} else if t, err := time.Parse(time.RFC3339, createdAt); err == nil {
c.CreatedAt = t
} else {
c.CreatedAt = time.Now() // Fallback to now if parsing fails
}
c.Status, c.IP, c.CPU, c.Memory = getContainerStatus(c.Name)
containers = append(containers, c)
}
return containersMsg(containers)
}
}
func getContainerStatus(name string) (status, ip, cpu, memory string) {
out, err := exec.Command("incus", "list", name, "--format=json").Output()
if err != nil {
return "unknown", "", "N/A", "N/A"
}
var list []struct {
Status string `json:"status"`
State struct {
CPU struct {
Usage int64 `json:"usage"`
} `json:"cpu"`
Memory struct {
Usage int64 `json:"usage"`
Total int64 `json:"total"`
} `json:"memory"`
Network map[string]struct {
Addresses []struct {
Address string `json:"address"`
Family string `json:"family"`
} `json:"addresses"`
} `json:"network"`
} `json:"state"`
}
if err := json.Unmarshal(out, &list); err != nil || len(list) == 0 {
return "not found", "", "N/A", "N/A"
}
status = strings.ToLower(list[0].Status)
// Get IP - prefer eth0, skip localhost and docker bridge networks
for netName, net := range list[0].State.Network {
for _, addr := range net.Addresses {
if addr.Family == "inet" &&
!strings.HasPrefix(addr.Address, "127.") &&
!strings.HasPrefix(addr.Address, "172.17.") && // Docker bridge
!strings.HasPrefix(addr.Address, "172.18.") { // Docker networks
// Prefer eth0 over other interfaces
if netName == "eth0" {
ip = addr.Address
break
} else if ip == "" {
ip = addr.Address
}
}
}
if ip != "" && netName == "eth0" {
break // Found eth0 IP, stop looking
}
}
// Format CPU time (nanoseconds to human readable)
// This is cumulative CPU time used, not current CPU percentage
if list[0].State.CPU.Usage > 0 {
cpuSec := float64(list[0].State.CPU.Usage) / 1e9
if cpuSec >= 3600 {
cpu = fmt.Sprintf("%.1fh", cpuSec/3600)
} else if cpuSec >= 60 {
cpu = fmt.Sprintf("%.1fm", cpuSec/60)
} else {
cpu = fmt.Sprintf("%.0fs", cpuSec)
}
} else {
cpu = "0s"
}
// Format Memory (bytes to MB/GB)
// Note: This is total memory usage including buffers/cache
if list[0].State.Memory.Usage > 0 {
memMB := float64(list[0].State.Memory.Usage) / (1024 * 1024)
if memMB >= 1024 {
memory = fmt.Sprintf("%.1fGB", memMB/1024)
} else {
memory = fmt.Sprintf("%.0fMB", memMB)
}
} else {
memory = "0MB"
}
return status, ip, cpu, memory
}
func isDomainInUse(db *sql.DB, domain string) bool {
var count int
db.QueryRow("SELECT COUNT(*) FROM containers WHERE domain = ?", domain).Scan(&count)
return count > 0
}
// getIncusContainers returns all container names from Incus API
func getIncusContainers() []string {
out, err := exec.Command("incus", "query", "/1.0/instances").Output()
if err != nil {
return nil
}
var paths []string
if err := json.Unmarshal(out, &paths); err != nil {
return nil
}
// Extract names from paths like "/1.0/instances/name"
var names []string
for _, p := range paths {
parts := strings.Split(p, "/")
if len(parts) > 0 {
names = append(names, parts[len(parts)-1])
}
}
return names
}
// getTrackedContainerNames returns container names from our database
func getTrackedContainerNames(db *sql.DB) []string {
if db == nil {
return nil
}
rows, err := db.Query("SELECT name FROM containers")
if err != nil {
return nil
}
defer rows.Close()
var names []string
for rows.Next() {
var name string
if rows.Scan(&name) == nil {
names = append(names, name)
}
}
return names
}
// getUntrackedContainers returns container names that exist in Incus but not in our DB
func getUntrackedContainers(db *sql.DB) []string {
incusContainers := getIncusContainers()
trackedContainers := getTrackedContainerNames(db)
// Create a set of tracked names
trackedSet := make(map[string]bool)
for _, name := range trackedContainers {
trackedSet[name] = true
}
// Find untracked
var untracked []string
for _, name := range incusContainers {
if !trackedSet[name] {
untracked = append(untracked, name)
}
}
return untracked
}
// getContainerOS detects the OS of a container (returns "debian", "ubuntu", or "unknown")
func getContainerOS(containerName string) string {
// Try to read /etc/os-release from the container
out, err := exec.Command("incus", "exec", containerName, "--", "cat", "/etc/os-release").Output()
if err != nil {
return "unknown"
}
osRelease := strings.ToLower(string(out))
if strings.Contains(osRelease, "id=debian") {
return "debian"
}
if strings.Contains(osRelease, "id=ubuntu") {
return "ubuntu"
}
return "unknown"
}
// createContainerWithProgress creates a container and sends progress updates via channel
func createContainerWithProgress(db *sql.DB, domain string, image containerImage, appPort int, sshKey string, dnsProvider dnsProvider, dnsToken string, cfProxy bool, authUser, authPass string, progress chan<- string) error {
sendProgress := func(msg string) {
if progress != nil {
select {
case progress <- msg:
default:
}
}
}
// Validate domain format
sendProgress("Validating domain format...")
if !isValidDomain(domain) {
return fmt.Errorf("invalid domain format: %s", domain)
}
// Generate container name from domain
name := strings.ReplaceAll(domain, ".", "-")
re := regexp.MustCompile(`[^a-zA-Z0-9-]`)
name = re.ReplaceAllString(name, "")
// Ensure name doesn't start with a digit (incus requirement)
if len(name) > 0 && name[0] >= '0' && name[0] <= '9' {
name = "c-" + name
}
if len(name) > 50 {
name = name[:50]
}
// Ensure name doesn't end with hyphen
name = strings.TrimSuffix(name, "-")
// Check if container name already exists in incus
if containerExistsInIncus(name) {
return fmt.Errorf("container name '%s' already exists", name)
}
// STEP 1: Create DNS records FIRST (if provider specified)
if dnsProvider != dnsNone && dnsToken != "" {
sendProgress("Creating DNS records...")
hostIP := getHostPublicIP()
if hostIP != "" {
sendProgress(fmt.Sprintf("Host IP: %s", hostIP))
// Create main domain record
sendProgress(fmt.Sprintf("Creating A record for %s...", domain))
if err := createDNSRecord(domain, hostIP, dnsProvider, dnsToken, cfProxy); err != nil {
sendProgress(fmt.Sprintf("❌ DNS error for %s: %v", domain, err))
} else {
sendProgress(fmt.Sprintf("✅ Created: %s -> %s", domain, hostIP))
}
// Create code subdomain (never proxied - needs direct access for websockets)
codeDomain := "code." + domain
sendProgress(fmt.Sprintf("Creating A record for %s...", codeDomain))
if err := createDNSRecord(codeDomain, hostIP, dnsProvider, dnsToken, false); err != nil {
sendProgress(fmt.Sprintf("❌ DNS error for %s: %v", codeDomain, err))
} else {
sendProgress(fmt.Sprintf("✅ Created: %s -> %s", codeDomain, hostIP))
}
// Create admin.code subdomain for admin app
adminDomain := "admin.code." + domain
sendProgress(fmt.Sprintf("Creating A record for %s...", adminDomain))
if err := createDNSRecord(adminDomain, hostIP, dnsProvider, dnsToken, false); err != nil {
sendProgress(fmt.Sprintf("❌ DNS error for %s: %v", adminDomain, err))
} else {
sendProgress(fmt.Sprintf("✅ Created: %s -> %s", adminDomain, hostIP))
}
// Wait for DNS propagation and verify
sendProgress("Waiting for DNS propagation (5s)...")
time.Sleep(5 * time.Second)
// Verify DNS records
sendProgress("Verifying DNS records...")
mainOK := checkDNSResolvesToHost(domain)
codeOK := checkDNSResolvesToHost(codeDomain)
adminOK := checkDNSResolvesToHost(adminDomain)
if mainOK {
sendProgress(fmt.Sprintf("✅ DNS verified: %s", domain))
} else {
sendProgress(fmt.Sprintf("⚠️ DNS not yet propagated: %s", domain))
}
if codeOK {
sendProgress(fmt.Sprintf("✅ DNS verified: %s", codeDomain))
} else {
sendProgress(fmt.Sprintf("⚠️ DNS not yet propagated: %s", codeDomain))
}
if adminOK {
sendProgress(fmt.Sprintf("✅ DNS verified: %s", adminDomain))
} else {
sendProgress(fmt.Sprintf("⚠️ DNS not yet propagated: %s", adminDomain))
}
} else {
sendProgress("❌ Could not determine host public IP")
}
}
// STEP 2: Clean up any stale container with same name
sendProgress("Cleaning up any stale containers...")
exec.Command("incus", "delete", name, "--force").Run()
// STEP 3: Launch container from native Incus image
sendProgress(fmt.Sprintf("Launching container from %s...", image.String()))
sendProgress("This may take a minute if the image needs to be downloaded...")
// Note: boot.autostart is intentionally NOT set - when unset, Incus uses "last-state"
// behavior which restores the container to its previous running/stopped state on daemon restart
cmd := exec.Command("incus", "launch", image.String(), name,
"-c", "security.nesting=true")
out, err := cmd.CombinedOutput()
if err != nil {
sendProgress(fmt.Sprintf("Error: %s", string(out)))
return fmt.Errorf("failed to create container: %s", string(out))
}
sendProgress(string(out))
// Wait for container to start and get basic networking
sendProgress("Waiting for container to initialize...")