Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Heartbeat writer can always generate on-demand leased heartbeats, even if not at all configured #16014

Merged
merged 17 commits into from
Jul 3, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
open() and close() create and destroy the on-deman rate limiter, resp…
…ectively. We use golang atomic LoadPointer/StorePointer to avoid using mutexes in RequestHeartbeats

Signed-off-by: Shlomi Noach <2607934+shlomi-noach@users.noreply.github.com>
  • Loading branch information
shlomi-noach committed May 27, 2024
commit 02ca773d4b51b86567fee1ef30f3dc2d514ff819
54 changes: 35 additions & 19 deletions go/vt/vttablet/tabletserver/repltracker/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"sync"
"sync/atomic"
"time"
"unsafe"

"vitess.io/vitess/go/constants/sidecar"

Expand Down Expand Up @@ -128,20 +129,16 @@ func newHeartbeatWriter(env tabletenv.Env, alias *topodatapb.TabletAlias) *heart
}

w.writeConnID.Store(-1)
if w.onDemandDuration > 0 {
// Clients are given access to RequestHeartbeats(). But such clients can also abuse
// the system by initiating heartbeats too frequently. We rate-limit these requests.
w.onDemandRequestsRateLimiter = timer.NewRateLimiter(w.onDemandDuration / 4)
} else {
w.onDemandRequestsRateLimiter = &timer.RateLimiter{}
}
return w
}

