diff --git a/CHANGELOG.md b/CHANGELOG.md index 28a6128..ef733ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ ## vX.X.X (YYYY-MM-DD) +### Fixed +- The default of `deployment_max_extensions` is now 3, as documented in `config.example.yaml`: the code defaulted to 4 +- Without Redis, expired deployments are now terminated: the expiry scheduler had no way to run a termination without the job queue, so it only marked them as errors ("no job queue configured for termination") and left their containers running +- A panic in a request handler now returns a 500 response and is logged with its stack trace: the recovery middleware was commented out, so the connection was dropped without a response +- `/admin/deploy-all` now lists the category and name of each challenge it deploys: its `challenges` entries were empty (`{"category": "", "challenge_name": ""}`). `/admin/deploy-all` and `/admin/terminate-all` return `"challenges": []` instead of `null` when there is nothing to do +- `/extend` refuses a deployment that is not running (starting, stopping or failed) with a 400 "deployment is not running", counted as `not_running` in the extension rejection metric: it extended any deployment and always answered with status `running` +- The `tcp` playbook no longer requires `traefik_network`: it declared that network in the compose definition although TCP services run on the bridge network and never join it, so TCP challenges failed to deploy when it was not set +- The Docker image's default command now starts the server (`serve --port 8080 --config data/config.yaml`): it passed the port as an argument, which `serve` rejects (`unknown command "8080"`), so the image only worked with an explicit command +- `max_concurrent_ansible` is now honored: without Redis, at most that many Ansible runs (default 5) run at once for team deploys, team terminations and expiries, the others waiting for a slot. Admin actions are not limited. The setting was read but never used, so these runs were unbounded +- The published port bindings store no longer leaks a SQLite connection, and its file descriptor, on every deploy and terminate: it opened a new connection pool for each call and never closed it. It now keeps one per database file + ## v0.7.2 (2026-10-01) ### Changed diff --git a/config.example.yaml b/config.example.yaml index dbfa0b0..e54e80f 100755 --- a/config.example.yaml +++ b/config.example.yaml @@ -14,7 +14,7 @@ instancer: randomized_port_min: 20000 # Lower bound for randomized host ports, included (default: 20000) randomized_port_max: 60999 # Upper bound for randomized host ports, included (default: 60999) num_workers: 10 # Number of Ansible workers for processing jobs (default: 10) - max_concurrent_ansible: 5 # Fallback: max concurrent Ansible when Redis not configured (default: 5) + max_concurrent_ansible: 5 # Without Redis: max concurrent Ansible runs for team requests and expiries, read at startup; admin actions are not limited (default: 5) metrics: username: "prometheus" # Basic-auth username for the /metrics endpoint (default: "prometheus") password: "" # Basic-auth password; leave empty to disable authentication diff --git a/data/playbooks/tcp.yaml b/data/playbooks/tcp.yaml index b64efda..1b6494a 100755 --- a/data/playbooks/tcp.yaml +++ b/data/playbooks/tcp.yaml @@ -27,7 +27,6 @@ compose_definition: services: tcp: "{{ _tcp_service }}" - networks: "{{ {traefik_network: {'external': true}} }}" tags: - create - delete diff --git a/galvanize-instancer/Dockerfile b/galvanize-instancer/Dockerfile index cc4b2d3..ffd3511 100755 --- a/galvanize-instancer/Dockerfile +++ b/galvanize-instancer/Dockerfile @@ -37,4 +37,5 @@ EXPOSE 8080 # Use tini as entrypoint to properly reap zombie SSH processes from Ansible ENTRYPOINT ["/usr/bin/tini", "--"] -CMD ["./galvanize", "serve", "8080", "-c", "config.yaml"] \ No newline at end of file +# The config is expected at data/config.yaml, as mounted by docker-compose.yml +CMD ["./galvanize", "serve", "--port", "8080", "--config", "data/config.yaml"] \ No newline at end of file diff --git a/galvanize-instancer/api/openapi.yaml.in b/galvanize-instancer/api/openapi.yaml.in index 28e9e06..de93634 100755 --- a/galvanize-instancer/api/openapi.yaml.in +++ b/galvanize-instancer/api/openapi.yaml.in @@ -120,7 +120,7 @@ paths: schema: $ref: '#/components/schemas/StatusResponse' '400': - description: Cannot extend deployment (too early, max extensions reached, etc.) + description: Cannot extend deployment (not running, too early, max extensions reached, etc.) '401': description: Unauthorized '404': diff --git a/galvanize-instancer/cmd/root.go b/galvanize-instancer/cmd/root.go index 216789e..cdfe11c 100755 --- a/galvanize-instancer/cmd/root.go +++ b/galvanize-instancer/cmd/root.go @@ -52,10 +52,7 @@ func initConfig() { viper.SetConfigFile(cfgFile) viper.SetConfigType("yaml") - viper.SetDefault("instancer.deployment_ttl", "1h") - viper.SetDefault("instancer.deployment_ttl_extension", "30m") - viper.SetDefault("instancer.deployment_max_extensions", 4) - viper.SetDefault("instancer.deployment_extension_window", "30m") + setConfigDefaults() if err := viper.ReadInConfig(); err != nil { zap.S().Fatalf("Error reading config file: %v", err) @@ -71,6 +68,14 @@ func initConfig() { }) } +// setConfigDefaults sets the defaults of the settings a config may omit. +func setConfigDefaults() { + viper.SetDefault("instancer.deployment_ttl", "1h") + viper.SetDefault("instancer.deployment_ttl_extension", "30m") + viper.SetDefault("instancer.deployment_max_extensions", 3) + viper.SetDefault("instancer.deployment_extension_window", "30m") +} + func handleConfigChange(filename string) { reloadMu.Lock() defer reloadMu.Unlock() diff --git a/galvanize-instancer/cmd/root_test.go b/galvanize-instancer/cmd/root_test.go new file mode 100644 index 0000000..8f44cbc --- /dev/null +++ b/galvanize-instancer/cmd/root_test.go @@ -0,0 +1,33 @@ +package cmd + +import ( + "os" + "path/filepath" + "testing" + "time" + + "github.com/28Pollux28/galvanize/pkg/config" + "github.com/spf13/viper" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// A config that omits the deployment settings gets the defaults documented +// in config.example.yaml +func TestSetConfigDefaults(t *testing.T) { + t.Cleanup(viper.Reset) + viper.Reset() + path := filepath.Join(t.TempDir(), "config.yaml") + require.NoError(t, os.WriteFile(path, []byte("instancer:\n instancer_host: example.org\n"), 0o600)) + + setConfigDefaults() + viper.SetConfigFile(path) + require.NoError(t, viper.ReadInConfig()) + require.NoError(t, config.Load()) + + ic := config.Get().Instancer + assert.Equal(t, 3, ic.DeploymentMaxExtensions) + assert.Equal(t, time.Hour, ic.DeploymentTTL) + assert.Equal(t, 30*time.Minute, ic.DeploymentTTLExtension) + assert.Equal(t, 30*time.Minute, ic.DeploymentExtensionWindow) +} diff --git a/galvanize-instancer/cmd/serve.go b/galvanize-instancer/cmd/serve.go index 5ea7d2f..16b0a71 100755 --- a/galvanize-instancer/cmd/serve.go +++ b/galvanize-instancer/cmd/serve.go @@ -54,23 +54,7 @@ var serveCmd = &cobra.Command{ e.HidePort = true // 2. Middleware - skipper := func(c echo.Context) bool { - // Skip health check endpoint - return c.Request().URL.Path == "/health" - } - e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{ - LogStatus: true, - LogMethod: true, - LogRemoteIP: true, - LogURI: true, - Skipper: skipper, - LogValuesFunc: func(c echo.Context, v middleware.RequestLoggerValues) error { - zap.S().Infof("| %v | %v | %v | %v", v.RemoteIP, v.Method, v.URI, v.Status) - return nil - }, - })) - //e.Use(middleware.Recover()) - e.Use(middleware.CORS()) + useMiddleware(e) // 3. Prometheus e.Use(echoprometheus.NewMiddleware("instancer")) // register middleware to gather metrics from requests @@ -192,12 +176,11 @@ var serveCmd = &cobra.Command{ Logger: zap.S().Named("WorkerPool"), }) zap.S().Infof("Redis job queue enabled with %d workers", numWorkers) - } else { - zap.S().Info("Redis not configured, using direct goroutines for deployments") } // Initialize scheduler with job queue (can be nil if Redis not configured) expirySched := scheduler.NewExpiryScheduler(db, jobQueue, zap.S().Named("ExpiryScheduler")) + teamDeployer := configureQueueless(cfg, jobQueue, expirySched, challIdx, confProv) // 7. Server Init via DI srv := server.NewServerWithOpts(server.ServerOpts{ @@ -205,6 +188,7 @@ var serveCmd = &cobra.Command{ ChallengeIndexer: challIdx, ConfigProvider: confProv, Deployer: &ansible.AnsibleDeployer{}, + TeamDeployer: teamDeployer, ExpiryScheduler: expirySched, JobQueue: jobQueue, }) @@ -280,6 +264,52 @@ func metricsHandler(username, password string, h http.Handler) http.Handler { }) } +// configureQueueless sets up running without a job queue (Redis not +// configured): team requests and expiries then share a LimitedDeployer with +// max_concurrent_ansible slots, which it returns, and the scheduler +// terminates expired deployments itself with it. Admin actions keep the +// unlimited deployer. With a job queue, it does nothing and returns nil. +func configureQueueless(cfg *config.Config, jobQueue *worker.Queue, expirySched *scheduler.ExpiryScheduler, challIdx challenge.ChallengeIndexer, confProv config.Provider) ansible.Deployer { + if jobQueue != nil { + return nil + } + limit := cfg.Instancer.MaxConcurrentAnsibleLimit() + teamDeployer := ansible.NewLimitedDeployer(&ansible.AnsibleDeployer{}, limit) + expirySched.WithDirectTermination(challIdx, confProv, teamDeployer) + zap.S().Infof("Redis not configured, using direct goroutines for deployments (at most %d Ansible runs at a time for team requests and expiries)", limit) + return teamDeployer +} + +// useMiddleware installs the request logger, panic recovery and CORS. +// +// Recover turns a panic in a handler into a 500 response, logged with its +// stack trace and by the request logger, instead of net/http's default of +// dropping the connection without a response. +func useMiddleware(e *echo.Echo) { + skipper := func(c echo.Context) bool { + // Skip health check endpoint + return c.Request().URL.Path == "/health" + } + e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{ + LogStatus: true, + LogMethod: true, + LogRemoteIP: true, + LogURI: true, + Skipper: skipper, + LogValuesFunc: func(c echo.Context, v middleware.RequestLoggerValues) error { + zap.S().Infof("| %v | %v | %v | %v", v.RemoteIP, v.Method, v.URI, v.Status) + return nil + }, + })) + e.Use(middleware.RecoverWithConfig(middleware.RecoverConfig{ + LogErrorFunc: func(c echo.Context, err error, stack []byte) error { + zap.S().Errorf("Panic serving %s %s: %v\n%s", c.Request().Method, c.Request().URL.Path, err, stack) + return err + }, + })) + e.Use(middleware.CORS()) +} + func validatePort(port string) bool { if port == "" { return false diff --git a/galvanize-instancer/cmd/serve_test.go b/galvanize-instancer/cmd/serve_test.go new file mode 100644 index 0000000..9e66cff --- /dev/null +++ b/galvanize-instancer/cmd/serve_test.go @@ -0,0 +1,83 @@ +package cmd + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/28Pollux28/galvanize/internal/ansible" + "github.com/28Pollux28/galvanize/pkg/config" + "github.com/28Pollux28/galvanize/pkg/scheduler" + "github.com/28Pollux28/galvanize/pkg/worker" + "github.com/labstack/echo/v4" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" + "go.uber.org/zap/zaptest/observer" +) + +func newPanickingEcho(withMiddleware bool) *echo.Echo { + e := echo.New() + if withMiddleware { + useMiddleware(e) + } + e.GET("/panic", func(echo.Context) error { panic("boom") }) + e.GET("/ok", func(c echo.Context) error { return c.String(http.StatusOK, "ok") }) + return e +} + +func serve(e *echo.Echo, path string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + e.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil)) + return rec +} + +func TestUseMiddleware_RecoversPanics(t *testing.T) { + core, logs := observer.New(zap.InfoLevel) + t.Cleanup(zap.ReplaceGlobals(zap.New(core))) + e := newPanickingEcho(true) + + rec := serve(e, "/panic") + assert.Equal(t, http.StatusInternalServerError, rec.Code) + + panics := logs.FilterMessageSnippet("Panic serving GET /panic: boom").All() + assert.Len(t, panics, 1, "the panic is logged with its stack trace") + assert.Len(t, logs.FilterMessageSnippet("| GET | /panic | 500").All(), 1, "and by the request logger") + + assert.Equal(t, http.StatusOK, serve(e, "/ok").Code, "the server keeps serving") +} + +// Without the middleware, the panic leaves the handler: net/http then drops +// the connection without a response +func TestWithoutMiddleware_PanicEscapes(t *testing.T) { + e := newPanickingEcho(false) + assert.Panics(t, func() { serve(e, "/panic") }) +} + +func newQueuelessTestScheduler() *scheduler.ExpiryScheduler { + return scheduler.NewExpiryScheduler(nil, nil, zap.NewNop().Sugar()) +} + +// Without Redis, team requests and expiries share one LimitedDeployer with +// max_concurrent_ansible slots, and the scheduler terminates expiries itself +func TestConfigureQueueless_WithoutRedis(t *testing.T) { + for _, tc := range []struct{ configured, want int }{{0, 5}, {2, 2}} { + cfg := &config.Config{Instancer: config.InstancerConfig{MaxConcurrentAnsible: tc.configured}} + sched := newQueuelessTestScheduler() + + got := configureQueueless(cfg, nil, sched, nil, &config.StaticProvider{Cfg: cfg}) + + limited, ok := got.(*ansible.LimitedDeployer) + require.True(t, ok, "a LimitedDeployer, got %T", got) + assert.Equal(t, tc.want, limited.Limit()) + assert.Same(t, limited, sched.DirectTerminationDeployer(), "the scheduler terminates with the same slots") + } +} + +// With Redis, the job queue and its workers handle both: nothing changes +func TestConfigureQueueless_WithRedis(t *testing.T) { + sched := newQueuelessTestScheduler() + got := configureQueueless(&config.Config{}, &worker.Queue{}, sched, nil, nil) + assert.Nil(t, got, "the server keeps its default deployer") + assert.Nil(t, sched.DirectTerminationDeployer(), "expiries go to the queue") +} diff --git a/galvanize-instancer/constants.go b/galvanize-instancer/constants.go index 6b203ab..4e349e5 100644 --- a/galvanize-instancer/constants.go +++ b/galvanize-instancer/constants.go @@ -2,5 +2,4 @@ package main const ( Version = "0.7.2" - test = 123 ) diff --git a/galvanize-instancer/internal/ansible/limited_deployer.go b/galvanize-instancer/internal/ansible/limited_deployer.go new file mode 100644 index 0000000..4be8326 --- /dev/null +++ b/galvanize-instancer/internal/ansible/limited_deployer.go @@ -0,0 +1,58 @@ +package ansible + +import ( + "context" + + "github.com/28Pollux28/galvanize/internal/challenge" + "github.com/28Pollux28/galvanize/pkg/config" +) + +// LimitedDeployer runs at most a fixed number of Deploy and Terminate calls +// of the wrapped Deployer at a time; other calls wait for one to finish. +// Without Redis, it bounds the Ansible runs started by team requests and +// expiries, as the worker pool does with Redis. +type LimitedDeployer struct { + inner Deployer + slots chan struct{} +} + +var _ Deployer = (*LimitedDeployer)(nil) + +// NewLimitedDeployer wraps inner so that at most limit calls run at a time +// (at least 1). +func NewLimitedDeployer(inner Deployer, limit int) *LimitedDeployer { + if limit < 1 { + limit = 1 + } + return &LimitedDeployer{inner: inner, slots: make(chan struct{}, limit)} +} + +// Limit returns the number of calls that can run at a time. +func (d *LimitedDeployer) Limit() int { return cap(d.slots) } + +func (d *LimitedDeployer) acquire(ctx context.Context) error { + select { + case d.slots <- struct{}{}: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func (d *LimitedDeployer) release() { <-d.slots } + +func (d *LimitedDeployer) Deploy(ctx context.Context, conf *config.Config, chall *challenge.Challenge, teamID string) (string, error) { + if err := d.acquire(ctx); err != nil { + return "", err + } + defer d.release() + return d.inner.Deploy(ctx, conf, chall, teamID) +} + +func (d *LimitedDeployer) Terminate(ctx context.Context, conf *config.Config, chall *challenge.Challenge, teamID string) error { + if err := d.acquire(ctx); err != nil { + return err + } + defer d.release() + return d.inner.Terminate(ctx, conf, chall, teamID) +} diff --git a/galvanize-instancer/internal/ansible/limited_deployer_test.go b/galvanize-instancer/internal/ansible/limited_deployer_test.go new file mode 100644 index 0000000..68e38cb --- /dev/null +++ b/galvanize-instancer/internal/ansible/limited_deployer_test.go @@ -0,0 +1,117 @@ +package ansible + +import ( + "context" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/28Pollux28/galvanize/internal/challenge" + "github.com/28Pollux28/galvanize/pkg/config" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// slowDeployer records how many calls run at the same time +type slowDeployer struct { + running, peak atomic.Int32 + calls atomic.Int32 +} + +func (d *slowDeployer) run() { + d.calls.Add(1) + n := d.running.Add(1) + for { + p := d.peak.Load() + if n <= p || d.peak.CompareAndSwap(p, n) { + break + } + } + time.Sleep(20 * time.Millisecond) + d.running.Add(-1) +} + +func (d *slowDeployer) Deploy(context.Context, *config.Config, *challenge.Challenge, string) (string, error) { + d.run() + return "ok", nil +} + +func (d *slowDeployer) Terminate(context.Context, *config.Config, *challenge.Challenge, string) error { + d.run() + return nil +} + +func TestLimitedDeployer_BoundsConcurrentCalls(t *testing.T) { + inner := &slowDeployer{} + d := NewLimitedDeployer(inner, 3) + chall := &challenge.Challenge{Name: "login", Category: "web"} + + var wg sync.WaitGroup + for i := range 12 { + wg.Add(1) + go func() { + defer wg.Done() + if i%2 == 0 { + _, err := d.Deploy(context.Background(), &config.Config{}, chall, "team") + assert.NoError(t, err) + } else { + assert.NoError(t, d.Terminate(context.Background(), &config.Config{}, chall, "team")) + } + }() + } + wg.Wait() + + assert.Equal(t, int32(12), inner.calls.Load(), "every call runs") + assert.Equal(t, int32(3), inner.peak.Load(), "deploys and terminations share the 3 slots") +} + +func TestLimitedDeployer_WaitingCallHonorsContext(t *testing.T) { + inner := &blockingDeployer{release: make(chan struct{})} + d := NewLimitedDeployer(inner, 1) + chall := &challenge.Challenge{Name: "login", Category: "web"} + + go func() { _, _ = d.Deploy(context.Background(), &config.Config{}, chall, "a") }() + require.Eventually(t, func() bool { return inner.started.Load() == 1 }, time.Second, time.Millisecond) + + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + _, err := d.Deploy(ctx, &config.Config{}, chall, "b") + assert.ErrorIs(t, err, context.DeadlineExceeded, "gives up waiting for a slot") + assert.Equal(t, int32(1), inner.started.Load(), "and never ran") + close(inner.release) +} + +func TestLimitedDeployer_WaitingTerminateHonorsContext(t *testing.T) { + inner := &blockingDeployer{release: make(chan struct{})} + d := NewLimitedDeployer(inner, 1) + chall := &challenge.Challenge{Name: "login", Category: "web"} + + go func() { _, _ = d.Deploy(context.Background(), &config.Config{}, chall, "a") }() + require.Eventually(t, func() bool { return inner.started.Load() == 1 }, time.Second, time.Millisecond) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + assert.ErrorIs(t, d.Terminate(ctx, &config.Config{}, chall, "b"), context.Canceled) + close(inner.release) +} + +func TestNewLimitedDeployer_AtLeastOneSlot(t *testing.T) { + assert.Equal(t, 1, NewLimitedDeployer(&slowDeployer{}, 0).Limit()) + assert.Equal(t, 4, NewLimitedDeployer(&slowDeployer{}, 4).Limit()) +} + +type blockingDeployer struct { + started atomic.Int32 + release chan struct{} +} + +func (d *blockingDeployer) Deploy(context.Context, *config.Config, *challenge.Challenge, string) (string, error) { + d.started.Add(1) + <-d.release + return "", nil +} + +func (d *blockingDeployer) Terminate(context.Context, *config.Config, *challenge.Challenge, string) error { + return nil +} diff --git a/galvanize-instancer/internal/ansible/port_bindings_store.go b/galvanize-instancer/internal/ansible/port_bindings_store.go index 6c32bfb..f54b980 100644 --- a/galvanize-instancer/internal/ansible/port_bindings_store.go +++ b/galvanize-instancer/internal/ansible/port_bindings_store.go @@ -11,8 +11,14 @@ import ( "gorm.io/gorm/clause" ) +// portBindingDBMu serializes the port bindings store and guards +// portBindingDBs. var portBindingDBMu sync.Mutex +// portBindingDBs holds one connection pool per database file, opened on +// first use and kept for the process lifetime. +var portBindingDBs = map[string]*gorm.DB{} + type portBindingRecord struct { DeploymentKey string `gorm:"column:deployment_key;primaryKey"` ContainerPort string `gorm:"column:container_port;primaryKey"` @@ -228,13 +234,24 @@ func CleanupStalePortBindings(dbPath string) { } } +// openPortBindingDB returns the connection pool of the store at dbPath, +// opening it and creating its table on first use. Callers hold +// portBindingDBMu. Opening a pool on every call, as before, leaked one +// SQLite connection and its file descriptor per call, since none was closed. func openPortBindingDB(dbPath string) (*gorm.DB, error) { + if db, ok := portBindingDBs[dbPath]; ok { + return db, nil + } db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{}) if err != nil { return nil, err } if err := db.AutoMigrate(&portBindingRecord{}); err != nil { + if sqlDB, dbErr := db.DB(); dbErr == nil { + _ = sqlDB.Close() + } return nil, err } + portBindingDBs[dbPath] = db return db, nil } diff --git a/galvanize-instancer/internal/ansible/port_bindings_store_test.go b/galvanize-instancer/internal/ansible/port_bindings_store_test.go new file mode 100644 index 0000000..ad105ca --- /dev/null +++ b/galvanize-instancer/internal/ansible/port_bindings_store_test.go @@ -0,0 +1,85 @@ +package ansible + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func openFileDescriptors(t *testing.T) int { + t.Helper() + entries, err := os.ReadDir("/dev/fd") + if err != nil { + t.Skip("cannot count file descriptors here") + } + return len(entries) +} + +// Each call used to open a connection pool that was never closed, leaking +// one SQLite connection and file descriptor per call +func TestPortBindingsStore_ReusesConnection(t *testing.T) { + dbPath := filepath.Join(t.TempDir(), "galvanize.db") + r := portRange{lo: 34000, hi: 34999} + + // First use opens the store + _, err := ensureRandomPortBindingsInDB(dbPath, "web/a:team0", []string{"22"}, r) + require.NoError(t, err) + before := openFileDescriptors(t) + + for i := range 100 { + _ = loadPortBindingsFromDB(dbPath, "web/a:team0") + savePortBindingsToDB(dbPath, "web/a:team1", map[string]int{"22": 34500 + i%10}) + clearPortBindingsFromDB(dbPath, "web/a:team1") + _, err := ensureRandomPortBindingsInDB(dbPath, "web/a:team0", []string{"22"}, r) + require.NoError(t, err) + } + CleanupStalePortBindings(dbPath) + + assert.LessOrEqual(t, openFileDescriptors(t), before+1, "no connection opened per call") + + portBindingDBMu.Lock() + db, err := openPortBindingDB(dbPath) + again, err2 := openPortBindingDB(dbPath) + portBindingDBMu.Unlock() + require.NoError(t, err) + require.NoError(t, err2) + assert.Same(t, db, again, "one pool per database file") +} + +// A store that cannot be created is reported, and not kept for later calls +func TestPortBindingsStore_OpenFailureNotCached(t *testing.T) { + dbPath := filepath.Join(t.TempDir(), "missing-dir", "galvanize.db") + + _, err := ensureRandomPortBindingsInDB(dbPath, "web/a:team0", []string{"22"}, portRange{lo: 35000, hi: 35009}) + require.Error(t, err) + + portBindingDBMu.Lock() + _, cached := portBindingDBs[dbPath] + portBindingDBMu.Unlock() + assert.False(t, cached) + + // Once the directory exists, the store opens + require.NoError(t, os.MkdirAll(filepath.Dir(dbPath), 0o755)) + b, err := ensureRandomPortBindingsInDB(dbPath, "web/a:team0", []string{"22"}, portRange{lo: 35000, hi: 35009}) + require.NoError(t, err) + assert.Contains(t, b, "22") +} + +// The file opens but its table cannot be created: the pool is closed and +// not kept +func TestPortBindingsStore_MigrationFailureNotCached(t *testing.T) { + dbPath := filepath.Join(t.TempDir(), "galvanize.db") + require.NoError(t, os.WriteFile(dbPath, []byte("this is not a SQLite database, just some text long enough to be read"), 0o600)) + + portBindingDBMu.Lock() + db, err := openPortBindingDB(dbPath) + _, cached := portBindingDBs[dbPath] + portBindingDBMu.Unlock() + + require.Error(t, err) + assert.Nil(t, db) + assert.False(t, cached) +} diff --git a/galvanize-instancer/pkg/api/api.gen.go b/galvanize-instancer/pkg/api/api.gen.go index 46cf94d..6e95ec8 100755 --- a/galvanize-instancer/pkg/api/api.gen.go +++ b/galvanize-instancer/pkg/api/api.gen.go @@ -471,43 +471,43 @@ func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL var swaggerSpec = []string{ "H4sIAAAAAAAC/+xabW/cNhL+KwPdAUkAee28FIfzfUrjJLeHQ69IHAS4JFhwxdGKtUQqJOVkG+x/LzjU", - "u6j1OrXdpOg3aTUkhzPPvPDhfokSVZRKorQmOv0SmSTDgtHjU14IeYZlrrav8GOFxrpfS61K1FYgySTM", - "4kbprXvmaBItSiuUjE6j8wyh+QoqBeveM5bnKDcIVgGnmRdRHNltidFpZKwWchPt4qiVW0lWYHhu9+V6", - "8+7iSOPHSmjk0em7TvXJeh/aoWr9CybWqfRjlV/8r0TNnAqv0JRKGgzYo5mJ3oTFgh7+rjGNTqO/HXfG", - "Pq4tffysGfKsVqidfdfqwbRm24FlzCpRlSSP1DJCWtygdlIFGsM22Ps4Y4NGMDBx/6egReb13ouSA5x9", - "k377C799OxQo7VKm6qZdFEeJkhITt7+VqBeYyPidIV/xysfRymCiJDdTC53VEiAk1EJghEwQeLsRMJZp", - "i7xnql4MtIvRsLAPrCiQHNCb9BMzkGhk9cSp0gWz0WnEmcUjNyDkcPxcCo1mxex0obcZyvEitfwCfqry", - "HFKloZLiY9WXMYevbiyzFRkRZVU4bJBl3Nc40pWU/slYVZbu8cPXQ6tdbGLgfe4NAfK51kpPcbg3dYUn", - "uXVoezQc7NyvQ5Dbyaq3+ylaSQRqEUi1KmjllIkceU+BYEoSPDxpT+/lWTiSSo2XQlVm1eFsOo//BmtM", - "lZ7ElNVMGuGkkbsURztZwFJy4Zxj4FOGNkMNrB4FSoNFXQjJLAKjvEJ2FRJKrTYaDcVHAO97UB5HFlmx", - "mjOF+wiCo7QiFagX8Lwo7Rb86F6QHjPXGI1DdbJWVfJrwyZnxkI98FDsjGJX8CjuIB8I4MYGU8eOUTiA", - "/mBDoYB+hblivO0KzHw7ICTHzxjwwk9VsUbtqmKrNbncWYoGAUstanrXtFwYseZClGVogVY7SEWOBnJM", - "LajKNoWYFnFzHtS5vfbLtJNOG7axb+qNdxqGDWn1tkt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/NqUy+G+nhOasgmORqJqAUuzAUwyWvCrSaACizc", + "jY9ngmBMGNmMWUiYlMo6rqJk2jgag45uzAKvPCAQmFR0XmqXvmfa66RjyQqMgWlsTtmkhoMr8obvaqD3", + "L3oaTWZocE0nEa0yPPhzoTGxbh+drhpZTbgkldYobW0LYeACS0sq/HBy4p412kpLf9wcxsmY5Pu9MbIv", + "NGYJxUAk1I7+U/TzM6Adwt/qba/I7osAR/SxAWHlkComaXQBr0tMRLptCDlmOspQ6T5BGMLFgLO8pWPD", + "DDP6tUcHb5s9p4bbLo/+FNIoMGgCiCcdeehODiRPbn/jZ8NdpqqS31VT0sTUhBWf7UQssuJGeuKGw4uh", + "pviA0OE5vhg2WlWunKy3nsKioT39Gp4z2DuPCLk7aX/mSMBrND99U5WoaeN/ddD7O+gxTuZx21ydzB7J", + "zxuRb5k3ChTqRm9X6e60bahT7OhaQA1uzkYZ8cZBcd7drR9O0LRg2M/RdIC4mqY5+YNoGtt3/nfP0/S8", + "eSBVcxgTfMvB/Cfifw9jcXt/XiF70FX098jpdrlCNBAhWNGVJp+H1XP6PoDVLaWD0ZVzqAltr3xJKewf", + "HvPtLHSe+fO0HzRo/dzruimLwSoFyHS+jaFgn/t3vdpdMTvOAG2yeHANjF1VNW4zw3jH+X8+NHZT6eBY", + "6RGQIctt1mtvhwB4ifbfXuJ3+n54Q9xdgF/5n8EpEF6jvhQJuhOx1347ts3AFF5/8BeUtOdu9bk9N4h/", + "3fzP6g/EvZegv6wIvER+Owj85nOZO2gNL2vogO38eZ2m99srkTff6t5FExqsKLvdbwMAESVPwJ4yAAA=", } // GetSwagger returns the content of the embedded swagger specification file diff --git a/galvanize-instancer/pkg/config/config.go b/galvanize-instancer/pkg/config/config.go index fe92f29..150c956 100755 --- a/galvanize-instancer/pkg/config/config.go +++ b/galvanize-instancer/pkg/config/config.go @@ -55,7 +55,7 @@ type InstancerConfig struct { RandomizePublishedPorts bool `mapstructure:"randomize_published_ports,omitempty"` // Randomize host ports for non-fixed TCP published_ports RandomizedPortMin int `mapstructure:"randomized_port_min,omitempty"` // Lower bound for randomized host ports, included (default: 20000) RandomizedPortMax int `mapstructure:"randomized_port_max,omitempty"` // Upper bound for randomized host ports, included (default: 60999) - MaxConcurrentAnsible int `mapstructure:"max_concurrent_ansible,omitempty"` // Maximum concurrent Ansible executions (default: 5) - deprecated, use NumWorkers + MaxConcurrentAnsible int `mapstructure:"max_concurrent_ansible,omitempty"` // Without Redis: maximum concurrent Ansible runs for team requests and expiries (default: 5); admin actions are not limited Redis RedisConfig `mapstructure:"redis"` // Redis configuration for job queue NumWorkers int `mapstructure:"num_workers,omitempty"` // Number of Ansible workers (default: 10) Metrics MetricsConfig `mapstructure:"metrics"` // Metrics endpoint configuration @@ -98,6 +98,18 @@ func MergeResourceLimits(defaults, overrides ResourceLimits) ResourceLimits { return result } +// DefaultMaxConcurrentAnsible is the default of max_concurrent_ansible +const DefaultMaxConcurrentAnsible = 5 + +// MaxConcurrentAnsibleLimit returns max_concurrent_ansible, or its default +// when unset or not positive. +func (ic InstancerConfig) MaxConcurrentAnsibleLimit() int { + if ic.MaxConcurrentAnsible > 0 { + return ic.MaxConcurrentAnsible + } + return DefaultMaxConcurrentAnsible +} + // Default range of randomized host ports, bounds included const ( DefaultRandomizedPortMin = 20000 diff --git a/galvanize-instancer/pkg/config/config_test.go b/galvanize-instancer/pkg/config/config_test.go index 9d80eb4..9538ada 100644 --- a/galvanize-instancer/pkg/config/config_test.go +++ b/galvanize-instancer/pkg/config/config_test.go @@ -54,3 +54,9 @@ func TestLoad_RejectsInvalidPortRange(t *testing.T) { assert.Contains(t, err.Error(), "randomized port range 40000-30009") assert.Equal(t, 30000, Get().Instancer.RandomizedPortMin, "the current config is kept") } + +func TestMaxConcurrentAnsibleLimit(t *testing.T) { + assert.Equal(t, 5, InstancerConfig{}.MaxConcurrentAnsibleLimit(), "default") + assert.Equal(t, 5, InstancerConfig{MaxConcurrentAnsible: -2}.MaxConcurrentAnsibleLimit()) + assert.Equal(t, 2, InstancerConfig{MaxConcurrentAnsible: 2}.MaxConcurrentAnsibleLimit()) +} diff --git a/galvanize-instancer/pkg/models/deployment.go b/galvanize-instancer/pkg/models/deployment.go index 1e91883..6ac9c98 100755 --- a/galvanize-instancer/pkg/models/deployment.go +++ b/galvanize-instancer/pkg/models/deployment.go @@ -27,6 +27,7 @@ var ( ErrAlreadyExpired = errors.New("deployment already expired") ErrNoExtensionsLeft = errors.New("no time extensions left") ErrNoExpiration = errors.New("deployment has no expiration time") + ErrNotRunning = errors.New("deployment is not running") ) type Deployment struct { @@ -196,6 +197,10 @@ func DeleteDeployment(db *gorm.DB, deployment *Deployment) error { } func ExtendDeploymentExpiration(db *gorm.DB, deployment *Deployment, extension, extensionWindow time.Duration, maxExtensions int) error { + // A deployment still starting, stopping or failed has nothing to extend + if deployment.Status != DeploymentStatusRunning { + return ErrNotRunning + } if deployment.ExpiresAt == nil { return ErrNoExpiration } diff --git a/galvanize-instancer/pkg/restserver.go b/galvanize-instancer/pkg/restserver.go index 35515c0..8d2a564 100755 --- a/galvanize-instancer/pkg/restserver.go +++ b/galvanize-instancer/pkg/restserver.go @@ -26,14 +26,15 @@ import ( // Server implements api.ServerInterface type Server struct { - db *gorm.DB - challIdx challenge.ChallengeIndexer - confProv config.Provider - deployer ansible.Deployer - expirySched *scheduler.ExpiryScheduler - kmu keymutex.KeyMutex - wg sync.WaitGroup - jobQueue *worker.Queue // Redis job queue (optional, nil means use direct goroutines) + db *gorm.DB + challIdx challenge.ChallengeIndexer + confProv config.Provider + deployer ansible.Deployer + teamDeployer ansible.Deployer // team requests run without the job queue + expirySched *scheduler.ExpiryScheduler + kmu keymutex.KeyMutex + wg sync.WaitGroup + jobQueue *worker.Queue // Redis job queue (optional, nil means use direct goroutines) } // ServerOpts holds the dependencies needed to construct a Server. @@ -42,9 +43,13 @@ type ServerOpts struct { ChallengeIndexer challenge.ChallengeIndexer ConfigProvider config.Provider Deployer ansible.Deployer - ExpiryScheduler *scheduler.ExpiryScheduler - KeyMutex keymutex.KeyMutex - JobQueue *worker.Queue // Optional: if provided, jobs are queued to Redis + // TeamDeployer runs team deploys and terminations started without the + // job queue (Redis not configured), e.g. an ansible.LimitedDeployer. + // Optional: defaults to Deployer. Admin actions always use Deployer. + TeamDeployer ansible.Deployer + ExpiryScheduler *scheduler.ExpiryScheduler + KeyMutex keymutex.KeyMutex + JobQueue *worker.Queue // Optional: if provided, jobs are queued to Redis } var _ api.ServerInterface = (*Server)(nil) @@ -61,14 +66,19 @@ func NewServerWithOpts(opts ServerOpts) *Server { if deployer == nil { deployer = &ansible.AnsibleDeployer{} } + teamDeployer := opts.TeamDeployer + if teamDeployer == nil { + teamDeployer = deployer + } return &Server{ - db: opts.DB, - challIdx: opts.ChallengeIndexer, - confProv: opts.ConfigProvider, - deployer: deployer, - expirySched: opts.ExpiryScheduler, - kmu: kmu, - jobQueue: opts.JobQueue, + db: opts.DB, + challIdx: opts.ChallengeIndexer, + confProv: opts.ConfigProvider, + deployer: deployer, + teamDeployer: teamDeployer, + expirySched: opts.ExpiryScheduler, + kmu: kmu, + jobQueue: opts.JobQueue, } } @@ -205,7 +215,7 @@ func (s *Server) DeployInstance(ctx echo.Context) error { defer s.wg.Done() start := time.Now() - connInfo, deployErr := s.deployer.Deploy(context.Background(), conf, chall, claims.TeamID) + connInfo, deployErr := s.teamDeployer.Deploy(context.Background(), conf, chall, claims.TeamID) duration := time.Since(start) result := "success" @@ -323,6 +333,8 @@ func (s *Server) ExtendInstance(ctx echo.Context) error { reason = "no_extensions_left" case errors.Is(err, models.ErrAlreadyExpired): reason = "already_expired" + case errors.Is(err, models.ErrNotRunning): + reason = "not_running" default: reason = "unknown" } @@ -408,7 +420,7 @@ func (s *Server) TerminateInstance(ctx echo.Context) error { teamID = *deployment.TeamID } start := time.Now() - terminateErr := models.TerminateDeployment(s.db, s.challIdx, s.deployer, conf, deployment) + terminateErr := models.TerminateDeployment(s.db, s.challIdx, s.teamDeployer, conf, deployment) duration := time.Since(start) result := "success" if terminateErr != nil { diff --git a/galvanize-instancer/pkg/restserver_admin.go b/galvanize-instancer/pkg/restserver_admin.go index 02009a1..1c7c2ec 100644 --- a/galvanize-instancer/pkg/restserver_admin.go +++ b/galvanize-instancer/pkg/restserver_admin.go @@ -246,6 +246,7 @@ func (s *Server) DeployAllAdminInstances(ctx echo.Context) error { return ctx.JSON(200, api.BulkOperationResponse{ Message: "No unique challenges found", ChallengesCount: 0, + Challenges: []api.ChallengeCategoryResponse{}, }) } @@ -273,7 +274,10 @@ func (s *Server) DeployAllAdminInstances(ctx echo.Context) error { } deployed++ - challenges = append(challenges, api.ChallengeCategoryResponse{}) + challenges = append(challenges, api.ChallengeCategoryResponse{ + Category: chall.Category, + ChallengeName: chall.Name, + }) // Deploy in goroutine go func(ch *challenge.Challenge) { @@ -338,6 +342,7 @@ func (s *Server) TerminateAllAdminInstances(ctx echo.Context) error { return ctx.JSON(200, api.BulkOperationResponse{ Message: "No unique deployments found", ChallengesCount: 0, + Challenges: []api.ChallengeCategoryResponse{}, }) } diff --git a/galvanize-instancer/pkg/restserver_admin_test.go b/galvanize-instancer/pkg/restserver_admin_test.go index 145f3f5..e765c0a 100644 --- a/galvanize-instancer/pkg/restserver_admin_test.go +++ b/galvanize-instancer/pkg/restserver_admin_test.go @@ -257,3 +257,49 @@ deploy_parameters: assert.Equal(t, "bof", chall2.Name) assert.Equal(t, "pwn", chall2.Category) } + +// --------------------------------------------------------------------------- +// DeployAllAdminInstances / TerminateAllAdminInstances +// --------------------------------------------------------------------------- + +func otherUniqueChallenge() *challenge.Challenge { + c := uniqueChallenge() + c.Name, c.Category = "board", "misc" + return c +} + +func TestDeployAllAdminInstances_ListsDeployedChallenges(t *testing.T) { + deployer := &mockDeployer{} + srv := newTestServerWithMock(t, deployer, newMockIndexer(uniqueChallenge(), otherUniqueChallenge(), httpChallenge())) + ctx, rec := echoCtxWithClaimsAndBody(http.MethodPost, "/admin/deploy-all", &auth.Claims{Role: "admin"}, "") + + require.NoError(t, srv.DeployAllAdminInstances(ctx)) + assert.Equal(t, http.StatusAccepted, rec.Code) + waitForBackground(t, srv) + + var resp api.BulkOperationResponse + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp)) + assert.Equal(t, 2, resp.ChallengesCount) + assert.ElementsMatch(t, []api.ChallengeCategoryResponse{ + {Category: "web", ChallengeName: "shared"}, + {Category: "misc", ChallengeName: "board"}, + }, resp.Challenges, "each deployed unique challenge, not empty entries") + assert.Len(t, deployer.deployCalls, 2) + + // Already deployed: nothing to do, and the list is empty, not null + ctx, rec = echoCtxWithClaimsAndBody(http.MethodPost, "/admin/deploy-all", &auth.Claims{Role: "admin"}, "") + require.NoError(t, srv.DeployAllAdminInstances(ctx)) + assert.JSONEq(t, `{"message":"Deploying 0 unique challenges","challenges_count":0,"challenges":[]}`, rec.Body.String()) +} + +func TestBulkAdminInstances_EmptyListNotNull(t *testing.T) { + srv := newTestServerWithMock(t, &mockDeployer{}, newMockIndexer(httpChallenge())) + + ctx, rec := echoCtxWithClaimsAndBody(http.MethodPost, "/admin/deploy-all", &auth.Claims{Role: "admin"}, "") + require.NoError(t, srv.DeployAllAdminInstances(ctx)) + assert.JSONEq(t, `{"message":"No unique challenges found","challenges_count":0,"challenges":[]}`, rec.Body.String()) + + ctx, rec = echoCtxWithClaimsAndBody(http.MethodPost, "/admin/terminate-all", &auth.Claims{Role: "admin"}, "") + require.NoError(t, srv.TerminateAllAdminInstances(ctx)) + assert.JSONEq(t, `{"message":"No unique deployments found","challenges_count":0,"challenges":[]}`, rec.Body.String()) +} diff --git a/galvanize-instancer/pkg/restserver_test.go b/galvanize-instancer/pkg/restserver_test.go index f61d6f6..59b3376 100644 --- a/galvanize-instancer/pkg/restserver_test.go +++ b/galvanize-instancer/pkg/restserver_test.go @@ -855,3 +855,58 @@ func TestTerminateInstance_AdminCanTerminateAnychallenge(t *testing.T) { waitForBackground(t, srv) assert.Len(t, deployer.terminateCalls, 1) } + +func TestExtendInstance_NotRunning(t *testing.T) { + for _, status := range []string{models.DeploymentStatusStarting, models.DeploymentStatusStopping, models.DeploymentStatusError} { + t.Run(status, func(t *testing.T) { + srv := newTestServerWithMock(t, &mockDeployer{}, newMockIndexer(httpChallenge())) + cfg := defaultTestConfig() + + d, err := models.CreateDeployment(srv.db, "http", "team1", "web", cfg.Instancer.DeploymentTTL, cfg.Instancer.DeploymentMaxExtensions) + require.NoError(t, err) + d.Status = status + // Inside the extension window, with extensions left + d.ExpiresAt = utils.Ptr(time.Now().Add(5 * time.Minute)) + require.NoError(t, srv.db.Save(d).Error) + + claims := &auth.Claims{TeamID: "team1", ChallengeName: "http", Category: "web", Role: "user"} + ctx, rec := echoCtxWithClaimsAndBody(http.MethodPost, "/extend", claims, "") + + require.NoError(t, srv.ExtendInstance(ctx)) + assert.Equal(t, http.StatusBadRequest, rec.Code) + assert.Contains(t, rec.Body.String(), "deployment is not running") + + got, err := models.GetDeploymentByID(srv.db, d.ID) + require.NoError(t, err) + assert.WithinDuration(t, *d.ExpiresAt, *got.ExpiresAt, time.Second, "not extended") + assert.Equal(t, d.TimeExtensionLeft, got.TimeExtensionLeft, "no extension used up") + }) + } +} + +// Without the job queue, team requests use TeamDeployer and admin actions +// the unlimited Deployer +func TestTeamDeployer_UsedForTeamRequestsOnly(t *testing.T) { + admin, team := &mockDeployer{}, &mockDeployer{} + srv := newTestServerWithMock(t, admin, newMockIndexer(httpChallenge(), uniqueChallenge())) + srv.teamDeployer = team + + claims := &auth.Claims{TeamID: "team1", ChallengeName: "http", Category: "web", Role: "user"} + ctx, rec := echoCtxWithClaimsAndBody(http.MethodPost, "/deploy", claims, `{"challenge_name":"http","category":"web"}`) + require.NoError(t, srv.DeployInstance(ctx)) + require.Equal(t, http.StatusAccepted, rec.Code) + + ctx, rec = echoCtxWithClaimsAndBody(http.MethodPost, "/admin/deploy-all", &auth.Claims{Role: "admin"}, "") + require.NoError(t, srv.DeployAllAdminInstances(ctx)) + require.Equal(t, http.StatusAccepted, rec.Code) + waitForBackground(t, srv) + + assert.Len(t, team.deployCalls, 1, "the team deploy") + assert.Len(t, admin.deployCalls, 1, "the admin deploy-all") +} + +func TestNewServerWithOpts_TeamDeployerDefaultsToDeployer(t *testing.T) { + d := &mockDeployer{} + srv := NewServerWithOpts(ServerOpts{Deployer: d}) + assert.Same(t, d, srv.teamDeployer) +} diff --git a/galvanize-instancer/pkg/scheduler/scheduler.go b/galvanize-instancer/pkg/scheduler/scheduler.go index f207a95..a48a4af 100644 --- a/galvanize-instancer/pkg/scheduler/scheduler.go +++ b/galvanize-instancer/pkg/scheduler/scheduler.go @@ -6,6 +6,9 @@ import ( "sync" "time" + "github.com/28Pollux28/galvanize/internal/ansible" + "github.com/28Pollux28/galvanize/internal/challenge" + "github.com/28Pollux28/galvanize/pkg/config" "github.com/28Pollux28/galvanize/pkg/models" "github.com/28Pollux28/galvanize/pkg/worker" "go.uber.org/zap" @@ -22,9 +25,18 @@ type ExpiryScheduler struct { rescheduleChan chan struct{} wg sync.WaitGroup // track ongoing terminations jobQueue *worker.Queue + direct *directTermination l *zap.SugaredLogger } +// directTermination holds what terminating a deployment in place needs, for +// when no job queue is configured. +type directTermination struct { + challIdx challenge.ChallengeIndexer + confProv config.Provider + deployer ansible.Deployer +} + func NewExpiryScheduler(db *gorm.DB, jobQueue *worker.Queue, logger *zap.SugaredLogger) *ExpiryScheduler { return &ExpiryScheduler{ db: db, @@ -36,6 +48,23 @@ func NewExpiryScheduler(db *gorm.DB, jobQueue *worker.Queue, logger *zap.Sugared } } +// WithDirectTermination makes the scheduler terminate expired deployments +// itself, as the API does, when it has no job queue: without one (Redis not +// configured), expired deployments were only marked as errors. +func (s *ExpiryScheduler) WithDirectTermination(challIdx challenge.ChallengeIndexer, confProv config.Provider, deployer ansible.Deployer) *ExpiryScheduler { + s.direct = &directTermination{challIdx: challIdx, confProv: confProv, deployer: deployer} + return s +} + +// DirectTerminationDeployer returns the deployer set by +// WithDirectTermination, or nil when expired deployments go to the job queue. +func (s *ExpiryScheduler) DirectTerminationDeployer() ansible.Deployer { + if s.direct == nil { + return nil + } + return s.direct.deployer +} + func (s *ExpiryScheduler) Start(ctx context.Context) { s.l.Debug("starting expiry scheduler") s.fetchNextExpiries() @@ -200,6 +229,14 @@ func (s *ExpiryScheduler) terminateDeployment(deploymentID uint) { } else { s.l.Infof("submitted termination job for deployment %d (team: %s, challenge: %s/%s)", deploymentID, teamID, deployment.Category, deployment.ChallengeName) } + } else if s.direct != nil { + // TerminateDeployment marks the deployment as an error when it fails + conf := s.direct.confProv.GetConfig() + if err := models.TerminateDeployment(s.db, s.direct.challIdx, s.direct.deployer, conf, &deployment); err != nil { + s.l.Errorf("failed to terminate expired deployment %d: %v", deploymentID, err) + } else { + s.l.Infof("terminated expired deployment %d (challenge: %s/%s)", deploymentID, deployment.Category, deployment.ChallengeName) + } } else { s.l.Warnf("no job queue available, cannot terminate deployment %d", deploymentID) _ = models.UpdateDeploymentStatus(s.db, &deployment, models.DeploymentStatusError, "", "no job queue configured for termination") diff --git a/galvanize-instancer/pkg/scheduler/scheduler_test.go b/galvanize-instancer/pkg/scheduler/scheduler_test.go new file mode 100644 index 0000000..d94d3b6 --- /dev/null +++ b/galvanize-instancer/pkg/scheduler/scheduler_test.go @@ -0,0 +1,141 @@ +package scheduler + +import ( + "context" + "errors" + "fmt" + "sync" + "testing" + "time" + + "github.com/28Pollux28/galvanize/internal/challenge" + "github.com/28Pollux28/galvanize/pkg/config" + "github.com/28Pollux28/galvanize/pkg/models" + "github.com/28Pollux28/galvanize/pkg/utils" + "github.com/glebarez/sqlite" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" + "gorm.io/gorm" +) + +type mockDeployer struct { + mu sync.Mutex + terminated []string + terminateFn func() error +} + +func (m *mockDeployer) Deploy(context.Context, *config.Config, *challenge.Challenge, string) (string, error) { + return "", nil +} + +func (m *mockDeployer) Terminate(_ context.Context, _ *config.Config, chall *challenge.Challenge, teamID string) error { + m.mu.Lock() + defer m.mu.Unlock() + m.terminated = append(m.terminated, chall.Category+"/"+chall.Name+":"+teamID) + if m.terminateFn != nil { + return m.terminateFn() + } + return nil +} + +type mockIndexer struct { + challs map[string]*challenge.Challenge +} + +func (m *mockIndexer) Get(category, name string) (*challenge.Challenge, error) { + if c, ok := m.challs[category+"/"+name]; ok { + return c, nil + } + return nil, fmt.Errorf("challenge not found: %s/%s", category, name) +} +func (m *mockIndexer) GetAllUnique() []*challenge.Challenge { return nil } +func (m *mockIndexer) GetAll() []*challenge.Challenge { return nil } +func (m *mockIndexer) BuildIndex(string) error { return nil } +func (m *mockIndexer) Skipped() []challenge.SkippedChallenge { return nil } +func (m *mockIndexer) add(c *challenge.Challenge) *mockIndexer { + m.challs[c.Category+"/"+c.Name] = c + return m +} +func newIndexer() *mockIndexer { return &mockIndexer{challs: map[string]*challenge.Challenge{}} } + +func newTestDB(t *testing.T) *gorm.DB { + t.Helper() + db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) + require.NoError(t, err) + require.NoError(t, db.AutoMigrate(models.Deployment{})) + return db +} + +// expiredDeployment stores a running team deployment of web/login that +// expired a minute ago. +func expiredDeployment(t *testing.T, db *gorm.DB) *models.Deployment { + t.Helper() + team := "team1" + d := &models.Deployment{ + ChallengeName: "login", Category: "web", TeamID: &team, + Status: models.DeploymentStatusRunning, ExpiresAt: utils.Ptr(time.Now().Add(-time.Minute)), + } + require.NoError(t, db.Create(d).Error) + return d +} + +func newScheduler(db *gorm.DB) *ExpiryScheduler { + return NewExpiryScheduler(db, nil, zap.NewNop().Sugar()) +} + +func TestTerminateDeployment_DirectWithoutQueue(t *testing.T) { + db := newTestDB(t) + d := expiredDeployment(t, db) + deployer := &mockDeployer{} + idx := newIndexer().add(&challenge.Challenge{Name: "login", Category: "web"}) + s := newScheduler(db).WithDirectTermination(idx, &config.StaticProvider{Cfg: &config.Config{}}, deployer) + + s.terminateDeployment(d.ID) + + assert.Equal(t, []string{"web/login:team1"}, deployer.terminated) + _, err := models.GetDeploymentByID(db, d.ID) + assert.True(t, errors.Is(err, models.ErrNotFound), "the deployment is deleted, got %v", err) +} + +func TestTerminateDeployment_DirectFailureMarksError(t *testing.T) { + db := newTestDB(t) + d := expiredDeployment(t, db) + deployer := &mockDeployer{terminateFn: func() error { return errors.New("ansible failed") }} + idx := newIndexer().add(&challenge.Challenge{Name: "login", Category: "web"}) + s := newScheduler(db).WithDirectTermination(idx, &config.StaticProvider{Cfg: &config.Config{}}, deployer) + + s.terminateDeployment(d.ID) + + got, err := models.GetDeploymentByID(db, d.ID) + require.NoError(t, err) + assert.Equal(t, models.DeploymentStatusError, got.Status) + assert.Contains(t, got.Error, "ansible failed") +} + +func TestTerminateDeployment_NoQueueNoDirectMarksError(t *testing.T) { + db := newTestDB(t) + d := expiredDeployment(t, db) + + newScheduler(db).terminateDeployment(d.ID) + + got, err := models.GetDeploymentByID(db, d.ID) + require.NoError(t, err) + assert.Equal(t, models.DeploymentStatusError, got.Status) + assert.Contains(t, got.Error, "no job queue configured") +} + +func TestTerminateDeployment_ExtendedIsKept(t *testing.T) { + db := newTestDB(t) + d := expiredDeployment(t, db) + require.NoError(t, db.Model(d).Update("expires_at", time.Now().Add(time.Hour)).Error) + deployer := &mockDeployer{} + s := newScheduler(db).WithDirectTermination(newIndexer(), &config.StaticProvider{Cfg: &config.Config{}}, deployer) + + s.terminateDeployment(d.ID) + + assert.Empty(t, deployer.terminated) + got, err := models.GetDeploymentByID(db, d.ID) + require.NoError(t, err) + assert.Equal(t, models.DeploymentStatusRunning, got.Status) +}