infra.go

543 lines
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
package internal

import (
	"encoding/json"
	"fmt"
	"sort"
	"strings"
	"sync"

	"congo.gg/dev/models"
)

// InfraConfig mirrors the CLI's infra.json structure.
// The dev platform uses this as the source of truth for service definitions.
type InfraConfig struct {
	Platforms map[string]InfraPlatform   `json:"platforms,omitempty"`
	Servers   map[string]InfraServer     `json:"servers,omitempty"`
	Services  map[string]InfraService    `json:"services,omitempty"`
	Instances map[string][]InfraInstance `json:"instances,omitempty"`
}

type InfraPlatform struct {
	Provider string `json:"provider"`
	Token    string `json:"token,omitempty"`
	Region   string `json:"region,omitempty"`
}

type InfraServer struct {
	Platform string        `json:"platform,omitempty"`
	Size     string        `json:"size"`
	Setup    string        `json:"setup,omitempty"`
	Volumes  []InfraVolume `json:"volumes,omitempty"`
	Services []string      `json:"services,omitempty"`
}

type InfraVolume struct {
	Name  string `json:"name"`
	Size  int    `json:"size,omitempty"`
	Mount string `json:"mount"`
}

type InfraService struct {
	Image       string             `json:"image,omitempty"`
	Source      string             `json:"source,omitempty"`
	Setup       string             `json:"setup,omitempty"`
	Command     []string           `json:"command,omitempty"`
	Ports       []InfraPort        `json:"ports,omitempty"`
	Volumes     []InfraVolumeMount `json:"volumes,omitempty"`
	Env         map[string]string  `json:"env,omitempty"`
	EnvFiles    map[string]string  `json:"env_files,omitempty"`
	Network     string             `json:"network,omitempty"`
	Healthcheck string             `json:"healthcheck,omitempty"`
	Privileged  bool               `json:"privileged,omitempty"`
	Domain      string             `json:"domain,omitempty"`
}

type InfraPort struct {
	Host      int    `json:"host"`
	Container int    `json:"container"`
	Bind      string `json:"bind,omitempty"`
}

type InfraVolumeMount struct {
	Source string `json:"source"`
	Target string `json:"target"`
}

type InfraInstance struct {
	ID     string `json:"id,omitempty"`
	Name   string `json:"name"`
	IP     string `json:"ip,omitempty"`
	Region string `json:"region,omitempty"`
}

// LocalService combines an infra.json service definition with runtime Docker state.
type LocalService struct {
	RepoName      string       // project name
	RepoID        string       // repository ID for linking
	Name          string       // service name (key in infra.json services map)
	Spec          InfraService // full spec from infra.json
	ContainerName string       // Docker container name: "{repo}-{service}"
	Status        string       // running/stopped/not_deployed (from Docker or binary process)
	Mode          string       // "docker", "binary", or "" (not_deployed)
	ContainerPort int          // port the app listens on inside the container
	ExposedPorts  []InfraPort  // explicit host port bindings (edge cases like SMTP)
	Domain        string       // from Domain records
	Image         string       // Docker image name
}

// Slug returns a URL-safe identifier for this service.
func (s *LocalService) Slug() string {
	return s.RepoName + "/" + s.Name
}

// ContainerNameFor returns the Docker container name for a project service.
func ContainerNameFor(repoName, serviceName string) string {
	return repoName + "-" + serviceName
}

// ImageNameFor returns the Docker image name for a project service.
func ImageNameFor(repoName, serviceName string) string {
	return "congo-" + repoName + "-" + serviceName + ":latest"
}

// ─── Infra cache ────────────────────────────────────────────────────────────
// In-memory cache of project infra.json configs. Loaded on boot,
// updated on CRUD. Eliminates CoderExec calls from page loads.

var (
	infraCache   = make(map[string]*InfraConfig)
	infraCacheMu sync.RWMutex
)

// InitInfraCache loads all project infra.json files into memory.
// Call once at boot after code-server is ready.
func InitInfraCache() {
	repos, _ := models.Repositories.Search("WHERE Status != 'missing' ORDER BY Name")
	cache := make(map[string]*InfraConfig)
	for _, repo := range repos {
		cfg, err := readProjectInfraFromDisk(repo.Name)
		if err != nil {
			continue
		}
		cache[repo.Name] = cfg
	}
	infraCacheMu.Lock()
	infraCache = cache
	infraCacheMu.Unlock()
	fmt.Printf("congo-dev: cached infra for %d project(s)\n", len(cache))
}

