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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
* [ENHANCEMENT] Upgrade promql-engine to latest. #7841
* [ENHANCEMENT] Ruler: Add new limit `-ruler.list-rules-max-rules` on the total number of rules returned by the Prometheus ListRules API. Responses exceeding the limit are truncated on a rule group boundary and return a `groupNextToken` for retrieving the remaining groups. A rule group is never split, so a single group larger than the limit is still returned whole. Defaults to 0, which is unlimited. #7785
* [ENHANCEMENT] Compactor: Add the `cortex_compactor_oldest_level_1_block_offset_seconds` metric, reporting per tenant how long ago the oldest level 1 block still listed in the bucket index was uploaded. Blocks marked for deletion or for no compaction are excluded. The bucket index entry now carries the block's compaction level; an entry written before this reports an unknown level and is skipped. #7959
* [ENHANCEMENT] Ingester: Renewing tokens via `/ingester/renewTokens` no longer makes queries using shuffle sharding with lookback miss data, so tokens can be renewed in more than one zone at a time. For the lookback period after a renewal, the renewed ingester is treated as newly registered, so subrings reaching its new tokens keep including the previous owners, and it is included in every tenant's subring, since it may still hold data of tenants whose subring it left. #7983
* [BUGFIX] Update prometheus alertmanager version to v0.34.1 to apply upstream inhibit rule bug fixes. #7877
* [BUGFIX] Tenant Federation: Fix regex tenant federation not working in single binary mode, and failing with `multiple org IDs present` when a matched tenant ID contains regex metacharacters and also matches other tenants as a regex. #7869
* [BUGFIX] Query Frontend: Fix the data selection time window computed for an instant query sent without a `time` parameter. The default evaluation time was passed to `util.ParseTimeParam` in milliseconds, but that helper formats the default and parses it as seconds, so the value overflowed `UnixNano()` and wrapped to a timestamp decades away from `now`. This made the `data_select_min_time` and `data_select_max_time` query stats wrong, and stopped the `time_window` query attribute of query priority and query rejection from matching such queries correctly. #7880
Expand Down
10 changes: 10 additions & 0 deletions pkg/ring/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ const pageContent = `
<th>State</th>
<th>Address</th>
<th>Registered At</th>
<th>Renewed At</th>
<th>Last Heartbeat</th>
<th>Tokens</th>
<th>Ownership</th>
Expand All @@ -54,6 +55,7 @@ const pageContent = `
<td>{{ .State }}</td>
<td>{{ .Address }}</td>
<td>{{ .RegisteredTimestamp }}</td>
<td>{{ .RenewedTimestamp }}</td>
<td>{{ .HeartbeatTimestamp }}</td>
<td>{{ .NumTokens }}</td>
<td>{{ .Ownership }}%</td>
Expand Down Expand Up @@ -112,6 +114,7 @@ type ingesterDesc struct {
Address string `json:"address"`
HeartbeatTimestamp string `json:"timestamp"`
RegisteredTimestamp string `json:"registered_timestamp"`
RenewedTimestamp string `json:"renewed_timestamp"`
Zone string `json:"zone"`
Tokens []uint32 `json:"tokens"`
NumTokens int `json:"-"`
Expand Down Expand Up @@ -173,6 +176,12 @@ func (r *Ring) ServeHTTP(w http.ResponseWriter, req *http.Request) {
registeredTimestamp = ing.GetRegisteredAt().String()
}

// Format the renewed timestamp.
renewedTimestamp := ""
if ing.RenewedTimestamp != 0 {
renewedTimestamp = ing.GetRenewedAt().String()
}

var ownership float64
var deltaOwnership float64

Expand All @@ -192,6 +201,7 @@ func (r *Ring) ServeHTTP(w http.ResponseWriter, req *http.Request) {
Address: ing.Addr,
HeartbeatTimestamp: heartbeatTimestamp.String(),
RegisteredTimestamp: registeredTimestamp,
RenewedTimestamp: renewedTimestamp,
Tokens: ing.Tokens,
Zone: ing.Zone,
NumTokens: len(ing.Tokens),
Expand Down
52 changes: 52 additions & 0 deletions pkg/ring/http_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package ring

import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestRing_ServeHTTP_RenewedTimestamp(t *testing.T) {
cfg := Config{HeartbeatTimeout: time.Hour, ReplicationFactor: 1}
r, err := NewWithStoreClientAndStrategy(cfg, testRingName, testRingKey, &MockClient{}, NewDefaultReplicationStrategy(), prometheus.NewRegistry(), log.NewNopLogger())
require.NoError(t, err)

renewedAt := time.Unix(1700000000, 0)
r.updateRingState(&Desc{Ingesters: map[string]InstanceDesc{
"renewed": {Addr: "addr-1", Timestamp: time.Now().Unix(), Tokens: []uint32{1}, RenewedTimestamp: renewedAt.Unix()},
"not-renewed": {Addr: "addr-2", Timestamp: time.Now().Unix(), Tokens: []uint32{2}},
}})

req := httptest.NewRequest(http.MethodGet, "/ring", nil)
req.Header.Set("Accept", "application/json")
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)

var resp struct {
Shards []struct {
ID string `json:"id"`
RenewedTimestamp string `json:"renewed_timestamp"`
} `json:"shards"`
}
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))
renewed := map[string]string{}
for _, s := range resp.Shards {
renewed[s.ID] = s.RenewedTimestamp
}
assert.Equal(t, map[string]string{"renewed": renewedAt.String(), "not-renewed": ""}, renewed)

