From 1a035ee1fd9477c8bbeaec6363c0ae436dd8531c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C4=90=E1=BB=97=20Tr=E1=BB=8Dng=20H=E1=BA=A3i?= <41283691+hainenber@users.noreply.github.com> Date: Thu, 8 Feb 2024 10:29:47 +0700 Subject: [PATCH] fix(comp): prevent divide-by-zero error when calculating array size for sharded targets (#6326) --- CHANGELOG.md | 2 ++ component/discovery/discovery.go | 10 ++++++++-- component/loki/source/podlogs/reconciler.go | 10 ++++++++-- 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1805a76bca0a..78b628221fb7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -73,6 +73,8 @@ Main (unreleased) - Fix an issue with static integrations-next marshaling where non singletons would cause `/-/config` to fail to marshal. (@erikbaranowski) +- Fix divide-by-zero issue when sharding targets. (@hainenber) + ### Other changes - Removed support for Windows 2012 in line with Microsoft end of life. (@mattdurham) diff --git a/component/discovery/discovery.go b/component/discovery/discovery.go index cacd9559070d..ebeca72ecd5a 100644 --- a/component/discovery/discovery.go +++ b/component/discovery/discovery.go @@ -43,7 +43,13 @@ func (t *DistributedTargets) Get() []Target { return t.targets } - res := make([]Target, 0, (len(t.targets)+1)/len(t.cluster.Peers())) + peerCount := len(t.cluster.Peers()) + resCap := (len(t.targets) + 1) + if peerCount != 0 { + resCap = (len(t.targets) + 1) / peerCount + } + + res := make([]Target, 0, resCap) for _, tgt := range t.targets { peers, err := t.cluster.Lookup(shard.StringKey(tgt.NonMetaLabels().String()), 1, shard.OpReadWrite) @@ -53,7 +59,7 @@ func (t *DistributedTargets) Get() []Target { // back to owning the target ourselves. res = append(res, tgt) } - if peers[0].Self { + if len(peers) == 0 || peers[0].Self { res = append(res, tgt) } } diff --git a/component/loki/source/podlogs/reconciler.go b/component/loki/source/podlogs/reconciler.go index 4d2ec87495f2..66baba5e86f7 100644 --- a/component/loki/source/podlogs/reconciler.go +++ b/component/loki/source/podlogs/reconciler.go @@ -131,7 +131,13 @@ func distributeTargets(c cluster.Cluster, targets []*kubetail.Target) []*kubetai return targets } - res := make([]*kubetail.Target, 0, (len(targets)+1)/len(c.Peers())) + peerCount := len(c.Peers()) + resCap := len(targets) + 1 + if peerCount != 0 { + resCap = (len(targets) + 1) / peerCount + } + + res := make([]*kubetail.Target, 0, resCap) for _, target := range targets { peers, err := c.Lookup(shard.StringKey(target.Labels().String()), 1, shard.OpReadWrite) @@ -141,7 +147,7 @@ func distributeTargets(c cluster.Cluster, targets []*kubetail.Target) []*kubetai // back to owning the target ourselves. res = append(res, target) } - if peers[0].Self { + if len(peers) == 0 || peers[0].Self { res = append(res, target) } }