// RefreshInfraCache reloads a single project's infra from disk into cache.
func RefreshInfraCache(repoName string) {
	cfg, err := readProjectInfraFromDisk(repoName)
	infraCacheMu.Lock()
	defer infraCacheMu.Unlock()
	if err != nil {
		delete(infraCache, repoName)
	} else {
		infraCache[repoName] = cfg
	}
}

// cachedInfra returns the cached infra config for a project.
func cachedInfra(repoName string) *InfraConfig {
	infraCacheMu.RLock()
	defer infraCacheMu.RUnlock()
	return infraCache[repoName]
}

// allCachedInfra returns a snapshot of all cached configs.
func allCachedInfra() map[string]*InfraConfig {
	infraCacheMu.RLock()
	defer infraCacheMu.RUnlock()
	copy := make(map[string]*InfraConfig, len(infraCache))
	for k, v := range infraCache {
		copy[k] = v
	}
	return copy
}

// ─── Disk I/O (used by cache init and CRUD) ─────────────────────────────────

// readProjectInfraFromDisk reads a project's infra.json via the code-server container.
func readProjectInfraFromDisk(repoName string) (*InfraConfig, error) {
	output, err := CoderExec(fmt.Sprintf("cat /home/coder/repos/%s/infra.json 2>/dev/null", repoName))
	if err != nil {
		return nil, fmt.Errorf("no infra.json found for %s", repoName)
	}

	var cfg InfraConfig
	if err := json.Unmarshal([]byte(output), &cfg); err != nil {
		return nil, fmt.Errorf("invalid infra.json: %w", err)
	}

	return &cfg, nil
}

// ReadProjectInfra returns the cached infra config, falling back to disk.
func ReadProjectInfra(repoName string) (*InfraConfig, error) {
	if cfg := cachedInfra(repoName); cfg != nil {
		return cfg, nil
	}
	// Cache miss — read from disk and cache
	cfg, err := readProjectInfraFromDisk(repoName)
	if err != nil {
		return nil, err
	}
	infraCacheMu.Lock()
	infraCache[repoName] = cfg
	infraCacheMu.Unlock()
	return cfg, nil
}

// WriteProjectInfra writes infra.json to a project via the code-server container
// and updates the cache.
func WriteProjectInfra(repoName string, cfg *InfraConfig) error {
	data, err := json.MarshalIndent(cfg, "", "  ")
	if err != nil {
		return fmt.Errorf("marshal infra.json: %w", err)
	}

	// Write via CoderExec — escape the JSON for shell
	escaped := strings.ReplaceAll(string(data), "'", "'\\''")
	_, err = CoderExec(fmt.Sprintf("echo '%s' > /home/coder/repos/%s/infra.json", escaped, repoName))
	if err != nil {
		return err
	}

	// Update cache
	infraCacheMu.Lock()
	infraCache[repoName] = cfg
	infraCacheMu.Unlock()
	return nil
}

// ─── Service CRUD (reads/writes disk, updates cache) ────────────────────────

// AddService adds a service to a project's infra.json.
func AddService(repoName, serviceName string, spec InfraService) error {
	cfg, _ := ReadProjectInfra(repoName)
	if cfg == nil {
		cfg = &InfraConfig{}
	}
	if cfg.Services == nil {
		cfg.Services = make(map[string]InfraService)
	}
	cfg.Services[serviceName] = spec
	if err := WriteProjectInfra(repoName, cfg); err != nil {
		return err
	}
	return CommitInfra(repoName, fmt.Sprintf("Add service %s", serviceName))
}

// UpdateService updates a service in a project's infra.json.
func UpdateService(repoName, serviceName string, spec InfraService) error {
	cfg, err := ReadProjectInfra(repoName)
	if err != nil {
		return err
	}
	if cfg.Services == nil {
		cfg.Services = make(map[string]InfraService)
	}
	cfg.Services[serviceName] = spec
	if err := WriteProjectInfra(repoName, cfg); err != nil {
		return err
	}
	return CommitInfra(repoName, fmt.Sprintf("Update service %s", serviceName))
}

