infra.go

245 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
package scaffold

import (
	"cmp"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
)

// InfraConfig defines the complete infrastructure for a project.
//
// Schema (infra.json):
//
//	{
//	  "platforms": { "<name>": { provider, token?, region? } }
//	  "servers":   { "<type>": { platform, size, setup?, volumes?, services } }
//	  "services":  { "<name>": { image|source, setup?, ports, volumes?, env?, env_files?, network?, healthcheck? } }
//	  "instances": { "<type>": [{ id, name, ip, region? }] }
//	}
//
// Volume references: Service volume sources and env values support $volume-name
// syntax. A server volume {"name": "data", "mount": "/mnt/data"} can be
// referenced as "$data/app" which expands to "/mnt/data/app" at deploy time.
type InfraConfig struct {
	Platforms map[string]PlatformConfig `json:"platforms"`
	Servers   map[string]ServerSpec     `json:"servers"`
	Services  map[string]ServiceSpec    `json:"services,omitempty"`
	Instances map[string][]Instance     `json:"instances,omitempty"`
}

type PlatformConfig struct {
	Provider string `json:"provider"`        // "digitalocean" or "metal"
	Token    string `json:"token,omitempty"` // API token (supports $ENV_VAR)
	Region   string `json:"region,omitempty"`

	RawToken string `json:"-"`
}

type ServerSpec struct {
	Platform string       `json:"platform,omitempty"` // key into Platforms map
	Size     string       `json:"size"`
	Setup    string       `json:"setup,omitempty"` // relative path to setup script
	Volumes  []VolumeSpec `json:"volumes,omitempty"`
	Services []string     `json:"services,omitempty"`
}

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

type ServiceSpec struct {
	Image       string            `json:"image,omitempty"`
	Source      string            `json:"source,omitempty"`
	Setup       string            `json:"setup,omitempty"` // relative path to setup script (runs on host before container)
	Command     []string          `json:"command,omitempty"`
	Ports       []PortSpec        `json:"ports,omitempty"`
	Volumes     []VolumeMount     `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"`
}

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

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

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

func (cfg *InfraConfig) AllInstances() []Instance {
	var all []Instance
	for _, instances := range cfg.Instances {
		all = append(all, instances...)
	}
	return all
}

func CountInstances(cfg *InfraConfig) int {
	return len(cfg.AllInstances())
}

// PlatformNameFor returns the platform key for a server type.
// Falls back to the first (or only) key if the server has no explicit platform.
func (cfg *InfraConfig) PlatformNameFor(serverType string) string {
	if spec, ok := cfg.Servers[serverType]; ok && spec.Platform != "" {
		return spec.Platform
	}
	// Default: if only one platform, use it
	for name := range cfg.Platforms {
		return name
	}
	return ""
}

// PlatformFor returns the PlatformConfig for a server type.
func (cfg *InfraConfig) PlatformFor(serverType string) PlatformConfig {
	return cfg.Platforms[cfg.PlatformNameFor(serverType)]
}

// LoadInfraConfig reads and validates infra.json from the given directory.
func LoadInfraConfig(projectDir string) (*InfraConfig, error) {
	path := filepath.Join(projectDir, "infra.json")
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("read infra.json: %w (see 'congo launch --help')", err)
	}

	var cfg InfraConfig
	if err := json.Unmarshal(data, &cfg); err != nil {
		return nil, fmt.Errorf("parse infra.json: %w", err)
	}

	if cfg.Instances == nil {
		cfg.Instances = make(map[string][]Instance)
	}
	if cfg.Services == nil {
		cfg.Services = make(map[string]ServiceSpec)
	}

	// Expand env vars for all platform tokens
	for name, pc := range cfg.Platforms {
		pc.RawToken = pc.Token
		pc.Token = ExpandEnv(pc.Token)
		cfg.Platforms[name] = pc
	}

	if err := validateInfra(&cfg); err != nil {
		return nil, err
	}

	return &cfg, nil
}

func ExpandEnv(s string) string {
	if strings.HasPrefix(s, "$") {
		val := os.ExpandEnv(s)
		if val == "" {
			log.Printf("   Warning: %s is empty or unset", s)
		}
		return val
	}
	return s
}

func (cfg *InfraConfig) Save(projectDir string) error {
	path := filepath.Join(projectDir, "infra.json")

	// Save and restore expanded tokens
	saved := make(map[string]string)
	for name, pc := range cfg.Platforms {
		saved[name] = pc.Token
		if pc.RawToken != "" {
			pc.Token = pc.RawToken
		}
		cfg.Platforms[name] = pc
	}
	defer func() {
		for name, tok := range saved {
			pc := cfg.Platforms[name]
			pc.Token = tok
			cfg.Platforms[name] = pc
		}
	}()

	data, err := json.MarshalIndent(cfg, "", "  ")
	if err != nil {
		return fmt.Errorf("marshal infra.json: %w", err)
	}

	return os.WriteFile(path, data, 0600)
}

func validateInfra(cfg *InfraConfig) error {
	var errs []string

	if len(cfg.Platforms) == 0 {
		errs = append(errs, "at least one platform is required in \"platforms\"")
	}
	for name, pc := range cfg.Platforms {
		if pc.Provider == "" {
			errs = append(errs, fmt.Sprintf("platforms.%s.provider is required", name))
		}
		if pc.Token == "" && pc.Provider != "metal" {
			errs = append(errs, fmt.Sprintf("platforms.%s.token is required (use $ENV_VAR for env reference)", name))
		}
	}

	for name, spec := range cfg.Servers {
		if spec.Size == "" {
			errs = append(errs, fmt.Sprintf("servers.%s.size is required", name))
		}
		platName := cmp.Or(spec.Platform, cfg.PlatformNameFor(name))
		if _, ok := cfg.Platforms[platName]; !ok && platName != "" {
			errs = append(errs, fmt.Sprintf("servers.%s references unknown platform %q", name, platName))
		}
		if spec.Setup != "" && !SafeRelPath(spec.Setup) {
			errs = append(errs, fmt.Sprintf("servers.%s.setup: invalid path %q", name, spec.Setup))
		}
		for _, svcName := range spec.Services {
			if _, ok := cfg.Services[svcName]; !ok {
				errs = append(errs, fmt.Sprintf("servers.%s references unknown service %q", name, svcName))
			}
		}
	}

	for name, spec := range cfg.Services {
		if spec.Image == "" && spec.Source == "" {
			errs = append(errs, fmt.Sprintf("services.%s must have either image or source", name))
		}
		if spec.Setup != "" && !SafeRelPath(spec.Setup) {
			errs = append(errs, fmt.Sprintf("services.%s.setup: invalid path %q", name, spec.Setup))
		}
		for i, p := range spec.Ports {
			if p.Host < 1 || p.Host > 65535 {
				errs = append(errs, fmt.Sprintf("services.%s.ports[%d].host out of range", name, i))
			}
			if p.Container < 1 || p.Container > 65535 {
				errs = append(errs, fmt.Sprintf("services.%s.ports[%d].container out of range", name, i))
			}
		}
	}

	if len(errs) > 0 {
		return fmt.Errorf("infra.json validation:\n  - %s", strings.Join(errs, "\n  - "))
	}
	return nil
}