// Command equipo-hosted-controller runs the hosted runner controller: the // signed HTTPS API Equipo instances and operators call, its metrics // listener, and the reaper loop. It is the one place the AWS adapter is // wired in. // // equipo-hosted-controller -config /etc/equipo-hosted/controller.json // // Launches stay off unless EQUIPO_HOSTED_ENABLED=1; stops, reads and the // reaper run either way. package main import ( "context" "crypto/tls" "errors" "flag" "fmt" "log" "log/slog" "net" "net/http" "os" "os/signal" "sync" "syscall" "time" "amadan.net/oficina/equipo/internal/hostedctl" "amadan.net/oficina/equipo/internal/isolatedjob" "amadan.net/oficina/equipo/internal/isolatedjob/awsjob" "github.com/aws/aws-sdk-go-v2/aws" awsconfig "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/ec2" "github.com/aws/aws-sdk-go-v2/service/lambdacore" "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms" "github.com/aws/aws-sdk-go-v2/service/sns" "github.com/aws/aws-sdk-go-v2/service/sts" ) // shutdownTimeout bounds how long the servers get to finish requests in // flight after a signal. const shutdownTimeout = 30 * time.Second func main() { path := flag.String("config", "", "path of the controller's JSON config file") flag.Parse() if err := run(*path); err != nil { log.Printf("equipo-hosted-controller: %v", err) os.Exit(1) } } func run(path string) error { cfg, err := loadConfig(path, os.Getenv) if err != nil { return err } ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() // Bad TLS files or a busy address fail here, before the store is // opened or any startup alert is sent. cert, err := tls.LoadX509KeyPair(cfg.tlsCert, cfg.tlsKey) if err != nil { return fmt.Errorf("TLS key pair: %w", err) } apiLn, err := net.Listen("tcp", cfg.listen) if err != nil { return err } defer apiLn.Close() metricsLn, err := net.Listen("tcp", cfg.metricsListen) if err != nil { return err } defer metricsLn.Close() clock := isolatedjob.SystemClock() store, err := hostedctl.Open(ctx, cfg.database, clock) if err != nil { return err } defer func() { if err := store.Close(); err != nil { log.Printf("equipo-hosted-controller: close store: %v", err) } }() // The default credential chain; the region is the config's, which the // connector ARN is checked against. awsCfg, err := awsconfig.LoadDefaultConfig(ctx, awsconfig.WithRegion(cfg.aws.Region)) if err != nil { return fmt.Errorf("AWS config: %w", err) } runner, err := awsjob.New(cfg.aws, awsjob.NewAPI(lambdamicrovms.NewFromConfig(awsCfg), ec2.NewFromConfig(awsCfg), lambdacore.NewFromConfig(awsCfg))) if err != nil { return err } if cfg.ctl.ProviderNamespace, err = providerNamespace(ctx, sts.NewFromConfig(awsCfg), cfg.aws.Region); err != nil { return err } metrics := hostedctl.NewMetrics() alerter := metrics.CountAlerts(snsAlerter{pub: awsjob.SNSPublisher{TopicARN: cfg.topicARN, Client: sns.NewFromConfig(awsCfg)}}) var jobs isolatedjob.Runner = runner if runnerHook != nil { jobs = runnerHook(jobs) } // Operator records (orphans, audits, restart settling) go to stderr // at info, beside the log package's lines. opLog := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelInfo})) c, err := hostedctl.New(cfg.ctl, hostedctl.Deps{Store: store, Runner: jobs, Auditor: runner, Alerter: alerter, Log: opLog}) if err != nil { return err } api, err := c.Handler(hostedctl.HandlerConfig{Keys: cfg.keys, Signing: cfg.signing, Wall: clock.Wall, Metrics: metrics}) if err != nil { return err } log.Printf("equipo-hosted-controller: API on %s, metrics on %s, launches enabled: %v", cfg.listen, cfg.metricsListen, cfg.ctl.Enabled) return serve(ctx, c, newAPIServer(api, cert), apiLn, newMetricsServer(metrics.Handler(c)), metricsLn, shutdownTimeout) } // runnerHook, when set, wraps the runner the controller calls. Only a build // with the hostedlive tag sets it (crashpoint.go, the Task 17 crash point); // in every other build it is nil and the controller calls the AWS runner // directly. var runnerHook func(isolatedjob.Runner) isolatedjob.Runner // callerIdentity is the STS call providerNamespace makes. // *sts.Client satisfies it. type callerIdentity interface { GetCallerIdentity(context.Context, *sts.GetCallerIdentityInput, ...func(*sts.Options)) (*sts.GetCallerIdentityOutput, error) } // providerNamespace is "aws:ACCOUNT:REGION" for the account the credentials // belong to: MicroVM IDs are only found there, so the controller binds its // database to it (ruling R28). The call is bounded like any provider call. func providerNamespace(ctx context.Context, c callerIdentity, region string) (string, error) { ctx, cancel := context.WithTimeout(ctx, hostedctl.ProviderCallTimeout) defer cancel() out, err := c.GetCallerIdentity(ctx, &sts.GetCallerIdentityInput{}) if err != nil { return "", fmt.Errorf("AWS caller identity: %w", err) } if aws.ToString(out.Account) == "" || region == "" { return "", errors.New("AWS caller identity names no account, or no region is set") } return "aws:" + aws.ToString(out.Account) + ":" + region, nil } // newAPIServer is the HTTPS API server. DisableGeneralOptionsHandler hands // "OPTIONS *" to the API handler, which verifies it like any request, // instead of Go answering it unsigned. func newAPIServer(api http.Handler, cert tls.Certificate) *http.Server { return &http.Server{ Handler: api, DisableGeneralOptionsHandler: true, TLSConfig: &tls.Config{MinVersion: tls.VersionTLS12, Certificates: []tls.Certificate{cert}}, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second, // A launch or stop waits on the provider (up to // hostedctl.ProviderLaunchTimeout), so writes get longer. WriteTimeout: 2 * time.Minute, IdleTimeout: 2 * time.Minute, MaxHeaderBytes: 64 << 10, } } func newMetricsServer(h http.Handler) *http.Server { return &http.Server{Handler: h, DisableGeneralOptionsHandler: true, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 30 * time.Second} } // serve runs the reaper loop and both servers until ctx ends (a signal) or // a server fails. Then, in order: the servers stop accepting and get drain // to finish their requests; the requests still running and the reaper, // which has a lifetime of its own, are both cancelled; and serve waits for // every handler and the reaper to return. The caller closes the store after // serve returns, so no request or reaper pass ever runs on a closed store. // Every provider call is bounded (hostedctl.ProviderCallTimeout), so a // handler or pass that ignores its cancelled context still returns. func serve(ctx context.Context, c *hostedctl.Controller, apiSrv *http.Server, apiLn net.Listener, metricsSrv *http.Server, metricsLn net.Listener, drain time.Duration) error { reqCtx, cancelRequests := context.WithCancel(context.Background()) defer cancelRequests() var active handlers for _, srv := range []*http.Server{apiSrv, metricsSrv} { srv.BaseContext = func(net.Listener) context.Context { return reqCtx } srv.Handler = active.wrap(srv.Handler) } reapCtx, stopReaper := context.WithCancel(context.Background()) defer stopReaper() reaperDone := make(chan error, 1) go func() { reaperDone <- c.Loop(reapCtx, hostedctl.ReapInterval) }() failed := make(chan error, 2) go func() { failed <- fmt.Errorf("API server: %w", apiSrv.ServeTLS(apiLn, "", "")) }() go func() { failed <- fmt.Errorf("metrics server: %w", metricsSrv.Serve(metricsLn)) }() var runErr error select { case <-ctx.Done(): case runErr = <-failed: } drainCtx, cancel := context.WithTimeout(context.Background(), drain) if err := errors.Join(apiSrv.Shutdown(drainCtx), metricsSrv.Shutdown(drainCtx)); err != nil { log.Printf("equipo-hosted-controller: requests still running after %v; cancelling them: %v", drain, err) } cancel() // Both at once, then join both (ruling R27): a request may be waiting // for an attempt lock a reaper pass holds across a provider call, and // only the reaper's cancellation ends that call. cancelRequests() stopReaper() active.closeAndWait() if err := <-reaperDone; err != nil { log.Printf("equipo-hosted-controller: last reaper pass: %v", err) } return runErr } // handlers counts running request handlers. After closeAndWait begins, a // request that still reaches a handler (a race with Shutdown) gets an // unsigned 503 and never touches the controller. type handlers struct { mu sync.Mutex n int closed bool idle chan struct{} // closed when closed and n is 0 } func (a *handlers) wrap(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { a.mu.Lock() if a.closed { a.mu.Unlock() w.WriteHeader(http.StatusServiceUnavailable) return } a.n++ a.mu.Unlock() defer a.leave() next.ServeHTTP(w, r) }) } func (a *handlers) leave() { a.mu.Lock() defer a.mu.Unlock() a.n-- if a.closed && a.n == 0 { close(a.idle) } } // closeAndWait refuses new handlers and waits for the running ones. func (a *handlers) closeAndWait() { a.mu.Lock() a.closed, a.idle = true, make(chan struct{}) if a.n == 0 { close(a.idle) } idle := a.idle a.mu.Unlock() <-idle }