Skip to content
Merged
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
2 changes: 0 additions & 2 deletions cmd/statshouse-agg/statshouse-agg.go
Original file line number Diff line number Diff line change
Expand Up @@ -268,8 +268,6 @@ func parseCommandLine() error {
flag.StringVar(&argv.Cluster, "cluster", aggregator.DefaultConfigAggregator().Cluster, "clickhouse cluster name to autodetect configuration, local shard and replica")
flag.StringVar(&argv.customHostName, "hostname", "", "override auto detected hostname")
flag.IntVar(&argv.RecentInserters, "recent-inserters", aggregator.DefaultConfigAggregator().RecentInserters, "How many parallel inserts to make for recent data")
flag.IntVar(&argv.HistoricInserters, "historic-inserters", aggregator.DefaultConfigAggregator().HistoricInserters, "How many parallel inserts to make for historic data")
flag.IntVar(&argv.InsertHistoricWhen, "insert-historic-when", aggregator.DefaultConfigAggregator().InsertHistoricWhen, "Aggregator will insert historic data when # of ongoing recent data inserts is this number or less")
var cardinalityWindow int
flag.IntVar(&cardinalityWindow, "cardinality-window", 0, "Depecated, not used.") // TODO - remove
var maxCardinality int
Expand Down
6 changes: 3 additions & 3 deletions internal/aggregator/aggregator.go
Original file line number Diff line number Diff line change
Expand Up @@ -738,8 +738,8 @@ func (a *Aggregator) goInsert(insertsSema *semaphore.Weighted, cancelCtx context
a.mu.Lock()
oldestTime := a.recentBuckets[0].time
newestTime := a.recentBuckets[len(a.recentBuckets)-1].time
willInsertHistoric := (a.recentSenders+a.historicSenders) < a.config.InsertHistoricWhen &&
a.historicSenders < a.config.HistoricInserters &&
willInsertHistoric := (a.recentSenders+a.historicSenders) < configR.InsertHistoricWhen &&
a.historicSenders < configR.HistoricInserters &&
len(a.historicBuckets) != 0
if willInsertHistoric {
a.historicSenders++
Expand All @@ -758,7 +758,7 @@ func (a *Aggregator) goInsert(insertsSema *semaphore.Weighted, cancelCtx context

recentContributors := aggBucket.contributorsCount()
historicContributors := 0.0
maxHistoricInsertBatch := data_model.MaxHistorySendStreams / (1 + a.config.HistoricInserters)
maxHistoricInsertBatch := data_model.MaxHistorySendStreams / (1 + configR.HistoricInserters)
// each historic inserter takes not more than maxHistoricInsertBatch the oldest buckets, so for example with 2 inserters
// [a, b, c, d, e, f] <- this is 6 seconds sent by agent and waiting in historicBuckets to be inserted
// [c, d, e, f] <- first inserter takes [a, b] and starts inserting
Expand Down
30 changes: 16 additions & 14 deletions internal/aggregator/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ type ConfigAggregatorRemote struct {
ShortWindow int
InsertBudget int // for single replica, in bytes per contributor, when many contributors
MinInsertBudget int64
HistoricInserters int
InsertHistoricWhen int
ShardInsertBudget map[int]int // pre shard overrides, if not set buget is equal to InsertBudget
ReceiveSampleBudget int // total pre-aggregator receive budget per shard, in bytes per second
StringTopCountInsert int
Expand All @@ -55,9 +57,7 @@ type ConfigAggregatorRemote struct {
}

type ConfigAggregator struct {
RecentInserters int
HistoricInserters int
InsertHistoricWhen int
RecentInserters int

KHAddr string
KHUser string
Expand Down Expand Up @@ -89,8 +89,6 @@ type ConfigAggregator struct {
func DefaultConfigAggregator() ConfigAggregator {
return ConfigAggregator{
RecentInserters: 4,
HistoricInserters: 1,
InsertHistoricWhen: 2,
SimulateRandomErrors: 0,
Cluster: "statlogs2",
MetadataNet: "tcp4",
Expand All @@ -102,6 +100,8 @@ func DefaultConfigAggregator() ConfigAggregator {
ShortWindow: data_model.MaxShortWindow,
InsertBudget: 400,
MinInsertBudget: data_model.InsertBudgetFixed,
HistoricInserters: 1,
InsertHistoricWhen: 2,
ReceiveSampleBudget: 500000,
StringTopCountInsert: 20,
SampleNamespaces: true,
Expand Down Expand Up @@ -186,6 +186,8 @@ func (c *ConfigAggregatorRemote) Bind(f *flag.FlagSet, d ConfigAggregatorRemote,
f.IntVar(&c.ShortWindow, "short-window", d.ShortWindow, "Short admission window. Shorter window reduces latency, but also reduces recent stats quality as more agents come too late")
f.IntVar(&c.InsertBudget, "insert-budget", d.InsertBudget, "Aggregator will sample data before inserting into clickhouse. Bytes per contributor when # >> 100.")
f.Int64Var(&c.MinInsertBudget, "min-insert-budget", d.MinInsertBudget, "Should put average insert budget here. If CH freezes, we lose contributors, budget falls, so sample factor extremely rises.")
f.IntVar(&c.HistoricInserters, "historic-inserters", d.HistoricInserters, "How many parallel inserts to make for historic data")
f.IntVar(&c.InsertHistoricWhen, "insert-historic-when", d.InsertHistoricWhen, "Aggregator will insert historic data when # of ongoing recent data inserts is this number or less")
f.IntVar(&c.ReceiveSampleBudget, "receive-sample-budget", d.ReceiveSampleBudget, "Total per-shard pre-aggregator receive budget, in bytes per second, to be divided between active contributors.")
f.Func("shard-insert-budget", "1:200 override budget for 1 shard with 200, shards start with 1", c.setShardBudget)
f.IntVar(&c.StringTopCountInsert, "string-top-insert", d.StringTopCountInsert, "How many different strings per key is inserted by aggregator in string tops.")
Expand Down Expand Up @@ -216,18 +218,9 @@ func (c *ConfigAggregatorRemote) Bind(f *flag.FlagSet, d ConfigAggregatorRemote,
}

func ValidateConfigAggregator(c *ConfigAggregator) error {
if c.InsertHistoricWhen < 1 {
return fmt.Errorf("--insert-historic-when (%d) must be >= 1", c.InsertHistoricWhen)
}
if c.RecentInserters < 1 {
return fmt.Errorf("--recent-inserters (%d) must be >= 1", c.RecentInserters)
}
if c.HistoricInserters < 1 {
return fmt.Errorf("--historic-inserters (%d) must be >= 1", c.HistoricInserters)
}
if c.HistoricInserters > 4 { // Otherwise batching during historic inserts will become too small
return fmt.Errorf("--historic-inserters (%d) must be <= 4", c.HistoricInserters)
}

return c.RemoteInitial.Validate()
}
Expand Down Expand Up @@ -267,6 +260,15 @@ func (c *ConfigAggregatorRemote) Validate() error {
if c.InsertBudget < 1 {
return fmt.Errorf("insert-budget (%d) must be >= 1", c.InsertBudget)
}
if c.InsertHistoricWhen < 1 {
return fmt.Errorf("--insert-historic-when (%d) must be >= 1", c.InsertHistoricWhen)
}
if c.HistoricInserters < 1 {
return fmt.Errorf("--historic-inserters (%d) must be >= 1", c.HistoricInserters)
}
if c.HistoricInserters > 4 { // Otherwise batching during historic inserts will become too small
return fmt.Errorf("--historic-inserters (%d) must be <= 4", c.HistoricInserters)
}
if c.ReceiveSampleBudget < 1 {
return fmt.Errorf("receive-sample-budget (%d) must be >= 1", c.ReceiveSampleBudget)
}
Expand Down
3 changes: 3 additions & 0 deletions internal/api/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ type Config struct {
CHMaxShardConnsRatio int
ReplicaThrottleCfgStr string
ReplicaThrottleCfg *chutil.ReplicaThrottleConfig
LatencySlackCH int
HardwareMetricResolution int
HardwareSlowMetricResolution int
Announcement string // if !empty, show to user in UI
Expand Down Expand Up @@ -133,6 +134,7 @@ func (argv *Config) Bind(f *flag.FlagSet, defaultI config.Config) {
f.StringVar(&argv.AvailableShardsStr, "available-shards", default_.AvailableShardsStr, "comma-separated list of default shards for metrics when namespace doesn't specify shards")
f.IntVar(&argv.CHMaxShardConnsRatio, "clickhouse-max-shard-conns-ratio", default_.CHMaxShardConnsRatio, "maximum number of ClickHouse connections per shard (%)")
f.StringVar(&argv.ReplicaThrottleCfgStr, "replica-throttle-config", "", "JSON config for replica throttling testing (feature flag)")
f.IntVar(&argv.LatencySlackCH, "latency-slack-ch", default_.LatencySlackCH, "percent of avg ClickHouse query duration used as slack (110 = 10% upside)")
f.IntVar(&argv.HardwareMetricResolution, "hardware-metric-resolution", default_.HardwareMetricResolution, "Statshouse hardware metric resolution")
f.IntVar(&argv.HardwareSlowMetricResolution, "hardware-slow-metric-resolution", default_.HardwareSlowMetricResolution, "Statshouse slow hardware metric resolution")

Expand Down Expand Up @@ -160,6 +162,7 @@ func DefaultConfig() *Config {
CacheChunkSize: 5,
AvailableShardsStr: "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16",
CHMaxShardConnsRatio: 20,
LatencySlackCH: chutil.DefaultLatencySlackCH,
RateLimitConfig: chutil.RateLimitConfig{
WindowDuration: 2 * time.Minute,
MaxErrorRate: 20,
Expand Down
2 changes: 1 addition & 1 deletion internal/api/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -642,7 +642,7 @@ func NewHandler(staticDir fs.FS, jsSettings JSSettings, showInvisible bool, chV2
})
h.hardwareMetricRes.Store(int64(cfg.HardwareMetricResolution))
h.hardwareSlowMetricRes.Store(int64(cfg.HardwareSlowMetricResolution))
_ = chV2.SetLimits(cfg.UserLimits, cfg.CHMaxShardConnsRatio, cfg.RateLimitConfig, cfg.ReplicaThrottleCfg)
_ = chV2.SetLimits(cfg.UserLimits, cfg.CHMaxShardConnsRatio, cfg.RateLimitConfig, cfg.ReplicaThrottleCfg, cfg.LatencySlackCH)
h.ConfigMu.Lock()
defer h.ConfigMu.Unlock()
h.DisableCHAddr = cfg.DisableCHAddr
Expand Down
67 changes: 37 additions & 30 deletions internal/chutil/chutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,13 @@ import (
)

type connPool struct {
poolName string
rnd *rand.Rand
maxActiveQuery int
maxShardActiveQuery int
servers []serverCH
sem *queue.Queue
shardSems []*queue.Queue // shard_id -> semaphore
poolName string
rnd *rand.Rand
maxActiveQuery int
maxShardActiveQuery int
servers []serverCH
sem *queue.Queue
shardSems []*queue.Queue // shard_id -> semaphore
avgQueryDurationNS atomic.Int64 // exponentially smoothed average in nanoseconds
shardAvgQueryNS []atomic.Int64 // avgQueryDurationNS per-shard
lastPoolQueryTimeNS atomic.Int64
Expand All @@ -51,13 +51,16 @@ type serverCH struct {
}

type ClickHouse struct {
opt ChConnOptions
mx sync.RWMutex
namedPools map[string][6]*connPool
rateLimits []*RateLimit
trotCfg *ReplicaThrottleConfig
opt ChConnOptions
mx sync.RWMutex
namedPools map[string][6]*connPool
rateLimits []*RateLimit
trotCfg *ReplicaThrottleConfig
latencySlackCH int
}

const DefaultLatencySlackCH = 90

type QueryMetaInto struct {
IsFast bool
IsLight bool
Expand Down Expand Up @@ -164,13 +167,17 @@ func OpenClickHouse(opt ChConnOptions) (*ClickHouse, error) {
result.rateLimits = append(result.rateLimits, NewRateLimit(opt.RateLimitConfig, i/3+1, i%3+1))
result.rateLimits[i].Start()
}
err := result.SetLimits(nil, opt.MaxShardConnsRatio, opt.RateLimitConfig, nil)
err := result.SetLimits(nil, opt.MaxShardConnsRatio, opt.RateLimitConfig, nil, DefaultLatencySlackCH)
return result, err
}

func (ch1 *ClickHouse) SetLimits(limits []ConnLimits, maxShardConnsRatio int, rtCfg RateLimitConfig, trotCfg *ReplicaThrottleConfig) error {
func (ch1 *ClickHouse) SetLimits(limits []ConnLimits, maxShardConnsRatio int, rtCfg RateLimitConfig, trotCfg *ReplicaThrottleConfig, latencySlackCH int) error {
ch1.mx.Lock()
defer ch1.mx.Unlock()
if latencySlackCH < 1 {
latencySlackCH = DefaultLatencySlackCH
}
ch1.latencySlackCH = latencySlackCH
ch1.trotCfg = trotCfg
ch1.namedPools = map[string][6]*connPool{}
limits = append(limits, ch1.opt.ConnLimits) // to avoid overriding default limits
Expand Down Expand Up @@ -375,26 +382,24 @@ func QueryKind(isFast, isLight, isHardware bool) int {
return slowHeavy
}
func (ch1 *ClickHouse) Select(ctx context.Context, meta QueryMetaInto, query chgo.Query) (info QueryHandleInfo, err error) {
pool, trotCfg := ch1.resolvePoolBy(meta)
return pool.selectCH(ctx, ch1, meta, query, trotCfg)
pool, trotCfg, latencySlackCH := ch1.resolvePoolBy(meta)
return pool.selectCH(ctx, ch1, meta, query, trotCfg, latencySlackCH)
}

func (ch1 *ClickHouse) resolvePoolBy(meta QueryMetaInto) (*connPool, *ReplicaThrottleConfig) {
func (ch1 *ClickHouse) resolvePoolBy(meta QueryMetaInto) (*connPool, *ReplicaThrottleConfig, int) {
ch1.mx.RLock()
defer ch1.mx.RUnlock()
kind := QueryKind(meta.IsFast, meta.IsLight, meta.IsHardware)
if pool, ok := ch1.namedPools[meta.User]; ok {
pool := pool[kind]
if pool.maxActiveQuery > 0 {
return pool, ch1.trotCfg
return pool, ch1.trotCfg, ch1.latencySlackCH
}
return ch1.namedPools[defaultUserName][kind], ch1.trotCfg
return ch1.namedPools[defaultUserName][kind], ch1.trotCfg, ch1.latencySlackCH
}
return ch1.namedPools[defaultUserName][kind], ch1.trotCfg
return ch1.namedPools[defaultUserName][kind], ch1.trotCfg, ch1.latencySlackCH
}

const latencySlackCH = 130 // 30% upside

const avgDecayGracePeriodNS int64 = int64(60 * time.Second)
const avgDecayHalfLifeNS int64 = int64(60 * time.Second)

Expand All @@ -415,7 +420,7 @@ func decayAvgNS(avgNS int64, elapsed time.Duration) int64 {
return int64(result)
}

func (pool *connPool) selectCH(ctx context.Context, ch *ClickHouse, meta QueryMetaInto, query chgo.Query, trotCfg *ReplicaThrottleConfig) (info QueryHandleInfo, err error) {
func (pool *connPool) selectCH(ctx context.Context, ch *ClickHouse, meta QueryMetaInto, query chgo.Query, trotCfg *ReplicaThrottleConfig, latencySlackCH int) (info QueryHandleInfo, err error) {
query.OnProfile = func(_ context.Context, p proto.Profile) error {
info.Profile = p
return nil
Expand Down Expand Up @@ -487,7 +492,7 @@ func (pool *connPool) selectCH(ctx context.Context, ch *ClickHouse, meta QueryMe
if deadline, ok := ctx.Deadline(); ok {
remaining := time.Until(deadline)
if avg := pool.getAvgQueryDuration(shard); avg > 0 {
if remaining < avg*latencySlackCH/100 {
if remaining < avg*time.Duration(latencySlackCH)/100 {
sem.Release()
info.ErrorCode = format.TagValueIDAPIResponseExceptionSemTooLate
return info, context.DeadlineExceeded
Expand All @@ -507,7 +512,9 @@ func (pool *connPool) selectCH(ctx context.Context, ch *ClickHouse, meta QueryMe
sem.Release()

info.QueryDuration = duration
pool.recordQueryDuration(duration, shard)
if err == nil {
pool.recordQueryDuration(duration, shard)
}
if queryCtx.Err() != nil {
statshouse.Value(format.BuiltinMetricMetaAPISelectDuration.Name, statshouse.Tags{
1: modeStr(meta.IsFast, meta.IsLight, meta.IsHardware),
Expand Down Expand Up @@ -561,7 +568,7 @@ func (pool *connPool) selectCH(ctx context.Context, ch *ClickHouse, meta QueryMe
if err != nil {
return info, err
}
pickCheckServer(servers, query, pool.rnd, info.QueryDuration*latencySlackCH/100, trotCfg)
pickCheckServer(servers, query, pool.rnd, info.QueryDuration*130/100, trotCfg)
return info, nil
}

Expand Down Expand Up @@ -672,10 +679,10 @@ func applyDecay(avgNS int64, lastQueryTimeNS int64) time.Duration {
func (pool *connPool) getAvgQueryDuration(shard int) time.Duration {
if shard >= 0 && shard < len(pool.shardAvgQueryNS) {
// TOCTOU: avg and timestamp are read separately; acceptable for this heuristic.
// Timestamps are updated only on query completion, so long-running in-flight
// queries may appear as idle time causing decay; this is an acceptable trade-off
// because the 60s grace period covers most queries and rejected/failed queries
// should not keep the average fresh.
// Timestamps are updated only on successful completion, so long-running
// in-flight queries may appear as idle time causing decay; this is an
// acceptable trade-off because the 60s grace period covers most queries
// and rejected/failed queries should not keep the average fresh.
return applyDecay(pool.shardAvgQueryNS[shard].Load(), pool.lastShardQueryTimeNS[shard].Load())
}
return applyDecay(pool.avgQueryDurationNS.Load(), pool.lastPoolQueryTimeNS.Load())
Expand Down
Loading