// RemoveService removes a service from a project's infra.json.
func RemoveService(repoName, serviceName string) error {
	cfg, err := ReadProjectInfra(repoName)
	if err != nil {
		return err
	}
	delete(cfg.Services, serviceName)
	if err := WriteProjectInfra(repoName, cfg); err != nil {
		return err
	}
	return CommitInfra(repoName, fmt.Sprintf("Remove service %s", serviceName))
}

// CommitInfra commits infra.json changes in the project's git repo.
func CommitInfra(repoName, message string) error {
	dir := "/home/coder/repos/" + repoName
	_, err := CoderExec(fmt.Sprintf("cd %s && git add infra.json && git diff --cached --quiet || git commit -m '%s'", dir, strings.ReplaceAll(message, "'", "'\\''")))
	return err
}

// ─── Service queries (read from cache, batch Docker state) ──────────────────

// containerStates returns a map of container name → state ("running", "exited", etc.)
// from a single docker ps call.
func containerStates() map[string]string {
	containers, err := ListContainers()
	if err != nil {
		return nil
	}
	states := make(map[string]string, len(containers))
	for _, ct := range containers {
		name := strings.TrimPrefix(ct.Name, "/")
		states[name] = ct.State
	}
	return states
}

// buildDomainLookup returns a map of container name → domain host.
func buildDomainLookup() map[string]string {
	domains, _ := models.Domains.All()
	m := make(map[string]string, len(domains))
	for _, d := range domains {
		if d.ContainerName != "" {
			m[d.ContainerName] = d.Host
		}
	}
	return m
}

// specToLocalService converts an infra.json service spec into a LocalService.
func specToLocalService(repoName, repoID, name string, spec InfraService, domainByContainer, states map[string]string) LocalService {
	containerName := ContainerNameFor(repoName, name)
	svc := LocalService{
		RepoName:      repoName,
		RepoID:        repoID,
		Name:          name,
		Spec:          spec,
		ContainerName: containerName,
		Status:        "not_deployed",
		Image:         ImageNameFor(repoName, name),
		Domain:        domainByContainer[containerName],
	}

	if len(spec.Ports) > 0 {
		svc.ContainerPort = spec.Ports[0].Container
		for _, p := range spec.Ports {
			if p.Host > 0 {
				svc.ExposedPorts = append(svc.ExposedPorts, p)
			}
		}
	}

	// Derive status: check Docker container first, then binary process
	if state, ok := states[containerName]; ok {
		svc.Mode = "docker"
		if state == "running" {
			svc.Status = "running"
		} else {
			svc.Status = "stopped"
		}
	} else if IsBinaryRunning(repoName, name) {
		svc.Status = "running"
		svc.Mode = "binary"
	}

	if spec.Image != "" {
		svc.Image = spec.Image
	}

	return svc
}

// AllLocalServices returns all services from all projects' cached infra configs
// combined with live Docker state.
func AllLocalServices() []LocalService {
	repos, _ := models.Repositories.Search("WHERE Status != 'missing' ORDER BY Name")
	domainByContainer := buildDomainLookup()
	states := containerStates()
	configs := allCachedInfra()

	var services []LocalService
	for _, repo := range repos {
		cfg := configs[repo.Name]
		if cfg == nil {
			continue
		}
		for name, spec := range cfg.Services {
			services = append(services, specToLocalService(repo.Name, repo.ID, name, spec, domainByContainer, states))
		}
	}

	sort.Slice(services, func(i, j int) bool {
		return services[i].RepoName+services[i].Name < services[j].RepoName+services[j].Name
	})

	return services
}

// ProjectServices returns services for a specific project from cache.
func ProjectServices(repoName, repoID string) []LocalService {
	cfg := cachedInfra(repoName)
	if cfg == nil {
		return nil
	}

	domainByContainer := buildDomainLookup()
	states := containerStates()

	var services []LocalService
	for name, spec := range cfg.Services {
		services = append(services, specToLocalService(repoName, repoID, name, spec, domainByContainer, states))
	}
	return services
}

// GetService returns a single service by repo name and service name from cache.
func GetService(repoName, serviceName string) (*LocalService, error) {
	cfg := cachedInfra(repoName)
	if cfg == nil {
		// Try loading from disk as fallback
		var err error
		cfg, err = ReadProjectInfra(repoName)
		if err != nil {
			return nil, err
		}
	}

	spec, ok := cfg.Services[serviceName]
	if !ok {
		return nil, fmt.Errorf("service %s not found in %s/infra.json", serviceName, repoName)
	}

	repo, _ := models.Repositories.First("WHERE Name = ?", repoName)
	repoID := ""
	if repo != nil {
		repoID = repo.ID
	}

	domainByContainer := buildDomainLookup()
	states := containerStates()

	svc := specToLocalService(repoName, repoID, serviceName, spec, domainByContainer, states)
	return &svc, nil
}