rec = httptest.NewRecorder()
r.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/ring", nil))
require.Equal(t, http.StatusOK, rec.Code)
assert.Contains(t, rec.Body.String(), "<th>Renewed At</th>")
// The template escapes "+" in the zone offset, so match the date and time only.
assert.Contains(t, rec.Body.String(), "<td>"+renewedAt.Format("2006-01-02 15:04:05"))
}
73 changes: 65 additions & 8 deletions pkg/ring/lifecycler.go
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,47 @@ func (i *Lifecycler) setRegisteredAt(registeredAt time.Time) {
i.registeredAt = registeredAt
}

// getRenewedAt returns when the instance last renewed its tokens, zero if never. It's kept
// in the tokens file, so it survives a restart that removes the instance from the ring.
func (i *Lifecycler) getRenewedAt() time.Time {
if ts := i.renewedTimestamp(); ts != 0 {
return time.Unix(ts, 0)
}
return time.Time{}
}

func (i *Lifecycler) setRenewedAt(renewedAt time.Time) {
i.stateMtx.Lock()
defer i.stateMtx.Unlock()

i.tokenFile.RenewedTimestamp = 0
if !renewedAt.IsZero() {
i.tokenFile.RenewedTimestamp = renewedAt.Unix()
}
if i.cfg.TokensFilePath != "" {
if err := i.tokenFile.StoreToFile(i.cfg.TokensFilePath); err != nil {
level.Error(i.logger).Log("msg", "error storing renewed timestamp to disk", "path", i.cfg.TokensFilePath, "err", err)
}
}
}

// renewedTimestamp returns the instance's renewed timestamp as stored in the ring.
func (i *Lifecycler) renewedTimestamp() int64 {
i.stateMtx.RLock()
defer i.stateMtx.RUnlock()
return i.tokenFile.RenewedTimestamp
}

// addToRing adds or replaces this instance's entry in the ring from its local state:
// state, registered and renewed timestamps. Update the local state before calling it.
// Use it instead of Desc.AddIngester, which leaves the renewed timestamp unset.
func (i *Lifecycler) addToRing(ringDesc *Desc, tokens []uint32) InstanceDesc {
instanceDesc := ringDesc.AddIngester(i.ID, i.Addr, i.Zone, tokens, i.GetState(), i.getRegisteredAt())
instanceDesc.RenewedTimestamp = i.renewedTimestamp()
ringDesc.Ingesters[i.ID] = instanceDesc
return instanceDesc
}