// stop() is used by unt tests for proper cleanup
func (w *heartbeatWriter) stop() {
w.ticks.Stop()
w.onDemandRequestsRateLimiter.Stop()
func (w *heartbeatWriter) unsafeOnDemandRequestsRateLimiter() *unsafe.Pointer {
return (*unsafe.Pointer)(unsafe.Pointer(&w.onDemandRequestsRateLimiter))
}

func (w *heartbeatWriter) safeOnDemandRequestsRateLimiter() *timer.RateLimiter {
result := (*timer.RateLimiter)(atomic.LoadPointer(w.unsafeOnDemandRequestsRateLimiter()))
return result
}

// InitDBConfig initializes the target name for the heartbeatWriter.
Expand Down Expand Up @@ -173,6 +170,14 @@ func (w *heartbeatWriter) Open() {
w.appPool.Open(w.env.Config().DB.AppWithDB())
w.allPrivsPool.Open(w.env.Config().DB.AllPrivsWithDB())
}

if w.onDemandDuration > 0 {
// Clients are given access to RequestHeartbeats(). But such clients can also abuse
// the system by initiating heartbeats too frequently. We rate-limit these requests.
rateLimiter := timer.NewRateLimiter(w.onDemandDuration / 4)
atomic.StorePointer(w.unsafeOnDemandRequestsRateLimiter(), unsafe.Pointer(rateLimiter))
}

switch w.configType {
case HeartbeatConfigTypeNone:
// Do not kick any heartbeats
Expand All @@ -198,6 +203,12 @@ func (w *heartbeatWriter) Close() {
w.disableWrites()
w.appPool.Close()
w.allPrivsPool.Close()

if rateLimiter := w.safeOnDemandRequestsRateLimiter(); rateLimiter != nil {
rateLimiter.Stop()
}
atomic.StorePointer(w.unsafeOnDemandRequestsRateLimiter(), nil)

log.Info("Heartbeat Writer: closed")
}

Expand Down Expand Up @@ -282,13 +293,8 @@ func (w *heartbeatWriter) disableWrites() {
// and no write is in progress.
ctx, cancel := context.WithCancel(context.Background())
go func() {
defer cancel()
w.mu.Lock()
defer w.mu.Unlock()
if !w.isOpen {
return
}
w.ticks.Stop()
cancel()
}()
w.killWritesUntilStopped(ctx)

Expand Down Expand Up @@ -338,7 +344,11 @@ func (w *heartbeatWriter) killWrite() error {
// allowNextHeartbeatRequest ensures that the next call to RequestHeartbeats() passes through and
// is not rate-limited.
func (w *heartbeatWriter) allowNextHeartbeatRequest() {
w.onDemandRequestsRateLimiter.AllowOne()
// The writer could be close()d while this function is running and thus the value of the rate limiter could be nil.
// We thus use golang atomic here to avoid locking mutexes.
if rateLimiter := w.safeOnDemandRequestsRateLimiter(); rateLimiter != nil {
rateLimiter.AllowOne()
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO using the atomic.Pointer value here (assuming there aren't good reasons to switch to that type) would be clearer and safer too.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done!

}

// RequestHeartbeats implements heartbeat.HeartbeatWriter.RequestHeartbeats()
Expand All @@ -357,7 +367,13 @@ func (w *heartbeatWriter) RequestHeartbeats() {
// Now, this function can be spammed by clients (the lag throttler). We therefore only allow this function to
// actually operate once per X seconds (1/4 of onDemandDuration as a reasonable oversampling value):

w.onDemandRequestsRateLimiter.Do(func() error {
// The writer could be close()d while this function is running and thus the value of the rate limiter could be nil.
// We thus use golang atomic here to avoid locking mutexes.
rateLimiter := w.safeOnDemandRequestsRateLimiter()
if rateLimiter == nil {
return
}
rateLimiter.Do(func() error {
w.onDemandMu.Lock()
defer w.onDemandMu.Unlock()

Expand Down
41 changes: 35 additions & 6 deletions go/vt/vttablet/tabletserver/repltracker/writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ func TestWriteHeartbeat(t *testing.T) {

now := time.Now()
tw := newSimpleTestWriter(db, &now)
defer tw.stop()

upsert := fmt.Sprintf("INSERT INTO %s.heartbeat (ts, tabletUid, keyspaceShard) VALUES (%d, %d, '%s') ON DUPLICATE KEY UPDATE ts=VALUES(ts), tabletUid=VALUES(tabletUid)",
"_vt", now.UnixNano(), tw.tabletAlias.Uid, tw.keyspaceShard)
Expand All @@ -61,7 +60,6 @@ func TestWriteHeartbeatOpen(t *testing.T) {
defer db.Close()

tw := newSimpleTestWriter(db, nil)
defer tw.stop()

assert.Zero(t, tw.onDemandDuration)

Expand All @@ -79,8 +77,17 @@ func TestWriteHeartbeatOpen(t *testing.T) {
<-time.After(3 * time.Second)
assert.EqualValues(t, 1, writes.Get())
})

{
rateLimiter := tw.safeOnDemandRequestsRateLimiter()
assert.Nil(t, rateLimiter)
}
tw.Open()
defer tw.Close()
{
rateLimiter := tw.safeOnDemandRequestsRateLimiter()
assert.Nil(t, rateLimiter)
}
t.Run("open, heartbeats", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
Expand Down Expand Up @@ -109,7 +116,6 @@ func TestWriteHeartbeatDisabled(t *testing.T) {
defer db.Close()

tw := newTestWriter(db, nil, tabletenv.Disable, 0)
defer tw.stop()

// Even though disabled, the writer will have an on-demand duration set.
assert.Equal(t, defaultOnDemandDuration, tw.onDemandDuration)
Expand All @@ -128,8 +134,16 @@ func TestWriteHeartbeatDisabled(t *testing.T) {
<-time.After(3 * time.Second)
assert.EqualValues(t, 1, writes.Get())
})
{
rateLimiter := tw.safeOnDemandRequestsRateLimiter()
assert.Nil(t, rateLimiter)
}
tw.Open()
defer tw.Close()
{
rateLimiter := tw.safeOnDemandRequestsRateLimiter()
assert.NotNil(t, rateLimiter)
}
t.Run("open, no heartbeats", func(t *testing.T) {
<-time.After(3 * time.Second)
assert.EqualValues(t, 1, writes.Get())
Expand Down Expand Up @@ -158,6 +172,11 @@ func TestWriteHeartbeatDisabled(t *testing.T) {
<-time.After(3 * time.Second)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO we should use the onDemandDuration value again here and everywhere else that we're using the 3 second literal in these tests.

Copy link
Contributor Author

@shlomi-noach shlomi-noach Jun 2, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's actually explicitly using a different value. It would be confusing to reuse onDemandDuration. What we want to say is: after onDemandDuration is expired, no new heartbeats are written, regardless of how many seconds we wait.

If we reused onDemandDuration, that could imply to the reader that there is come mysterious connection, where after the duration expires, you need it to expire again so as to eliminate heartbeats.

Does that make sense?

assert.EqualValues(t, currentWrites, writes.Get())
})
tw.Close()
{
rateLimiter := tw.safeOnDemandRequestsRateLimiter()
assert.Nil(t, rateLimiter)
}
}

// TestWriteHeartbeatOnDemand tests that the heartbeat writer initiates leased heartbeats once opened,
Expand All @@ -170,7 +189,6 @@ func TestWriteHeartbeatOnDemand(t *testing.T) {
defer db.Close()

tw := newTestWriter(db, nil, tabletenv.Heartbeat, onDemandDuration)
defer tw.stop()

assert.Equal(t, onDemandDuration, tw.onDemandDuration)

Expand All @@ -188,8 +206,16 @@ func TestWriteHeartbeatOnDemand(t *testing.T) {
<-time.After(3 * time.Second)
assert.EqualValues(t, 1, writes.Get())
})
{
rateLimiter := tw.safeOnDemandRequestsRateLimiter()
assert.Nil(t, rateLimiter)
}
tw.Open()
defer tw.Close()
{
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Personal preference, but I don't see the value that these code blocks add and use of them is pretty non-standard within Vitess.

Copy link
Contributor Author

@shlomi-noach shlomi-noach Jun 2, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll explain why I use this: it's allowing me to redeclare a variable (rateLimiter := in this case) that I do not need to fear is "leaking" elsewhere. Also, I dislike how in unit testing you want to duplicate some tests, but golang requires that the first assignment be := and then you can only use =. But then as you shuffle things, you need to again modify := to = or = to := in places that are unrelated to your change. This causes git diffs that are irrelevant to your change (not unlike trailing comma in a table definition on an unrelated index when you add a new index).
So I feel like these code blocks help me isolate:

  • actual code/variables
  • git diffs

It's a personal preference and I recognize this is not standard in Vitess. FWIW I've already spread that around quite a bit.

rateLimiter := tw.safeOnDemandRequestsRateLimiter()
assert.NotNil(t, rateLimiter)
}
t.Run("open, initial heartbeats", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), tw.onDemandDuration-time.Second)
Copy link
Contributor

@mattlord mattlord May 31, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason to use the -time.Second part? That would put us at 2 seconds and it seems like it may be possible that we then only tick with the ticker once before the context is done.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. The reasoning is that I don't want to get past the expiration of the heartbeat lease. This function is checking:

  • That heartbeats are generated when on-demand is engaged (upon Open() in this case)
  • And that they keep being generated for the duration of the on-demand lease. The heartbeat interval in this test is 250ms, and we test every 1 second, just shy of the expiration.

If we go past the expiration, then we can wrongly condlude that heartbeats are not being produced when they should (they shouldn't, past the expiration).

defer cancel()
Expand Down Expand Up @@ -225,6 +251,11 @@ func TestWriteHeartbeatOnDemand(t *testing.T) {
<-time.After(3 * time.Second)
assert.EqualValues(t, currentWrites, writes.Get())
})
tw.Close()
{
rateLimiter := tw.safeOnDemandRequestsRateLimiter()
assert.Nil(t, rateLimiter)
}
}

func TestWriteHeartbeatError(t *testing.T) {
Expand All @@ -233,7 +264,6 @@ func TestWriteHeartbeatError(t *testing.T) {

now := time.Now()
tw := newSimpleTestWriter(db, &now)
defer tw.stop()

writes.Reset()
writeErrors.Reset()
Expand All @@ -247,7 +277,6 @@ func TestWriteHeartbeatError(t *testing.T) {
func TestCloseWhileStuckWriting(t *testing.T) {
db := fakesqldb.New(t)
tw := newSimpleTestWriter(db, nil)
defer tw.stop()

tw.isOpen = true

Expand Down
Loading