forked from vitessio/vitess
/
tx_throttler.go
316 lines (283 loc) · 10.9 KB
/
tx_throttler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package txthrottler
import (
"fmt"
"sync"
"time"
log "github.com/golang/glog"
"github.com/golang/protobuf/proto"
"github.com/youtube/vitess/go/vt/discovery"
"github.com/youtube/vitess/go/vt/vttablet/tabletserver/tabletenv"
"github.com/youtube/vitess/go/vt/throttler"
"github.com/youtube/vitess/go/vt/topo"
throttlerdatapb "github.com/youtube/vitess/go/vt/proto/throttlerdata"
topodatapb "github.com/youtube/vitess/go/vt/proto/topodata"
)
// TxThrottler throttles transactions based on replication lag.
// It's a thin wrapper around the throttler found in vitess/go/vt/throttler.
// It uses a discovery.HealthCheck to send replication-lag updates to the wrapped throttler.
//
// Intended Usage:
// // Assuming topoServer is a topo.Server variable pointing to a Vitess topology server.
// t := CreateTxThrottlerFromTabletConfig(topoServer)
//
// // A transaction throttler must be opened before its first use:
// if err := t.Open(keyspace, shard); err != nil {
// return err
// }
//
// // Checking whether to throttle can be done as follows before starting a transaction.
// if t.Throttle() {
// return fmt.Errorf("Transaction throttled!")
// } else {
// // execute transaction.
// }
//
// // To release the resources used by the throttler the caller should call Close().
// t.Close()
//
// A TxThrottler object is generally not thread-safe: at any given time at most one goroutine should
// be executing a method. The only exception is the 'Throttle' method where multiple goroutines are
// allowed to execute it concurrently.
type TxThrottler struct {
// config stores the transaction throttler's configuration.
// It is populated in NewTxThrottler and is not modified
// since.
config *txThrottlerConfig
// state holds an open transaction throttler state. It is nil
// if the TransactionThrottler is closed.
state *txThrottlerState
}
// CreateTxThrottlerFromTabletConfig tries to construct a TxThrottler from the
// relevant fields in the tabletenv.Config object. It returns a disabled TxThrottler if
// any error occurs.
// This function calls tryCreateTxThrottler that does the actual creation work
// and returns an error if one occurred.
func CreateTxThrottlerFromTabletConfig(topoServer topo.Server) *TxThrottler {
txThrottler, err := tryCreateTxThrottler(topoServer)
if err != nil {
log.Errorf("Error creating transaction throttler. Transaction throttling will"+
" be disabled. Error: %v", err)
txThrottler, err = newTxThrottler(&txThrottlerConfig{enabled: false})
if err != nil {
panic("BUG: Can't create a disabled transaction throttler")
}
} else {
log.Infof("Initialized transaction throttler with config: %+v", txThrottler.config)
}
return txThrottler
}
func tryCreateTxThrottler(topoServer topo.Server) (*TxThrottler, error) {
if !tabletenv.Config.EnableTxThrottler {
return newTxThrottler(&txThrottlerConfig{enabled: false})
}
var throttlerConfig throttlerdatapb.Configuration
if err := proto.UnmarshalText(tabletenv.Config.TxThrottlerConfig, &throttlerConfig); err != nil {
return nil, err
}
// Clone tsv.TxThrottlerHealthCheckCells so that we don't assume tsv.TxThrottlerHealthCheckCells
// is immutable.
healthCheckCells := make([]string, len(tabletenv.Config.TxThrottlerHealthCheckCells))
copy(healthCheckCells, tabletenv.Config.TxThrottlerHealthCheckCells)
return newTxThrottler(&txThrottlerConfig{
enabled: true,
topoServer: topoServer,
throttlerConfig: &throttlerConfig,
healthCheckCells: healthCheckCells,
})
}
// txThrottlerConfig holds the parameters that need to be
// passed when constructing a TxThrottler object.
type txThrottlerConfig struct {
// enabled is true if the transaction throttler is enabled. All methods
// of a disabled transaction throttler do nothing and Throttle() always
// returns false.
enabled bool
topoServer topo.Server
throttlerConfig *throttlerdatapb.Configuration
// healthCheckCells stores the cell names in which running vttablets will be monitored for
// replication lag.
healthCheckCells []string
}
// ThrottlerInterface defines the public interface that is implemented by go/vt/throttler.Throttler
// It is only used here to allow mocking out a throttler object.
type ThrottlerInterface interface {
Throttle(threadID int) time.Duration
ThreadFinished(threadID int)
Close()
MaxRate() int64
SetMaxRate(rate int64)
RecordReplicationLag(time time.Time, ts *discovery.TabletStats)
GetConfiguration() *throttlerdatapb.Configuration
UpdateConfiguration(configuration *throttlerdatapb.Configuration, copyZeroValues bool) error
ResetConfiguration()
}
// TopologyWatcherInterface defines the public interface that is implemented by
// discovery.TopologyWatcher. It is only used here to allow mocking out
// go/vt/discovery.TopologyWatcher.
type TopologyWatcherInterface interface {
WaitForInitialTopology() error
Stop()
}
// txThrottlerState holds the state of an open TxThrottler object.
type txThrottlerState struct {
// throttleMu serializes calls to throttler.Throttler.Throttle(threadId).
// That method is required to be called in serial for each threadId.
throttleMu sync.Mutex
throttler ThrottlerInterface
healthCheck discovery.HealthCheck
topologyWatchers []TopologyWatcherInterface
}
// These vars store the functions used to create the topo server, healthcheck,
// topology watchers and go/vt/throttler. These are provided here so that they can be overridden
// in tests to generate mocks.
type healthCheckFactoryFunc func() discovery.HealthCheck
type topologyWatcherFactoryFunc func(topoServer topo.Server, tr discovery.TabletRecorder, cell, keyspace, shard string, refreshInterval time.Duration, topoReadConcurrency int) TopologyWatcherInterface
type throttlerFactoryFunc func(name, unit string, threadCount int, maxRate, maxReplicationLag int64) (ThrottlerInterface, error)
var (
healthCheckFactory healthCheckFactoryFunc
topologyWatcherFactory topologyWatcherFactoryFunc
throttlerFactory throttlerFactoryFunc
)
func init() {
resetTxThrottlerFactories()
}
func resetTxThrottlerFactories() {
healthCheckFactory = discovery.NewDefaultHealthCheck
topologyWatcherFactory = func(topoServer topo.Server, tr discovery.TabletRecorder, cell, keyspace, shard string, refreshInterval time.Duration, topoReadConcurrency int) TopologyWatcherInterface {
return discovery.NewShardReplicationWatcher(
topoServer, tr, cell, keyspace, shard, refreshInterval, topoReadConcurrency)
}
throttlerFactory = func(name, unit string, threadCount int, maxRate, maxReplicationLag int64) (ThrottlerInterface, error) {
return throttler.NewThrottler(name, unit, threadCount, maxRate, maxReplicationLag)
}
}
// TxThrottlerName is the name the wrapped go/vt/throttler object will be registered with
// go/vt/throttler.GlobalManager.
const TxThrottlerName = "TransactionThrottler"
func newTxThrottler(config *txThrottlerConfig) (*TxThrottler, error) {
if config.enabled {
// Verify config.
err := throttler.MaxReplicationLagModuleConfig{Configuration: *config.throttlerConfig}.Verify()
if err != nil {
return nil, err
}
if len(config.healthCheckCells) == 0 {
return nil, fmt.Errorf("Empty healthCheckCells given. %+v", config)
}
}
return &TxThrottler{
config: config,
}, nil
}
// Open opens the transaction throttler. It must be called prior to 'Throttle'.
func (t *TxThrottler) Open(keyspace, shard string) error {
if !t.config.enabled {
return nil
}
if t.state != nil {
return fmt.Errorf("Transaction throttler already opened")
}
var err error
t.state, err = newTxThrottlerState(t.config, keyspace, shard)
return err
}
// Close closes the TxThrottler object and releases resources.
// It should be called after the throttler is no longer needed.
// It's ok to call this method on a closed throttler--in which case the method does nothing.
func (t *TxThrottler) Close() {
if !t.config.enabled {
return
}
if t.state == nil {
return
}
log.Infof("Shutting down transaction throttler.")
t.state.deallocateResources()
t.state = nil
}
// Throttle should be called before a new transaction is started.
// It returns true if the transaction should not proceed (the caller
// should back off). Throttle requires that Open() was previously called
// successfuly.
func (t *TxThrottler) Throttle() (result bool) {
if !t.config.enabled {
return false
}
if t.state == nil {
panic("BUG: Throttle() called on a closed TxThrottler")
}
return t.state.throttle()
}
func newTxThrottlerState(config *txThrottlerConfig, keyspace, shard string,
) (*txThrottlerState, error) {
t, err := throttlerFactory(
TxThrottlerName,
"TPS", /* unit */
1, /* threadCount */
throttler.MaxRateModuleDisabled, /* maxRate */
config.throttlerConfig.MaxReplicationLagSec /* maxReplicationLag */)
if err != nil {
return nil, err
}
if err := t.UpdateConfiguration(config.throttlerConfig, true /* copyZeroValues */); err != nil {
t.Close()
return nil, err
}
result := &txThrottlerState{
throttler: t,
}
result.healthCheck = healthCheckFactory()
result.healthCheck.SetListener(result, false /* sendDownEvents */)
result.topologyWatchers = make(
[]TopologyWatcherInterface, 0, len(config.healthCheckCells))
for _, cell := range config.healthCheckCells {
result.topologyWatchers = append(
result.topologyWatchers,
topologyWatcherFactory(
config.topoServer,
result.healthCheck, /* TabletRecorder */
cell,
keyspace,
shard,
discovery.DefaultTopologyWatcherRefreshInterval,
discovery.DefaultTopoReadConcurrency))
}
return result, nil
}
func (ts *txThrottlerState) throttle() bool {
if ts.throttler == nil {
panic("BUG: throttle called after deallocateResources was called.")
}
// Serialize calls to ts.throttle.Throttle()
ts.throttleMu.Lock()
defer ts.throttleMu.Unlock()
return ts.throttler.Throttle(0 /* threadId */) > 0
}
func (ts *txThrottlerState) deallocateResources() {
// We don't really need to nil out the fields here
// as deallocateResources is not expected to be called
// more than once, but it doesn't hurt to do so.
for _, watcher := range ts.topologyWatchers {
watcher.Stop()
}
ts.topologyWatchers = nil
ts.healthCheck.Close()
ts.healthCheck = nil
// After ts.healthCheck is closed txThrottlerState.StatsUpdate() is guaranteed not
// to be executing, so we can safely close the throttler.
ts.throttler.Close()
ts.throttler = nil
}
// StatsUpdate is part of the HealthCheckStatsListener interface.
func (ts *txThrottlerState) StatsUpdate(tabletStats *discovery.TabletStats) {
// Ignore MASTER and RDONLY stats.
// We currently do not monitor RDONLY tablets for replication lag. RDONLY tablets are not
// candidates for becoming master during failover, and it's acceptable to serve somewhat
// stale date from these.
// TODO(erez): If this becomes necessary, we can add a configuration option that would
// determine whether we consider RDONLY tablets here, as well.
if tabletStats.Target.TabletType != topodatapb.TabletType_REPLICA {
return
}
ts.throttler.RecordReplicationLag(time.Now(), tabletStats)
}