// ClaimTokensFor takes all the tokens for the supplied ingester and assigns them to this ingester.
//
// For this method to work correctly (especially when using gossiping), source ingester (specified by
Expand Down Expand Up @@ -767,7 +808,7 @@ func (i *Lifecycler) initRing(ctx context.Context) (bool, error) {
if len(tokensFromFile) >= i.cfg.NumTokens && i.autoJoinOnStartup {
i.setState(i.getPreviousState())
state := i.GetState()
ringDesc.AddIngester(i.ID, i.Addr, i.Zone, tokensFromFile, state, registeredAt)
i.addToRing(ringDesc, tokensFromFile)
level.Info(i.logger).Log("msg", "auto join on startup, adding with token and state", "ring", i.RingName, "state", state)
return ringDesc, true, nil
}
Expand All @@ -779,13 +820,18 @@ func (i *Lifecycler) initRing(ctx context.Context) (bool, error) {

// Either we are a new ingester, or consul must have restarted
level.Info(i.logger).Log("msg", "instance not found in ring, adding with no tokens", "ring", i.RingName)
ringDesc.AddIngester(i.ID, i.Addr, i.Zone, []uint32{}, i.GetState(), registeredAt)
i.addToRing(ringDesc, []uint32{})
return ringDesc, true, nil
}

// The instance already exists in the ring, so we can't change the registered timestamp (even if it's zero)
// but we need to update the local state accordingly.
i.setRegisteredAt(instanceDesc.GetRegisteredAt())
// The ring is authoritative, but an entry written by a version without the renewed
// timestamp has none, so keep the one from the tokens file then.
if renewedAt := instanceDesc.GetRenewedAt(); !renewedAt.IsZero() {
i.setRenewedAt(renewedAt)
}

// If the ingester is in the JOINING state this means it crashed due to
// a failed token transfer or some other reason during startup. We want
Expand Down Expand Up @@ -889,13 +935,23 @@ func (i *Lifecycler) RenewTokens(ratio float64, ctx context.Context) {

needTokens := i.cfg.NumTokens - len(ringTokens)
level.Info(i.logger).Log("msg", "renewing new tokens", "count", needTokens, "ring", i.RingName)
ringDesc.AddIngester(i.ID, i.Addr, i.Zone, ringTokens, i.GetState(), i.getRegisteredAt())
i.addToRing(ringDesc, ringTokens)
newTokens := i.tg.GenerateTokens(ringDesc, i.ID, i.Zone, needTokens, true, true)

ringTokens = append(ringTokens, newTokens...)
sort.Sort(ringTokens)

ringDesc.AddIngester(i.ID, i.Addr, i.Zone, ringTokens, i.GetState(), i.getRegisteredAt())
// Mark the instance as renewed. For the lookback period, shuffle sharding with
// lookback then keeps including the previous owners of its new tokens' ranges, as
// for a newly registered instance, and includes it in every subring, since it may
// still hold data of the tenants whose subring it left.
//
// The local state is updated before the CAS commits: the heartbeat writes the
// renewed timestamp from it, so updating it afterwards would let a heartbeat in
// between revert it in the ring. A retry only moves it to a later time, and if the
// CAS fails the instance is just included in more subrings than needed.
i.setRenewedAt(time.Now())
i.addToRing(ringDesc, ringTokens)
i.setTokens(ringTokens)
return ringDesc, true, nil
})
Expand Down Expand Up @@ -932,7 +988,7 @@ func (i *Lifecycler) verifyTokens(ctx context.Context) bool {
ringTokens = append(ringTokens, newTokens...)
sort.Sort(ringTokens)

ringDesc.AddIngester(i.ID, i.Addr, i.Zone, ringTokens, i.GetState(), i.getRegisteredAt())
i.addToRing(ringDesc, ringTokens)

i.setTokens(ringTokens)

Expand Down Expand Up @@ -993,7 +1049,7 @@ func (i *Lifecycler) autoJoin(ctx context.Context, targetState InstanceState, al
// Tokens have been verified. No need to change them.
i.setState(targetState)
state := i.GetState()
ringDesc.AddIngester(i.ID, i.Addr, i.Zone, i.getTokens(), state, i.getRegisteredAt())
i.addToRing(ringDesc, i.getTokens())
level.Info(i.logger).Log("msg", "auto joined with existing tokens", "ring", i.RingName, "state", state)
return ringDesc, true, nil
}
Expand All @@ -1015,7 +1071,7 @@ func (i *Lifecycler) autoJoin(ctx context.Context, targetState InstanceState, al

i.setState(targetState)
state := i.GetState()
ringDesc.AddIngester(i.ID, i.Addr, i.Zone, i.getTokens(), state, i.getRegisteredAt())
i.addToRing(ringDesc, i.getTokens())
level.Info(i.logger).Log("msg", "auto joined with new tokens", "ring", i.RingName, "state", state)

return ringDesc, true, nil
Expand Down Expand Up @@ -1045,13 +1101,14 @@ func (i *Lifecycler) updateConsul(ctx context.Context) error {
if !ok {
// consul must have restarted
level.Info(i.logger).Log("msg", "found empty ring, inserting tokens", "ring", i.RingName)
ringDesc.AddIngester(i.ID, i.Addr, i.Zone, i.getTokens(), i.GetState(), i.getRegisteredAt())
i.addToRing(ringDesc, i.getTokens())
} else {
instanceDesc.Timestamp = time.Now().Unix()
instanceDesc.State = i.GetState()
instanceDesc.Addr = i.Addr
instanceDesc.Zone = i.Zone
instanceDesc.RegisteredTimestamp = i.getRegisteredAt().Unix()
instanceDesc.RenewedTimestamp = i.renewedTimestamp()
ringDesc.Ingesters[i.ID] = instanceDesc
}
i.delegate.OnRingInstanceHeartbeat(i, ringDesc)
Expand Down
Loading