Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
1 change: 1 addition & 0 deletions pkg/apiserver/apiserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@ func NewServer(ctx context.Context, config *csconfig.LocalApiServerCfg, accessLo
ConsoleConfig: config.ConsoleConfig,
DisableRemoteLapiRegistration: config.DisableRemoteLapiRegistration,
AutoRegisterCfg: config.AutoRegister,
DecisionsStreamPageSize: config.DecisionsStreamPageSize,
}

var (
Expand Down
3 changes: 3 additions & 0 deletions pkg/apiserver/controllers/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ type Controller struct {
HandlerV1 *v1.Controller
AutoRegisterCfg *csconfig.LocalAPIAutoRegisterCfg
DisableRemoteLapiRegistration bool
DecisionsStreamPageSize int
}

func (c *Controller) Init() error {
Expand Down Expand Up @@ -89,6 +90,8 @@ func (c *Controller) NewV1() error {
ConsoleConfig: *c.ConsoleConfig,
TrustedIPs: c.TrustedIPs,
AutoRegisterCfg: c.AutoRegisterCfg,

DecisionsStreamPageSize: c.DecisionsStreamPageSize,
}

c.HandlerV1, err = v1.New(&v1Config)
Expand Down
19 changes: 19 additions & 0 deletions pkg/apiserver/controllers/v1/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"fmt"
"net"

log "github.com/sirupsen/logrus"

middlewares "github.com/crowdsecurity/crowdsec/pkg/apiserver/middlewares/v1"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/csprofiles"
Expand All @@ -24,6 +26,8 @@ type Controller struct {
ConsoleConfig csconfig.ConsoleConfig
TrustedIPs []net.IPNet
AutoRegisterCfg *csconfig.LocalAPIAutoRegisterCfg

DecisionsStreamPageSize int
}

type ControllerV1Config struct {
Expand All @@ -37,6 +41,8 @@ type ControllerV1Config struct {
ConsoleConfig csconfig.ConsoleConfig
TrustedIPs []net.IPNet
AutoRegisterCfg *csconfig.LocalAPIAutoRegisterCfg

DecisionsStreamPageSize int
}

func New(cfg *ControllerV1Config) (*Controller, error) {
Expand All @@ -47,6 +53,17 @@ func New(cfg *ControllerV1Config) (*Controller, error) {
return &Controller{}, fmt.Errorf("failed to compile profiles: %w", err)
}

pageSize := cfg.DecisionsStreamPageSize
if pageSize < 0 {
log.Warningf("decisions_stream_page_size cannot be negative (%d), using the default value of %d", pageSize, defaultDecisionsStreamPageSize)
}

// ent drops LIMIT for 0 and SQLite ignores a negative one: a page would be the whole table,
// and the paging loop would never end.
if pageSize <= 0 {
Comment thread
tommy-ng0 marked this conversation as resolved.
Resolved
pageSize = defaultDecisionsStreamPageSize
}

v1 := &Controller{
DBClient: cfg.DbClient,
APIKeyHeader: middlewares.APIKeyHeader,
Expand All @@ -57,6 +74,8 @@ func New(cfg *ControllerV1Config) (*Controller, error) {
ConsoleConfig: cfg.ConsoleConfig,
TrustedIPs: cfg.TrustedIPs,
AutoRegisterCfg: cfg.AutoRegisterCfg,

DecisionsStreamPageSize: pageSize,
}

v1.Middlewares, err = middlewares.NewMiddlewares(cfg.DbClient)
Expand Down
10 changes: 6 additions & 4 deletions pkg/apiserver/controllers/v1/decisions.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ import (
"github.com/crowdsecurity/crowdsec/pkg/models"
)

// Each page is held in memory while it is written out, once per in-flight stream request.
const defaultDecisionsStreamPageSize = 30000

// Format decisions for the bouncers
func FormatDecisions(decisions []*ent.Decision) []*models.Decision {
var results []*models.Decision
Expand Down Expand Up @@ -158,8 +161,7 @@ func (c *Controller) DeleteDecisions(gctx *gin.Context) {
// writeDecisions streams the decisions returned by query into the array the caller has already
// opened, paginating by id from startID. A startup resync passes 0, a stream delta passes the
// bouncer cursor: both are the same query, they only differ in where they start.
func writeDecisions(gctx *gin.Context, now time.Time, filters map[string][]string, startID int, query func(context.Context, time.Time, map[string][]string) ([]*ent.Decision, error)) error {
limit := 30000 // FIXME : make it configurable
func writeDecisions(gctx *gin.Context, now time.Time, filters map[string][]string, startID int, limit int, query func(context.Context, time.Time, map[string][]string) ([]*ent.Decision, error)) error {
needComma := false
lastId := startID

Expand Down Expand Up @@ -233,7 +235,7 @@ func (c *Controller) streamDecisions(gctx *gin.Context, bouncerInfo *ent.Bouncer
gctx.Writer.WriteString(`{"new": [`) // No need to check for errors, the doc says it always returns nil

// Active decisions. A startup resync is this same query with a zero cursor.
if err := writeDecisions(gctx, now, filters, cursor, c.DBClient.QueryAllDecisionsWithFilters); err != nil {
if err := writeDecisions(gctx, now, filters, cursor, c.DecisionsStreamPageSize, c.DBClient.QueryAllDecisionsWithFilters); err != nil {
log.Errorf("failed sending new decisions: %v", err)
gctx.Writer.WriteString(`], "deleted": []}`)
gctx.Writer.Flush()
Expand All @@ -260,7 +262,7 @@ func (c *Controller) streamDecisions(gctx *gin.Context, bouncerInfo *ent.Bouncer
}
}

if err := writeDecisions(gctx, now, filters, 0, expired); err != nil {
if err := writeDecisions(gctx, now, filters, 0, c.DecisionsStreamPageSize, expired); err != nil {
log.Errorf("failed sending expired decisions: %v", err)
gctx.Writer.WriteString(`]}`)
gctx.Writer.Flush()
Expand Down
79 changes: 79 additions & 0 deletions pkg/apiserver/decisions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ import (
"testing"
"time"

logtest "github.com/sirupsen/logrus/hooks/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/crowdsecurity/crowdsec/pkg/csnet"
"github.com/crowdsecurity/crowdsec/pkg/models"
"github.com/crowdsecurity/crowdsec/pkg/types"
)

Expand Down Expand Up @@ -493,6 +495,83 @@ func TestStreamDecisionDeltaFilters(t *testing.T) {
}
}

// Small pages force the stream across several id_gt boundaries, for active and expired
// decisions, on startup and on a delta.
func TestStreamDecisionPageSize(t *testing.T) {
tests := []struct {
name string
pageSize int
want int
}{
{"default", 0, 30000},
{"negative falls back to default", -1, 30000},
{"one per page", 1, 1},
{"partial last page", 2, 2},
{"exact multiple", 5, 5},
}

values := func(ds []*models.Decision) []string {
out := make([]string, 0, len(ds))
for _, d := range ds {
out = append(out, *d.Value)
}

return out
}

for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
ctx := t.Context()

config := LoadTestConfig(t)
config.API.Server.DecisionsStreamPageSize = tc.pageSize

logger, _ := logtest.NewNullLogger()
apiServer, err := NewServer(ctx, config.API.Server, logger.WithFields(nil))
require.NoError(t, err)
require.NoError(t, apiServer.InitController())
require.Equal(t, tc.want, apiServer.controller.HandlerV1.DecisionsStreamPageSize)

router, err := apiServer.Router()
require.NoError(t, err)

apiKey, dbClient := CreateTestBouncer(t, ctx, config.API.Server.DbConfig)
lapi := LAPI{router: router, bouncerKey: apiKey, DBClient: dbClient}

for _, v := range []string{"1.0.0.1", "1.0.0.2", "1.0.0.3", "1.0.0.4", "1.0.0.5"} {
seedOne(t, ctx, lapi, v, "lists", "test/page", types.Ip, "ban")
}

for _, v := range []string{"2.0.0.1", "2.0.0.2", "2.0.0.3"} {
_, err = dbClient.Ent.Decision.Create().
SetUntil(time.Now().UTC().Add(-time.Second)).
SetScenario("test/page").
SetType("ban").
SetScope(types.Ip).
SetValue(v).
SetOrigin("lists").
Save(ctx)
require.NoError(t, err)
}

w := lapi.RecordResponse(t, ctx, "GET", "/v1/decisions/stream?startup=true", emptyBody, APIKEY)
decisions, code := readDecisionsStreamResp(t, w)
require.Equal(t, 200, code)
require.Equal(t, []string{"1.0.0.1", "1.0.0.2", "1.0.0.3", "1.0.0.4", "1.0.0.5"}, values(decisions["new"]))
require.Equal(t, []string{"2.0.0.1", "2.0.0.2", "2.0.0.3"}, values(decisions["deleted"]))

for _, v := range []string{"3.0.0.1", "3.0.0.2", "3.0.0.3"} {
seedOne(t, ctx, lapi, v, "lists", "test/page", types.Ip, "ban")
}

w = lapi.RecordResponse(t, ctx, "GET", "/v1/decisions/stream", emptyBody, APIKEY)
decisions, code = readDecisionsStreamResp(t, w)
require.Equal(t, 200, code)
require.Equal(t, []string{"3.0.0.1", "3.0.0.2", "3.0.0.3"}, values(decisions["new"]))
})
}
}

func seedOne(t *testing.T, ctx context.Context, lapi LAPI, value, origin, scenario, scope, dtype string) {
t.Helper()

Expand Down
1 change: 1 addition & 0 deletions pkg/csconfig/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,7 @@ type LocalApiServerCfg struct {
CapiWhitelists *CapiWhitelist `yaml:"-"`
AutoRegister *LocalAPIAutoRegisterCfg `yaml:"auto_registration,omitempty"`
DisableUsageMetricsExport bool `yaml:"disable_usage_metrics_export"`
DecisionsStreamPageSize int `yaml:"decisions_stream_page_size,omitempty"`
Comment thread
tommy-ng0 marked this conversation as resolved.
Resolved
}

// NewAccessLogger builds and returns a logger configured for HTTP access
Expand Down
Loading