| 1 | // Command equipo-hosted-controller runs the hosted runner controller: the |
| 2 | // signed HTTPS API Equipo instances and operators call, its metrics |
| 3 | // listener, and the reaper loop. It is the one place the AWS adapter is |
| 4 | // wired in. |
| 5 | // |
| 6 | // equipo-hosted-controller -config /etc/equipo-hosted/controller.json |
| 7 | // |
| 8 | // Launches stay off unless EQUIPO_HOSTED_ENABLED=1; stops, reads and the |
| 9 | // reaper run either way. |
| 10 | package main |
| 11 | |
| 12 | import ( |
| 13 | "context" |
| 14 | "crypto/tls" |
| 15 | "errors" |
| 16 | "flag" |
| 17 | "fmt" |
| 18 | "log" |
| 19 | "log/slog" |
| 20 | "net" |
| 21 | "net/http" |
| 22 | "os" |
| 23 | "os/signal" |
| 24 | "sync" |
| 25 | "syscall" |
| 26 | "time" |
| 27 | |
| 28 | "amadan.net/oficina/equipo/internal/hostedctl" |
| 29 | "amadan.net/oficina/equipo/internal/isolatedjob" |
| 30 | "amadan.net/oficina/equipo/internal/isolatedjob/awsjob" |
| 31 | "github.com/aws/aws-sdk-go-v2/aws" |
| 32 | awsconfig "github.com/aws/aws-sdk-go-v2/config" |
| 33 | "github.com/aws/aws-sdk-go-v2/service/ec2" |
| 34 | "github.com/aws/aws-sdk-go-v2/service/lambdacore" |
| 35 | "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms" |
| 36 | "github.com/aws/aws-sdk-go-v2/service/sns" |
| 37 | "github.com/aws/aws-sdk-go-v2/service/sts" |
| 38 | ) |
| 39 | |
| 40 | // shutdownTimeout bounds how long the servers get to finish requests in |
| 41 | // flight after a signal. |
| 42 | const shutdownTimeout = 30 * time.Second |
| 43 | |
| 44 | func main() { |
| 45 | path := flag.String("config", "", "path of the controller's JSON config file") |
| 46 | flag.Parse() |
| 47 | if err := run(*path); err != nil { |
| 48 | log.Printf("equipo-hosted-controller: %v", err) |
| 49 | os.Exit(1) |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | func run(path string) error { |
| 54 | cfg, err := loadConfig(path, os.Getenv) |
| 55 | if err != nil { |
| 56 | return err |
| 57 | } |
| 58 | ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| 59 | defer stop() |
| 60 | |
| 61 | // Bad TLS files or a busy address fail here, before the store is |
| 62 | // opened or any startup alert is sent. |
| 63 | cert, err := tls.LoadX509KeyPair(cfg.tlsCert, cfg.tlsKey) |
| 64 | if err != nil { |
| 65 | return fmt.Errorf("TLS key pair: %w", err) |
| 66 | } |
| 67 | apiLn, err := net.Listen("tcp", cfg.listen) |
| 68 | if err != nil { |
| 69 | return err |
| 70 | } |
| 71 | defer apiLn.Close() |
| 72 | metricsLn, err := net.Listen("tcp", cfg.metricsListen) |
| 73 | if err != nil { |
| 74 | return err |
| 75 | } |
| 76 | defer metricsLn.Close() |
| 77 | |
| 78 | clock := isolatedjob.SystemClock() |
| 79 | store, err := hostedctl.Open(ctx, cfg.database, clock) |
| 80 | if err != nil { |
| 81 | return err |
| 82 | } |
| 83 | defer func() { |
| 84 | if err := store.Close(); err != nil { |
| 85 | log.Printf("equipo-hosted-controller: close store: %v", err) |
| 86 | } |
| 87 | }() |
| 88 | |
| 89 | // The default credential chain; the region is the config's, which the |
| 90 | // connector ARN is checked against. |
| 91 | awsCfg, err := awsconfig.LoadDefaultConfig(ctx, awsconfig.WithRegion(cfg.aws.Region)) |
| 92 | if err != nil { |
| 93 | return fmt.Errorf("AWS config: %w", err) |
| 94 | } |
| 95 | runner, err := awsjob.New(cfg.aws, awsjob.NewAPI(lambdamicrovms.NewFromConfig(awsCfg), ec2.NewFromConfig(awsCfg), |
| 96 | lambdacore.NewFromConfig(awsCfg))) |
| 97 | if err != nil { |
| 98 | return err |
| 99 | } |
| 100 | if cfg.ctl.ProviderNamespace, err = providerNamespace(ctx, sts.NewFromConfig(awsCfg), cfg.aws.Region); err != nil { |
| 101 | return err |
| 102 | } |
| 103 | metrics := hostedctl.NewMetrics() |
| 104 | alerter := metrics.CountAlerts(snsAlerter{pub: awsjob.SNSPublisher{TopicARN: cfg.topicARN, Client: sns.NewFromConfig(awsCfg)}}) |
| 105 | var jobs isolatedjob.Runner = runner |
| 106 | if runnerHook != nil { |
| 107 | jobs = runnerHook(jobs) |
| 108 | } |
| 109 | // Operator records (orphans, audits, restart settling) go to stderr |
| 110 | // at info, beside the log package's lines. |
| 111 | opLog := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelInfo})) |
| 112 | c, err := hostedctl.New(cfg.ctl, hostedctl.Deps{Store: store, Runner: jobs, Auditor: runner, Alerter: alerter, Log: opLog}) |
| 113 | if err != nil { |
| 114 | return err |
| 115 | } |
| 116 | api, err := c.Handler(hostedctl.HandlerConfig{Keys: cfg.keys, Signing: cfg.signing, Wall: clock.Wall, Metrics: metrics}) |
| 117 | if err != nil { |
| 118 | return err |
| 119 | } |
| 120 | log.Printf("equipo-hosted-controller: API on %s, metrics on %s, launches enabled: %v", cfg.listen, cfg.metricsListen, cfg.ctl.Enabled) |
| 121 | return serve(ctx, c, newAPIServer(api, cert), apiLn, newMetricsServer(metrics.Handler(c)), metricsLn, shutdownTimeout) |
| 122 | } |
| 123 | |
| 124 | // runnerHook, when set, wraps the runner the controller calls. Only a build |
| 125 | // with the hostedlive tag sets it (crashpoint.go, the Task 17 crash point); |
| 126 | // in every other build it is nil and the controller calls the AWS runner |
| 127 | // directly. |
| 128 | var runnerHook func(isolatedjob.Runner) isolatedjob.Runner |
| 129 | |
| 130 | // callerIdentity is the STS call providerNamespace makes. |
| 131 | // *sts.Client satisfies it. |
| 132 | type callerIdentity interface { |
| 133 | GetCallerIdentity(context.Context, *sts.GetCallerIdentityInput, ...func(*sts.Options)) (*sts.GetCallerIdentityOutput, error) |
| 134 | } |
| 135 | |
| 136 | // providerNamespace is "aws:ACCOUNT:REGION" for the account the credentials |
| 137 | // belong to: MicroVM IDs are only found there, so the controller binds its |
| 138 | // database to it (ruling R28). The call is bounded like any provider call. |
| 139 | func providerNamespace(ctx context.Context, c callerIdentity, region string) (string, error) { |
| 140 | ctx, cancel := context.WithTimeout(ctx, hostedctl.ProviderCallTimeout) |
| 141 | defer cancel() |
| 142 | out, err := c.GetCallerIdentity(ctx, &sts.GetCallerIdentityInput{}) |
| 143 | if err != nil { |
| 144 | return "", fmt.Errorf("AWS caller identity: %w", err) |
| 145 | } |
| 146 | if aws.ToString(out.Account) == "" || region == "" { |
| 147 | return "", errors.New("AWS caller identity names no account, or no region is set") |
| 148 | } |
| 149 | return "aws:" + aws.ToString(out.Account) + ":" + region, nil |
| 150 | } |
| 151 | |
| 152 | // newAPIServer is the HTTPS API server. DisableGeneralOptionsHandler hands |
| 153 | // "OPTIONS *" to the API handler, which verifies it like any request, |
| 154 | // instead of Go answering it unsigned. |
| 155 | func newAPIServer(api http.Handler, cert tls.Certificate) *http.Server { |
| 156 | return &http.Server{ |
| 157 | Handler: api, |
| 158 | DisableGeneralOptionsHandler: true, |
| 159 | TLSConfig: &tls.Config{MinVersion: tls.VersionTLS12, Certificates: []tls.Certificate{cert}}, |
| 160 | ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second, |
| 161 | // A launch or stop waits on the provider (up to |
| 162 | // hostedctl.ProviderLaunchTimeout), so writes get longer. |
| 163 | WriteTimeout: 2 * time.Minute, IdleTimeout: 2 * time.Minute, MaxHeaderBytes: 64 << 10, |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | func newMetricsServer(h http.Handler) *http.Server { |
| 168 | return &http.Server{Handler: h, DisableGeneralOptionsHandler: true, |
| 169 | ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 30 * time.Second} |
| 170 | } |
| 171 | |
| 172 | // serve runs the reaper loop and both servers until ctx ends (a signal) or |
| 173 | // a server fails. Then, in order: the servers stop accepting and get drain |
| 174 | // to finish their requests; the requests still running and the reaper, |
| 175 | // which has a lifetime of its own, are both cancelled; and serve waits for |
| 176 | // every handler and the reaper to return. The caller closes the store after |
| 177 | // serve returns, so no request or reaper pass ever runs on a closed store. |
| 178 | // Every provider call is bounded (hostedctl.ProviderCallTimeout), so a |
| 179 | // handler or pass that ignores its cancelled context still returns. |
| 180 | func serve(ctx context.Context, c *hostedctl.Controller, apiSrv *http.Server, apiLn net.Listener, |
| 181 | metricsSrv *http.Server, metricsLn net.Listener, drain time.Duration) error { |
| 182 | reqCtx, cancelRequests := context.WithCancel(context.Background()) |
| 183 | defer cancelRequests() |
| 184 | var active handlers |
| 185 | for _, srv := range []*http.Server{apiSrv, metricsSrv} { |
| 186 | srv.BaseContext = func(net.Listener) context.Context { return reqCtx } |
| 187 | srv.Handler = active.wrap(srv.Handler) |
| 188 | } |
| 189 | |
| 190 | reapCtx, stopReaper := context.WithCancel(context.Background()) |
| 191 | defer stopReaper() |
| 192 | reaperDone := make(chan error, 1) |
| 193 | go func() { reaperDone <- c.Loop(reapCtx, hostedctl.ReapInterval) }() |
| 194 | |
| 195 | failed := make(chan error, 2) |
| 196 | go func() { failed <- fmt.Errorf("API server: %w", apiSrv.ServeTLS(apiLn, "", "")) }() |
| 197 | go func() { failed <- fmt.Errorf("metrics server: %w", metricsSrv.Serve(metricsLn)) }() |
| 198 | |
| 199 | var runErr error |
| 200 | select { |
| 201 | case <-ctx.Done(): |
| 202 | case runErr = <-failed: |
| 203 | } |
| 204 | drainCtx, cancel := context.WithTimeout(context.Background(), drain) |
| 205 | if err := errors.Join(apiSrv.Shutdown(drainCtx), metricsSrv.Shutdown(drainCtx)); err != nil { |
| 206 | log.Printf("equipo-hosted-controller: requests still running after %v; cancelling them: %v", drain, err) |
| 207 | } |
| 208 | cancel() |
| 209 | // Both at once, then join both (ruling R27): a request may be waiting |
| 210 | // for an attempt lock a reaper pass holds across a provider call, and |
| 211 | // only the reaper's cancellation ends that call. |
| 212 | cancelRequests() |
| 213 | stopReaper() |
| 214 | active.closeAndWait() |
| 215 | if err := <-reaperDone; err != nil { |
| 216 | log.Printf("equipo-hosted-controller: last reaper pass: %v", err) |
| 217 | } |
| 218 | return runErr |
| 219 | } |
| 220 | |
| 221 | // handlers counts running request handlers. After closeAndWait begins, a |
| 222 | // request that still reaches a handler (a race with Shutdown) gets an |
| 223 | // unsigned 503 and never touches the controller. |
| 224 | type handlers struct { |
| 225 | mu sync.Mutex |
| 226 | n int |
| 227 | closed bool |
| 228 | idle chan struct{} // closed when closed and n is 0 |
| 229 | } |
| 230 | |
| 231 | func (a *handlers) wrap(next http.Handler) http.Handler { |
| 232 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 233 | a.mu.Lock() |
| 234 | if a.closed { |
| 235 | a.mu.Unlock() |
| 236 | w.WriteHeader(http.StatusServiceUnavailable) |
| 237 | return |
| 238 | } |
| 239 | a.n++ |
| 240 | a.mu.Unlock() |
| 241 | defer a.leave() |
| 242 | next.ServeHTTP(w, r) |
| 243 | }) |
| 244 | } |
| 245 | |
| 246 | func (a *handlers) leave() { |
| 247 | a.mu.Lock() |
| 248 | defer a.mu.Unlock() |
| 249 | a.n-- |
| 250 | if a.closed && a.n == 0 { |
| 251 | close(a.idle) |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | // closeAndWait refuses new handlers and waits for the running ones. |
| 256 | func (a *handlers) closeAndWait() { |
| 257 | a.mu.Lock() |
| 258 | a.closed, a.idle = true, make(chan struct{}) |
| 259 | if a.n == 0 { |
| 260 | close(a.idle) |
| 261 | } |
| 262 | idle := a.idle |
| 263 | a.mu.Unlock() |
| 264 | <-idle |
| 265 | } |
| 266 | |