From 3a6c10823b56bee81f4a01c4c0b867c5e9b1bb27 Mon Sep 17 00:00:00 2001 From: CorentinFelten Date: Thu, 1 Oct 2026 19:32:51 -0400 Subject: [PATCH 01/11] fix: default deployment_max_extensions to 3, as documented config.example.yaml documents a default of 3 extensions per deployment, but cmd/root.go set 4, so a config without the key allowed one more extension than documented. --- CHANGELOG.md | 3 +++ galvanize-instancer/cmd/root.go | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 28a6128..dc63e87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## 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 + ## v0.7.2 (2026-10-01) ### Changed diff --git a/galvanize-instancer/cmd/root.go b/galvanize-instancer/cmd/root.go index 216789e..9072312 100755 --- a/galvanize-instancer/cmd/root.go +++ b/galvanize-instancer/cmd/root.go @@ -54,7 +54,7 @@ func initConfig() { viper.SetDefault("instancer.deployment_ttl", "1h") viper.SetDefault("instancer.deployment_ttl_extension", "30m") - viper.SetDefault("instancer.deployment_max_extensions", 4) + viper.SetDefault("instancer.deployment_max_extensions", 3) viper.SetDefault("instancer.deployment_extension_window", "30m") if err := viper.ReadInConfig(); err != nil { From 44aebda2e48ea7b94ee282b1e9f0c81fd47aa56d Mon Sep 17 00:00:00 2001 From: CorentinFelten Date: Thu, 1 Oct 2026 19:33:50 -0400 Subject: [PATCH 02/11] fix: terminate expired deployments when Redis is not configured Without a job queue, the expiry scheduler marked each expired deployment as an error ("no job queue configured for termination") and left its containers running, while the API's own terminate endpoint already terminates in place in that case. ExpiryScheduler.WithDirectTermination gives the scheduler the challenge index, config provider and deployer it needs, and serve sets it when Redis is not configured: expired deployments are then terminated with models.TerminateDeployment, as the API does, which marks them as errors only if the termination fails. --- CHANGELOG.md | 1 + galvanize-instancer/cmd/serve.go | 4 + .../pkg/scheduler/scheduler.go | 28 ++++ .../pkg/scheduler/scheduler_test.go | 141 ++++++++++++++++++ 4 files changed, 174 insertions(+) create mode 100644 galvanize-instancer/pkg/scheduler/scheduler_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index dc63e87..9f3bf5b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### 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 ## v0.7.2 (2026-10-01) diff --git a/galvanize-instancer/cmd/serve.go b/galvanize-instancer/cmd/serve.go index 5ea7d2f..5cb125e 100755 --- a/galvanize-instancer/cmd/serve.go +++ b/galvanize-instancer/cmd/serve.go @@ -198,6 +198,10 @@ var serveCmd = &cobra.Command{ // Initialize scheduler with job queue (can be nil if Redis not configured) expirySched := scheduler.NewExpiryScheduler(db, jobQueue, zap.S().Named("ExpiryScheduler")) + if jobQueue == nil { + // Without Redis, expired deployments are terminated in place + expirySched.WithDirectTermination(challIdx, confProv, &ansible.AnsibleDeployer{}) + } // 7. Server Init via DI srv := server.NewServerWithOpts(server.ServerOpts{ diff --git a/galvanize-instancer/pkg/scheduler/scheduler.go b/galvanize-instancer/pkg/scheduler/scheduler.go index f207a95..03f77f8 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,14 @@ 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 +} + func (s *ExpiryScheduler) Start(ctx context.Context) { s.l.Debug("starting expiry scheduler") s.fetchNextExpiries() @@ -200,6 +220,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) +} From a1b22fbaed04fbc3b5d23f907b38cf630cb04926 Mon Sep 17 00:00:00 2001 From: CorentinFelten Date: Thu, 1 Oct 2026 19:34:34 -0400 Subject: [PATCH 03/11] fix: recover from panics in request handlers middleware.Recover was commented out since the first commit, with no note on why. Without it, net/http recovers a panicking handler itself but drops the connection without a response, and the request logger never logs the request. Nothing in Galvanize panics or recovers on purpose, so enabling it changes nothing else. The middleware setup moves to useMiddleware, so it can be tested. Recover logs the panic and its stack trace through zap, and the request logger then logs the 500 response. --- CHANGELOG.md | 1 + galvanize-instancer/cmd/serve.go | 48 ++++++++++++++++--------- galvanize-instancer/cmd/serve_test.go | 50 +++++++++++++++++++++++++++ 3 files changed, 82 insertions(+), 17 deletions(-) create mode 100644 galvanize-instancer/cmd/serve_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f3bf5b..032f41b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### 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 ## v0.7.2 (2026-10-01) diff --git a/galvanize-instancer/cmd/serve.go b/galvanize-instancer/cmd/serve.go index 5cb125e..a85462d 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 @@ -284,6 +268,36 @@ func metricsHandler(username, password string, h http.Handler) http.Handler { }) } +// 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..aec6b10 --- /dev/null +++ b/galvanize-instancer/cmd/serve_test.go @@ -0,0 +1,50 @@ +package cmd + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/labstack/echo/v4" + "github.com/stretchr/testify/assert" + "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") }) +} From 526c1b8fcba142e3b2bad9672013f6a1712f74bc Mon Sep 17 00:00:00 2001 From: CorentinFelten Date: Thu, 1 Oct 2026 19:35:18 -0400 Subject: [PATCH 04/11] fix: list the deployed challenges in the deploy-all response DeployAllAdminInstances appended an empty ChallengeCategoryResponse for each challenge it deployed, so its challenges list held one {"category": "", "challenge_name": ""} per challenge. It now holds each one's category and name, as TerminateAllAdminInstances already does. Zync only reads challenges_count, so it is unaffected. Both endpoints also returned "challenges": null when there was nothing to do, although the API spec requires an array: they now return []. --- CHANGELOG.md | 1 + galvanize-instancer/pkg/restserver_admin.go | 7 ++- .../pkg/restserver_admin_test.go | 46 +++++++++++++++++++ 3 files changed, 53 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 032f41b..c8ce59e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ - 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 ## v0.7.2 (2026-10-01) 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()) +} From 6eb7e7ebbb2d53769e18563e9042d3fe632e50ab Mon Sep 17 00:00:00 2001 From: CorentinFelten Date: Thu, 1 Oct 2026 19:35:55 -0400 Subject: [PATCH 05/11] fix: refuse to extend a deployment that is not running ExtendDeploymentExpiration only checked the expiry, the extension window and the extensions left, so a deployment still starting, being stopped or failed could be extended, using up an extension, and ExtendInstance answered with status running regardless. It now returns ErrNotRunning first for any deployment not running, which ExtendInstance answers with a 400 like the other refusals and counts as not_running in the extension rejection metric. --- CHANGELOG.md | 1 + galvanize-instancer/api/openapi.yaml.in | 2 +- galvanize-instancer/pkg/api/api.gen.go | 74 ++++++++++---------- galvanize-instancer/pkg/models/deployment.go | 5 ++ galvanize-instancer/pkg/restserver.go | 2 + galvanize-instancer/pkg/restserver_test.go | 28 ++++++++ 6 files changed, 74 insertions(+), 38 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c8ce59e..41c7bf4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ - 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` ## v0.7.2 (2026-10-01) 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/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", - "lZ7ElNVMGuGkkbsURztZwFJy4Zxj4FOGNkMNrB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ogO38eZ2m99srkTff6t5FExqsKLvdbwMAESVPwJ4yAAA=", } // GetSwagger returns the content of the embedded swagger specification file 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..939a55e 100755 --- a/galvanize-instancer/pkg/restserver.go +++ b/galvanize-instancer/pkg/restserver.go @@ -323,6 +323,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" } diff --git a/galvanize-instancer/pkg/restserver_test.go b/galvanize-instancer/pkg/restserver_test.go index f61d6f6..f6927a4 100644 --- a/galvanize-instancer/pkg/restserver_test.go +++ b/galvanize-instancer/pkg/restserver_test.go @@ -855,3 +855,31 @@ 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") + }) + } +} From 2220b3df730803cb2a537d65cd2db53bdfdc2916 Mon Sep 17 00:00:00 2001 From: CorentinFelten Date: Thu, 1 Oct 2026 19:36:26 -0400 Subject: [PATCH 06/11] fix(playbooks): do not declare the Traefik network for TCP challenges The tcp playbook's compose definition declared traefik_network as an external network, but the TCP service runs with network_mode: bridge and publishes its ports, so it never joins it. Ansible failed with "'traefik_network' is undefined" when the parameter was not set, and TCP challenges do not need Traefik. Checked by rendering the compose definition with and without traefik_network and validating it with docker compose config. Instances deployed by the previous playbook still terminate: the network was external, so compose never created or removed it. --- CHANGELOG.md | 1 + data/playbooks/tcp.yaml | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 41c7bf4..d69d711 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ - 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 ## v0.7.2 (2026-10-01) 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 From 1b8a2fd39eccd6b17ab9343139f74618828e493b Mon Sep 17 00:00:00 2001 From: CorentinFelten Date: Thu, 1 Oct 2026 19:36:59 -0400 Subject: [PATCH 07/11] fix(docker): make the image's default command valid The Dockerfile's CMD ran `galvanize serve 8080 -c config.yaml`, but serve takes no arguments (cobra.NoArgs) and reads the port from --port, so the container exited with 'unknown command "8080" for "galvanize serve"' unless a command was given, as docker-compose.yml does. The default is now the same command as docker-compose.yml's: serve --port 8080 --config data/config.yaml. --- CHANGELOG.md | 1 + galvanize-instancer/Dockerfile | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d69d711..b3dbf22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ - `/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 ## v0.7.2 (2026-10-01) 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 From 4a8d0f3fb8fb05f47eda383803d064e54f8735d6 Mon Sep 17 00:00:00 2001 From: CorentinFelten Date: Thu, 1 Oct 2026 19:38:29 -0400 Subject: [PATCH 08/11] fix: honor max_concurrent_ansible when Redis is not configured max_concurrent_ansible is documented as the cap on concurrent Ansible runs without Redis (default 5), but nothing read it: each team deploy or terminate, and now each expiry, started its own unbounded run. ansible.LimitedDeployer wraps a Deployer with a fixed number of slots shared by Deploy and Terminate; further calls wait for a slot, or for their context. Without Redis, serve gives one with max_concurrent_ansible slots to the server, as ServerOpts.TeamDeployer for team requests, and to the expiry scheduler. Admin actions keep the unlimited deployer, so they are never queued behind team requests. With Redis, num_workers bounds these runs as before. --- CHANGELOG.md | 1 + config.example.yaml | 2 +- galvanize-instancer/cmd/serve.go | 11 +- .../internal/ansible/limited_deployer.go | 55 ++++++++++ .../internal/ansible/limited_deployer_test.go | 102 ++++++++++++++++++ galvanize-instancer/pkg/config/config.go | 14 ++- galvanize-instancer/pkg/config/config_test.go | 6 ++ galvanize-instancer/pkg/restserver.go | 50 +++++---- galvanize-instancer/pkg/restserver_test.go | 27 +++++ 9 files changed, 244 insertions(+), 24 deletions(-) create mode 100644 galvanize-instancer/internal/ansible/limited_deployer.go create mode 100644 galvanize-instancer/internal/ansible/limited_deployer_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index b3dbf22..cda7587 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ - `/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 ## v0.7.2 (2026-10-01) 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/galvanize-instancer/cmd/serve.go b/galvanize-instancer/cmd/serve.go index a85462d..bd12175 100755 --- a/galvanize-instancer/cmd/serve.go +++ b/galvanize-instancer/cmd/serve.go @@ -146,6 +146,8 @@ var serveCmd = &cobra.Command{ // 6. Initialize Redis job queue and worker pool (if configured) var jobQueue *worker.Queue var workerPool *worker.Pool + // Runs team requests and expiries without Redis; nil: the default deployer + var teamDeployer ansible.Deployer if cfg.Instancer.Redis.Addr != "" { var queueErr error @@ -177,14 +179,18 @@ var serveCmd = &cobra.Command{ }) zap.S().Infof("Redis job queue enabled with %d workers", numWorkers) } else { - zap.S().Info("Redis not configured, using direct goroutines for deployments") + // Team requests and expiries share max_concurrent_ansible slots; + // admin actions are not limited + limit := cfg.Instancer.MaxConcurrentAnsibleLimit() + teamDeployer = ansible.NewLimitedDeployer(&ansible.AnsibleDeployer{}, limit) + 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) } // Initialize scheduler with job queue (can be nil if Redis not configured) expirySched := scheduler.NewExpiryScheduler(db, jobQueue, zap.S().Named("ExpiryScheduler")) if jobQueue == nil { // Without Redis, expired deployments are terminated in place - expirySched.WithDirectTermination(challIdx, confProv, &ansible.AnsibleDeployer{}) + expirySched.WithDirectTermination(challIdx, confProv, teamDeployer) } // 7. Server Init via DI @@ -193,6 +199,7 @@ var serveCmd = &cobra.Command{ ChallengeIndexer: challIdx, ConfigProvider: confProv, Deployer: &ansible.AnsibleDeployer{}, + TeamDeployer: teamDeployer, ExpiryScheduler: expirySched, JobQueue: jobQueue, }) diff --git a/galvanize-instancer/internal/ansible/limited_deployer.go b/galvanize-instancer/internal/ansible/limited_deployer.go new file mode 100644 index 0000000..478075d --- /dev/null +++ b/galvanize-instancer/internal/ansible/limited_deployer.go @@ -0,0 +1,55 @@ +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)} +} + +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..79a2d22 --- /dev/null +++ b/galvanize-instancer/internal/ansible/limited_deployer_test.go @@ -0,0 +1,102 @@ +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 TestNewLimitedDeployer_AtLeastOneSlot(t *testing.T) { + assert.Equal(t, 1, cap(NewLimitedDeployer(&slowDeployer{}, 0).slots)) +} + +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/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/restserver.go b/galvanize-instancer/pkg/restserver.go index 939a55e..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" @@ -410,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_test.go b/galvanize-instancer/pkg/restserver_test.go index f6927a4..59b3376 100644 --- a/galvanize-instancer/pkg/restserver_test.go +++ b/galvanize-instancer/pkg/restserver_test.go @@ -883,3 +883,30 @@ func TestExtendInstance_NotRunning(t *testing.T) { }) } } + +// 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) +} From 5c1a2c2defc392ea815c0ba03ac4036b80b0f91c Mon Sep 17 00:00:00 2001 From: CorentinFelten Date: Thu, 1 Oct 2026 19:38:36 -0400 Subject: [PATCH 09/11] chore: remove the unused test constant constants.go declared test = 123, used nowhere. --- galvanize-instancer/constants.go | 1 - 1 file changed, 1 deletion(-) 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 ) From 1b989f7ec156bbb4fee0f927176060fa5b12ceed Mon Sep 17 00:00:00 2001 From: CorentinFelten Date: Thu, 1 Oct 2026 19:39:22 -0400 Subject: [PATCH 10/11] fix: reuse one connection pool for the port bindings store openPortBindingDB opened a new gorm connection pool, and ran AutoMigrate, on each of its calls: loading, reserving, saving and clearing bindings, i.e. several times per deploy and terminate. None was ever closed, so each call left a SQLite connection and its file descriptor open: 200 calls left 200 more descriptors open. The store now keeps one pool per database file, opened and migrated on first use, in a map guarded by portBindingDBMu, which every caller already holds. Checked while looking into it: these connections did not lack a busy timeout, as suspected; the glebarez driver sets busy_timeout to 5000 by default. --- CHANGELOG.md | 1 + .../internal/ansible/port_bindings_store.go | 17 +++++++ .../ansible/port_bindings_store_test.go | 50 +++++++++++++++++++ 3 files changed, 68 insertions(+) create mode 100644 galvanize-instancer/internal/ansible/port_bindings_store_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index cda7587..ef733ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ - 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) 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..7fcb228 --- /dev/null +++ b/galvanize-instancer/internal/ansible/port_bindings_store_test.go @@ -0,0 +1,50 @@ +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") +} From a5aeac6db52a237b369ebcd9921c10ebf04ecf7d Mon Sep 17 00:00:00 2001 From: CorentinFelten Date: Thu, 1 Oct 2026 19:50:37 -0400 Subject: [PATCH 11/11] test: cover the startup wiring and error paths of these fixes Coverage of the lines changed by these fixes showed what no test ran: - serve's choice of execution without Redis. It moves to configureQueueless, tested with and without a job queue: without one, team requests and expiries share one LimitedDeployer with max_concurrent_ansible slots (default 5); with one, nothing changes. ExpiryScheduler.DirectTerminationDeployer and LimitedDeployer.Limit expose what the tests check. - The config defaults, including deployment_max_extensions: 3. They move to setConfigDefaults, tested by loading a config that omits them. - A terminate call that gives up waiting for a slot, and a port bindings store that cannot be opened or migrated, which must not be cached. The lines changed by these fixes go from 61% to 74% covered; the rest are the calls in serve and initConfig, which only run at startup. --- galvanize-instancer/cmd/root.go | 13 ++++--- galvanize-instancer/cmd/root_test.go | 33 +++++++++++++++++ galvanize-instancer/cmd/serve.go | 29 ++++++++------- galvanize-instancer/cmd/serve_test.go | 33 +++++++++++++++++ .../internal/ansible/limited_deployer.go | 3 ++ .../internal/ansible/limited_deployer_test.go | 17 ++++++++- .../ansible/port_bindings_store_test.go | 35 +++++++++++++++++++ .../pkg/scheduler/scheduler.go | 9 +++++ 8 files changed, 155 insertions(+), 17 deletions(-) create mode 100644 galvanize-instancer/cmd/root_test.go diff --git a/galvanize-instancer/cmd/root.go b/galvanize-instancer/cmd/root.go index 9072312..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", 3) - 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 bd12175..16b0a71 100755 --- a/galvanize-instancer/cmd/serve.go +++ b/galvanize-instancer/cmd/serve.go @@ -146,8 +146,6 @@ var serveCmd = &cobra.Command{ // 6. Initialize Redis job queue and worker pool (if configured) var jobQueue *worker.Queue var workerPool *worker.Pool - // Runs team requests and expiries without Redis; nil: the default deployer - var teamDeployer ansible.Deployer if cfg.Instancer.Redis.Addr != "" { var queueErr error @@ -178,20 +176,11 @@ var serveCmd = &cobra.Command{ Logger: zap.S().Named("WorkerPool"), }) zap.S().Infof("Redis job queue enabled with %d workers", numWorkers) - } else { - // Team requests and expiries share max_concurrent_ansible slots; - // admin actions are not limited - limit := cfg.Instancer.MaxConcurrentAnsibleLimit() - teamDeployer = ansible.NewLimitedDeployer(&ansible.AnsibleDeployer{}, limit) - 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) } // Initialize scheduler with job queue (can be nil if Redis not configured) expirySched := scheduler.NewExpiryScheduler(db, jobQueue, zap.S().Named("ExpiryScheduler")) - if jobQueue == nil { - // Without Redis, expired deployments are terminated in place - expirySched.WithDirectTermination(challIdx, confProv, teamDeployer) - } + teamDeployer := configureQueueless(cfg, jobQueue, expirySched, challIdx, confProv) // 7. Server Init via DI srv := server.NewServerWithOpts(server.ServerOpts{ @@ -275,6 +264,22 @@ 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 diff --git a/galvanize-instancer/cmd/serve_test.go b/galvanize-instancer/cmd/serve_test.go index aec6b10..9e66cff 100644 --- a/galvanize-instancer/cmd/serve_test.go +++ b/galvanize-instancer/cmd/serve_test.go @@ -5,8 +5,13 @@ import ( "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" ) @@ -48,3 +53,31 @@ 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/internal/ansible/limited_deployer.go b/galvanize-instancer/internal/ansible/limited_deployer.go index 478075d..4be8326 100644 --- a/galvanize-instancer/internal/ansible/limited_deployer.go +++ b/galvanize-instancer/internal/ansible/limited_deployer.go @@ -27,6 +27,9 @@ func NewLimitedDeployer(inner Deployer, limit int) *LimitedDeployer { 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{}{}: diff --git a/galvanize-instancer/internal/ansible/limited_deployer_test.go b/galvanize-instancer/internal/ansible/limited_deployer_test.go index 79a2d22..68e38cb 100644 --- a/galvanize-instancer/internal/ansible/limited_deployer_test.go +++ b/galvanize-instancer/internal/ansible/limited_deployer_test.go @@ -82,8 +82,23 @@ func TestLimitedDeployer_WaitingCallHonorsContext(t *testing.T) { 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, cap(NewLimitedDeployer(&slowDeployer{}, 0).slots)) + assert.Equal(t, 1, NewLimitedDeployer(&slowDeployer{}, 0).Limit()) + assert.Equal(t, 4, NewLimitedDeployer(&slowDeployer{}, 4).Limit()) } type blockingDeployer struct { diff --git a/galvanize-instancer/internal/ansible/port_bindings_store_test.go b/galvanize-instancer/internal/ansible/port_bindings_store_test.go index 7fcb228..ad105ca 100644 --- a/galvanize-instancer/internal/ansible/port_bindings_store_test.go +++ b/galvanize-instancer/internal/ansible/port_bindings_store_test.go @@ -48,3 +48,38 @@ func TestPortBindingsStore_ReusesConnection(t *testing.T) { 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/scheduler/scheduler.go b/galvanize-instancer/pkg/scheduler/scheduler.go index 03f77f8..a48a4af 100644 --- a/galvanize-instancer/pkg/scheduler/scheduler.go +++ b/galvanize-instancer/pkg/scheduler/scheduler.go @@ -56,6 +56,15 @@ func (s *ExpiryScheduler) WithDirectTermination(challIdx challenge.ChallengeInde 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()