// ─── Running containers (dashboard display) ─────────────────────────────────

// RunningContainer represents a Docker container for dashboard display.
type RunningContainer struct {
	Name     string // container name
	Image    string // Docker image
	Status   string // human-readable uptime from docker ps
	Ports    string // raw port mapping string
	Domain   string // domain if mapped
	RepoName string // project name, empty for standalone infrastructure
	SvcName  string // service name from infra.json, empty for standalone
}

// ShortPorts formats the docker ps Ports field into a compact display.
// Deduplicates IPv4/IPv6 bindings (e.g. 0.0.0.0:5001->5000 and :::5001->5000).
func (c RunningContainer) ShortPorts() string {
	if c.Ports == "" {
		return ""
	}
	seen := map[string]bool{}
	var parts []string
	for _, mapping := range strings.Split(c.Ports, ", ") {
		mapping = strings.TrimSpace(mapping)
		mapping = strings.TrimSuffix(mapping, "/tcp")
		mapping = strings.TrimSuffix(mapping, "/udp")
		if idx := strings.Index(mapping, "->"); idx >= 0 {
			host := mapping[:idx]
			container := mapping[idx+2:]
			if colonIdx := strings.LastIndex(host, ":"); colonIdx >= 0 {
				host = host[colonIdx:]
			}
			entry := host + "\u2192:" + container
			if !seen[entry] {
				seen[entry] = true
				parts = append(parts, entry)
			}
		}
	}
	if len(parts) == 0 {
		return ""
	}
	return strings.Join(parts, " ")
}

// AllRunningContainers returns all running Docker containers enriched with
// project and domain information for dashboard display.
func AllRunningContainers() []RunningContainer {
	containers, err := ListContainers()
	if err != nil {
		return nil
	}

	// Build mapping from container name → (repoName, serviceName, hasSource)
	// using cached infra configs — no CoderExec calls.
	type mapping struct {
		RepoName  string
		SvcName   string
		HasSource bool
	}
	configs := allCachedInfra()
	repos, _ := models.Repositories.Search("WHERE Status != 'missing' ORDER BY Name")
	containerRepo := make(map[string]mapping)
	for _, repo := range repos {
		cfg := configs[repo.Name]
		if cfg == nil {
			continue
		}
		for svcName, spec := range cfg.Services {
			m := mapping{
				RepoName:  repo.Name,
				SvcName:   svcName,
				HasSource: spec.Source != "",
			}
			// Match both direct service key (from congo launch) and {repo}-{svc} (from local deploy)
			containerRepo[svcName] = m
			containerRepo[ContainerNameFor(repo.Name, svcName)] = m
		}
	}

	domainByContainer := buildDomainLookup()

	var result []RunningContainer
	for _, ct := range containers {
		if ct.State != "running" {
			continue
		}
		name := strings.TrimPrefix(ct.Name, "/")

		rc := RunningContainer{
			Name:   name,
			Image:  ct.Image,
			Status: ct.Status,
			Ports:  ct.Ports,
			Domain: domainByContainer[name],
		}

		// Link to repo only if service is built from source (not image-only infra like caddy)
		if info, ok := containerRepo[name]; ok && info.HasSource {
			rc.RepoName = info.RepoName
			rc.SvcName = info.SvcName
		}

		result = append(result, rc)
	}

	sort.Slice(result, func(i, j int) bool {
		return result[i].Name < result[j].Name
	})

	return result
}

// InfraSummary returns a brief human-readable summary of the infra config.
func InfraSummary(cfg *InfraConfig) string {
	platforms := len(cfg.Platforms)
	servers := len(cfg.Servers)
	services := len(cfg.Services)
	var instanceCount int
	for _, insts := range cfg.Instances {
		instanceCount += len(insts)
	}

	summary := fmt.Sprintf("%d platform(s), %d server type(s), %d service(s)", platforms, servers, services)
	if instanceCount > 0 {
		summary += fmt.Sprintf(", %d instance(s)", instanceCount)
	}
	return summary
}