services.go
692 lines1
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
package controllers
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"strings"
"congo.gg/dev/internal"
"congo.gg/dev/models"
"congo.gg/pkg/application"
"congo.gg/pkg/router"
)
func Services() (string, *ServicesController) {
return "services", &ServicesController{}
}
type ServicesController struct {
application.BaseController
}
func (c *ServicesController) Setup(app *application.App) {
c.BaseController.Setup(app)
// Service detail page — identified by repo/service from infra.json
app.Handle("GET /services/{repo}/{service}", app.Serve("service.html", RequireAuth()))
app.Handle("POST /services/deploy", app.Method(c, "Deploy", RequireAuth()))
app.Handle("POST /services/{repo}/{service}/stop", app.Method(c, "Stop", RequireAuth()))
app.Handle("POST /services/{repo}/{service}/start", app.Method(c, "Start", RequireAuth()))
app.Handle("POST /services/{repo}/{service}/restart", app.Method(c, "Restart", RequireAuth()))
app.Handle("POST /services/{repo}/{service}/redeploy", app.Method(c, "Redeploy", RequireAuth()))
app.Handle("GET /services/{repo}/{service}/logs", app.Method(c, "Logs", RequireAuth()))
app.Handle("POST /services/{repo}/{service}/domain", app.Method(c, "SetDomain", RequireAuth()))
app.Handle("POST /services/{repo}/{service}/delete", app.Method(c, "Delete", RequireAuth()))
app.Handle("POST /services/{repo}/{service}/env", app.Method(c, "UpdateEnv", RequireAuth()))
app.Handle("POST /services/{repo}/{service}/settings", app.Method(c, "UpdateSettings", RequireAuth()))
app.Handle("POST /services/{repo}/{service}/run-binary", app.Method(c, "RunBinary", RequireAuth()))
app.Handle("POST /services/{repo}/{service}/stop-binary", app.Method(c, "StopBinary", RequireAuth()))
app.Handle("POST /services/{repo}/launch", app.Method(c, "LaunchRemote", RequireAuth()))
}
// ─── Template methods ───────────────────────────────────────────────────────
// Service returns the current service from infra.json + Docker state.
func (c *ServicesController) Service() *internal.LocalService {
repoName := c.PathValue("repo")
serviceName := c.PathValue("service")
if repoName == "" || serviceName == "" {
return nil
}
svc, _ := internal.GetService(repoName, serviceName)
return svc
}
func (c *ServicesController) ServiceUptime() string {
svc := c.Service()
if svc == nil {
return ""
}
ct, err := internal.InspectContainer(svc.ContainerName)
if err != nil {
return ""
}
return ct.Status
}
// ServiceDomainID returns the Domain record ID for DNS check.
func (c *ServicesController) ServiceDomainID() string {
svc := c.Service()
if svc == nil {
return ""
}
dom, _ := models.Domains.First("WHERE ContainerName = ?", svc.ContainerName)
if dom == nil {
return ""
}
return dom.ID
}
// ServiceHistory returns recent log entries for this service.
func (c *ServicesController) ServiceHistory() []*models.LogEntry {
svc := c.Service()
if svc == nil {
return nil
}
entries, _ := models.LogEntries.Search(
"WHERE (Type IN ('deploy', 'start', 'stop', 'restart', 'delete_service')) AND Summary LIKE ? ORDER BY CreatedAt DESC LIMIT 10",
"%"+svc.Name+"%",
)
return entries
}
// AllServices returns all services from all projects' infra.json files.
func (c *ServicesController) AllServices() []internal.LocalService {
return internal.AllLocalServices()
}
// AvailableRepos returns repos available for deployment.
func (c *ServicesController) AvailableRepos() []*models.Repository {
repos, _ := models.Repositories.Search("WHERE Status != 'missing' ORDER BY Name")
return repos
}
// EnvJSON returns the service env as a JSON string (for EnvEditor component).
func (c *ServicesController) EnvJSON() string {
svc := c.Service()
if svc == nil || len(svc.Spec.Env) == 0 {
return "{}"
}
data, _ := json.Marshal(svc.Spec.Env)
return string(data)
}
// VolumesJSON returns the service volumes as a JSON string (for VolumeEditor component).
func (c *ServicesController) VolumesJSON() string {
svc := c.Service()
if svc == nil || len(svc.Spec.Volumes) == 0 {
return "[]"
}
// Convert InfraVolumeMount to the format VolumeEditor expects
type volUI struct {
Host string `json:"host"`
Container string `json:"container"`
}
var vols []volUI
for _, v := range svc.Spec.Volumes {
vols = append(vols, volUI{Host: v.Source, Container: v.Target})
}
data, _ := json.Marshal(vols)
return string(data)
}
// ─── Handlers ───────────────────────────────────────────────────────────────
func (c *ServicesController) Deploy(w http.ResponseWriter, r *http.Request) {
repoID := r.FormValue("repo_id")
if repoID == "" {
c.RenderError(w, r, fmt.Errorf("select a repository to deploy"))
return
}
repo, err := models.Repositories.Get(repoID)
if err != nil {
c.RenderError(w, r, fmt.Errorf("repository not found"))
return
}
// Determine service name — use existing from infra.json or default to "app"
serviceName := strings.TrimSpace(r.FormValue("service_name"))
if serviceName == "" {
serviceName = "app"
}
containerPort := 5000
if cp := r.FormValue("container_port"); cp != "" {
if parsed, err := strconv.Atoi(cp); err == nil && parsed > 0 && parsed <= 65535 {
containerPort = parsed
}
}
// Build service spec — no host port mapping by default.
// All HTTP traffic goes through the reverse proxy on the internal Docker network.
spec := internal.InfraService{
Source: ".",
Network: "internal",
Ports: []internal.InfraPort{
{Container: containerPort},
},
}
// Parse volumes from form if provided
if volJSON := strings.TrimSpace(r.FormValue("volumes")); volJSON != "" {
var vols []struct {
Host string `json:"host"`
Container string `json:"container"`
}
if json.Unmarshal([]byte(volJSON), &vols) == nil {
for _, v := range vols {
if v.Host != "" && v.Container != "" {
spec.Volumes = append(spec.Volumes, internal.InfraVolumeMount{Source: v.Host, Target: v.Container})
}
}
}
}
// Build path
if bp := strings.TrimSpace(r.FormValue("build_path")); bp != "" && bp != "." {
spec.Source = bp
}
// Check if container already exists
containerName := internal.ContainerNameFor(repo.Name, serviceName)
if internal.IsContainerRunning(containerName) {
c.RenderError(w, r, fmt.Errorf("service %s/%s is already running", repo.Name, serviceName))
return
}
// Write to infra.json
if err := internal.AddService(repo.Name, serviceName, spec); err != nil {
c.RenderError(w, r, err)
return
}
// Build and run in background
imageName := internal.ImageNameFor(repo.Name, serviceName)
go func() {
repoLocalPath := internal.LocalRepoPath(repo.Path)
buildCtx := repoLocalPath
dockerfilePath := ""
if spec.Source != "" && spec.Source != "." {
dockerfilePath = repoLocalPath + "/" + strings.TrimSuffix(spec.Source, "/") + "/Dockerfile"
}
if err := internal.BuildImage(buildCtx, imageName, dockerfilePath); err != nil {
models.LogEntries.Insert(&models.LogEntry{
Type: "deploy",
Summary: fmt.Sprintf("Deploy failed for %s/%s: %v", repo.Name, serviceName, err),
Author: "system",
})
return
}
internal.RemoveContainer(containerName)
err := internal.RunContainer(containerName, imageName, internal.RunOptions{
Network: "internal",
Ports: infraExposedPorts(spec.Ports),
Detach: true,
Restart: "unless-stopped",
Env: spec.Env,
Volumes: infraVolumesToMap(spec.Volumes),
})
if err != nil {
models.LogEntries.Insert(&models.LogEntry{
Type: "deploy",
Summary: fmt.Sprintf("Deploy failed for %s/%s: %v", repo.Name, serviceName, err),
Author: "system",
})
return
}
models.LogEntries.Insert(&models.LogEntry{
Type: "deploy",
Summary: fmt.Sprintf("Deployed %s/%s", repo.Name, serviceName),
Author: "system",
})
}()
c.Redirect(w, r, "/")
}
func (c *ServicesController) Stop(w http.ResponseWriter, r *http.Request) {
repoName := r.PathValue("repo")
serviceName := r.PathValue("service")
containerName := internal.ContainerNameFor(repoName, serviceName)
internal.StopContainer(containerName)
models.LogEntries.Insert(&models.LogEntry{
Type: "stop",
Summary: fmt.Sprintf("Stopped %s/%s", repoName, serviceName),
Author: "system",
})
c.Refresh(w, r)
}
func (c *ServicesController) Start(w http.ResponseWriter, r *http.Request) {
repoName := r.PathValue("repo")
serviceName := r.PathValue("service")
containerName := internal.ContainerNameFor(repoName, serviceName)
internal.StartContainer(containerName)
models.LogEntries.Insert(&models.LogEntry{
Type: "start",
Summary: fmt.Sprintf("Started %s/%s", repoName, serviceName),
Author: "system",
})
c.Refresh(w, r)
}
func (c *ServicesController) Restart(w http.ResponseWriter, r *http.Request) {
repoName := r.PathValue("repo")
serviceName := r.PathValue("service")
containerName := internal.ContainerNameFor(repoName, serviceName)
go func() {
internal.StopContainer(containerName)
internal.StartContainer(containerName)
models.LogEntries.Insert(&models.LogEntry{
Type: "restart",
Summary: fmt.Sprintf("Restarted %s/%s", repoName, serviceName),
Author: "system",
})
}()
c.Refresh(w, r)
}
func (c *ServicesController) RunBinary(w http.ResponseWriter, r *http.Request) {
repoName := r.PathValue("repo")
serviceName := r.PathValue("service")
svc, err := internal.GetService(repoName, serviceName)
if err != nil {
c.RenderError(w, r, err)
return
}
// Stop any existing binary process
internal.StopBinary(repoName, serviceName)
go func() {
source := svc.Spec.Source
if source == "" {
source = "."
}
if err := internal.BuildBinary(repoName, source, serviceName); err != nil {
models.LogEntries.Insert(&models.LogEntry{
Type: "deploy",
Summary: fmt.Sprintf("Binary build failed for %s/%s: %v", repoName, serviceName, err),
Author: "system",
})
return
}
port := svc.ContainerPort
if port == 0 {
port = 5000
}
env := make(map[string]string)
for k, v := range svc.Spec.Env {
env[k] = v
}
env["PORT"] = fmt.Sprintf("%d", port)
if err := internal.RunBinary(repoName, serviceName, env); err != nil {
models.LogEntries.Insert(&models.LogEntry{
Type: "deploy",
Summary: fmt.Sprintf("Binary run failed for %s/%s: %v", repoName, serviceName, err),
Author: "system",
})
return
}
models.LogEntries.Insert(&models.LogEntry{
Type: "deploy",
Summary: fmt.Sprintf("Started %s/%s as binary (port %d)", repoName, serviceName, port),
Author: "system",
})
}()
c.Refresh(w, r)
}
func (c *ServicesController) StopBinary(w http.ResponseWriter, r *http.Request) {
repoName := r.PathValue("repo")
serviceName := r.PathValue("service")
internal.StopBinary(repoName, serviceName)
models.LogEntries.Insert(&models.LogEntry{
Type: "stop",
Summary: fmt.Sprintf("Stopped binary %s/%s", repoName, serviceName),
Author: "system",
})
c.Refresh(w, r)
}
func (c *ServicesController) Redeploy(w http.ResponseWriter, r *http.Request) {
repoName := r.PathValue("repo")
serviceName := r.PathValue("service")
svc, err := internal.GetService(repoName, serviceName)
if err != nil {
c.RenderError(w, r, err)
return
}
repo, _ := models.Repositories.First("WHERE Name = ?", repoName)
if repo == nil {
c.RenderError(w, r, fmt.Errorf("repository %s not found", repoName))
return
}
go func() {
containerName := svc.ContainerName
repoLocalPath := internal.LocalRepoPath(repo.Path)
imageName := svc.Image
buildCtx := repoLocalPath
dockerfilePath := ""
if svc.Spec.Source != "" && svc.Spec.Source != "." {
dockerfilePath = repoLocalPath + "/" + strings.TrimSuffix(svc.Spec.Source, "/") + "/Dockerfile"
}
if err := internal.BuildImage(buildCtx, imageName, dockerfilePath); err != nil {
models.LogEntries.Insert(&models.LogEntry{
Type: "deploy",
Summary: fmt.Sprintf("Redeploy failed for %s/%s: %v", repoName, serviceName, err),
Author: "system",
})
return
}
internal.StopContainer(containerName)
internal.RemoveContainer(containerName)
err := internal.RunContainer(containerName, imageName, internal.RunOptions{
Network: "internal",
Ports: infraExposedPorts(svc.Spec.Ports),
Detach: true,
Restart: "unless-stopped",
Env: svc.Spec.Env,
Volumes: infraVolumesToMap(svc.Spec.Volumes),
})
if err != nil {
models.LogEntries.Insert(&models.LogEntry{
Type: "deploy",
Summary: fmt.Sprintf("Redeploy failed for %s/%s: %v", repoName, serviceName, err),
Author: "system",
})
return
}
models.LogEntries.Insert(&models.LogEntry{
Type: "deploy",
Summary: fmt.Sprintf("Redeployed %s/%s", repoName, serviceName),
Author: "system",
})
}()
c.Refresh(w, r)
}
func (c *ServicesController) Logs(w http.ResponseWriter, r *http.Request) {
repoName := r.PathValue("repo")
serviceName := r.PathValue("service")
svc, _ := internal.GetService(repoName, serviceName)
var logs string
if svc != nil && svc.Mode == "binary" {
logs, _ = internal.BinaryLogs(repoName, serviceName, 100)
} else {
containerName := internal.ContainerNameFor(repoName, serviceName)
logs, _ = internal.ContainerLogs(containerName, 100)
}
c.Render(w, r, "service-logs.html", logs)
}
func (c *ServicesController) SetDomain(w http.ResponseWriter, r *http.Request) {
repoName := r.PathValue("repo")
serviceName := r.PathValue("service")
containerName := internal.ContainerNameFor(repoName, serviceName)
svc, err := internal.GetService(repoName, serviceName)
if err != nil {
c.RenderError(w, r, err)
return
}
domain := strings.TrimSpace(r.FormValue("domain"))
// Update infra.json with domain
svc.Spec.Domain = domain
internal.UpdateService(repoName, serviceName, svc.Spec)
// For binary services, the reverse proxy routes to the code-server container
target := containerName
if svc.Mode == "binary" {
target = "congo-dev-coder"
}
// Update Domain records for reverse proxy routing
existing, _ := models.Domains.First("WHERE ContainerName = ?", containerName)
if domain == "" {
if existing != nil {
models.Domains.Delete(existing)
models.LogEntries.Insert(&models.LogEntry{
Type: "update_route",
Summary: fmt.Sprintf("Removed domain from %s/%s", repoName, serviceName),
Author: "system",
})
}
} else if existing != nil {
existing.Host = domain
existing.Target = target
existing.Active = true
models.Domains.Update(existing)
models.LogEntries.Insert(&models.LogEntry{
Type: "update_route",
Summary: fmt.Sprintf("Updated domain for %s/%s to %s", repoName, serviceName, domain),
Author: "system",
})
} else {
cp := svc.ContainerPort
if cp == 0 {
cp = 5000
}
models.Domains.Insert(&models.Domain{
Host: domain,
Target: target,
Port: cp,
ContainerName: containerName,
Active: true,
})
models.LogEntries.Insert(&models.LogEntry{
Type: "add_route",
Summary: fmt.Sprintf("Mapped %s to %s/%s", domain, repoName, serviceName),
Author: "system",
})
}
// Add domain to router (validates DNS, provisions TLS)
if domain != "" {
if err := router.AllowDomain(domain); err != nil {
log.Printf("[warn] domain %s: %v", domain, err)
}
router.Proxy(domain, fmt.Sprintf("%s:%d", target, svc.ContainerPort))
}
c.Refresh(w, r)
}
func (c *ServicesController) Delete(w http.ResponseWriter, r *http.Request) {
repoName := r.PathValue("repo")
serviceName := r.PathValue("service")
containerName := internal.ContainerNameFor(repoName, serviceName)
// Stop any running process (binary or Docker)
internal.StopBinary(repoName, serviceName)
internal.StopContainer(containerName)
internal.RemoveContainer(containerName)
// Remove domain records and cert allowlist entries
domains, _ := models.Domains.Search("WHERE ContainerName = ?", containerName)
for _, d := range domains {
router.DisallowDomain(d.Host)
router.RemoveProxy(d.Host)
models.Domains.Delete(d)
}
// Remove from infra.json
internal.RemoveService(repoName, serviceName)
models.LogEntries.Insert(&models.LogEntry{
Type: "delete_service",
Summary: fmt.Sprintf("Deleted service %s/%s", repoName, serviceName),
Author: "system",
})
c.Redirect(w, r, "/")
}
func (c *ServicesController) UpdateEnv(w http.ResponseWriter, r *http.Request) {
repoName := r.PathValue("repo")
serviceName := r.PathValue("service")
svc, err := internal.GetService(repoName, serviceName)
if err != nil {
c.RenderError(w, r, err)
return
}
envJSON := r.FormValue("env")
var env map[string]string
if envJSON != "" {
json.Unmarshal([]byte(envJSON), &env)
}
svc.Spec.Env = env
internal.UpdateService(repoName, serviceName, svc.Spec)
c.Refresh(w, r)
}
func (c *ServicesController) UpdateSettings(w http.ResponseWriter, r *http.Request) {
repoName := r.PathValue("repo")
serviceName := r.PathValue("service")
svc, err := internal.GetService(repoName, serviceName)
if err != nil {
c.RenderError(w, r, err)
return
}
// Update source/build path
if bp := strings.TrimSpace(r.FormValue("build_path")); bp != "" {
svc.Spec.Source = bp
}
// Update container (listen) port
if cp := r.FormValue("container_port"); cp != "" {
if parsed, err := strconv.Atoi(cp); err == nil && parsed > 0 && parsed <= 65535 {
if len(svc.Spec.Ports) > 0 {
svc.Spec.Ports[0].Container = parsed
} else {
svc.Spec.Ports = []internal.InfraPort{{Container: parsed}}
}
// Update domain record port for reverse proxy routing
dom, _ := models.Domains.First("WHERE ContainerName = ?", svc.ContainerName)
if dom != nil {
dom.Port = parsed
models.Domains.Update(dom)
}
}
}
// Update explicit host port exposures (for SMTP, etc.)
exposePorts := strings.TrimSpace(r.FormValue("expose_ports"))
// Rebuild ports: keep listen port (first entry, Host=0), add explicit bindings
listenPort := 5000
if len(svc.Spec.Ports) > 0 {
listenPort = svc.Spec.Ports[0].Container
}
svc.Spec.Ports = []internal.InfraPort{{Container: listenPort}}
if exposePorts != "" {
for _, pair := range strings.Split(exposePorts, ",") {
pair = strings.TrimSpace(pair)
parts := strings.SplitN(pair, ":", 2)
if len(parts) == 2 {
host, err1 := strconv.Atoi(strings.TrimSpace(parts[0]))
container, err2 := strconv.Atoi(strings.TrimSpace(parts[1]))
if err1 == nil && err2 == nil && host > 0 && container > 0 {
svc.Spec.Ports = append(svc.Spec.Ports, internal.InfraPort{Host: host, Container: container})
}
}
}
}
internal.UpdateService(repoName, serviceName, svc.Spec)
c.Refresh(w, r)
}
func (c *ServicesController) LaunchRemote(w http.ResponseWriter, r *http.Request) {
repoName := r.PathValue("repo")
repo, _ := models.Repositories.First("WHERE Name = ?", repoName)
if repo == nil {
c.RenderError(w, r, fmt.Errorf("repository %s not found", repoName))
return
}
models.LogEntries.Insert(&models.LogEntry{
Type: "launch",
Summary: fmt.Sprintf("Starting remote deploy of %s...", repoName),
Author: "system",
})
go func() {
output, err := internal.CoderExec(fmt.Sprintf(
"cd /home/coder/repos/%s && congo launch 2>&1 | tail -5", repoName,
))
if err != nil {
models.LogEntries.Insert(&models.LogEntry{
Type: "launch",
Summary: fmt.Sprintf("Remote deploy of %s failed: %v", repoName, err),
Author: "system",
})
return
}
models.LogEntries.Insert(&models.LogEntry{
Type: "launch",
Summary: fmt.Sprintf("Remote deploy of %s completed: %s", repoName, strings.TrimSpace(output)),
Author: "system",
})
}()
c.Refresh(w, r)
}
// infraExposedPorts returns only explicitly host-bound ports for docker run -p.
// Most services don't need host ports — the reverse proxy routes via the internal Docker network.
func infraExposedPorts(ports []internal.InfraPort) map[int]int {
m := make(map[int]int)
for _, p := range ports {
if p.Host > 0 {
m[p.Host] = p.Container
}
}
return m
}
// infraVolumesToMap converts infra.json volume mounts to the map format for RunOptions.
func infraVolumesToMap(vols []internal.InfraVolumeMount) map[string]string {
if len(vols) == 0 {
return nil
}
m := make(map[string]string)
for _, v := range vols {
if v.Source != "" && v.Target != "" {
m[v.Source] = v.Target
}
}
return m
}