Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 0 additions & 1 deletion data/playbooks/tcp.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
compose_definition:
services:
tcp: "{{ _tcp_service }}"
networks: "{{ {traefik_network: {'external': true}} }}"
tags:
- create
- delete
Expand Down
3 changes: 2 additions & 1 deletion galvanize-instancer/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
# The config is expected at data/config.yaml, as mounted by docker-compose.yml
CMD ["./galvanize", "serve", "--port", "8080", "--config", "data/config.yaml"]
2 changes: 1 addition & 1 deletion galvanize-instancer/api/openapi.yaml.in
Original file line number Diff line number Diff line change
Expand Up @@ -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':
Expand Down
13 changes: 9 additions & 4 deletions galvanize-instancer/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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()
Expand Down
33 changes: 33 additions & 0 deletions galvanize-instancer/cmd/root_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
68 changes: 49 additions & 19 deletions galvanize-instancer/cmd/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -192,19 +176,19 @@ 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{
DB: db,
ChallengeIndexer: challIdx,
ConfigProvider: confProv,
Deployer: &ansible.AnsibleDeployer{},
TeamDeployer: teamDeployer,
ExpiryScheduler: expirySched,
JobQueue: jobQueue,
})
Expand Down Expand Up @@ -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
Expand Down
83 changes: 83 additions & 0 deletions galvanize-instancer/cmd/serve_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
1 change: 0 additions & 1 deletion galvanize-instancer/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,4 @@ package main

const (
Version = "0.7.2"
test = 123
)
58 changes: 58 additions & 0 deletions galvanize-instancer/internal/ansible/limited_deployer.go
Original file line number Diff line number Diff line change
@@ -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)
}
Loading
Loading