repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
vitessio/vitess
go/vt/vtgate/planbuilder/route.go
queryTimeout
func queryTimeout(d sqlparser.CommentDirectives) int { if d == nil { return 0 } val, ok := d[sqlparser.DirectiveQueryTimeout] if !ok { return 0 } intVal, ok := val.(int) if ok { return intVal } return 0 }
go
func queryTimeout(d sqlparser.CommentDirectives) int { if d == nil { return 0 } val, ok := d[sqlparser.DirectiveQueryTimeout] if !ok { return 0 } intVal, ok := val.(int) if ok { return intVal } return 0 }
[ "func", "queryTimeout", "(", "d", "sqlparser", ".", "CommentDirectives", ")", "int", "{", "if", "d", "==", "nil", "{", "return", "0", "\n", "}", "\n\n", "val", ",", "ok", ":=", "d", "[", "sqlparser", ".", "DirectiveQueryTimeout", "]", "\n", "if", "!", "ok", "{", "return", "0", "\n", "}", "\n\n", "intVal", ",", "ok", ":=", "val", ".", "(", "int", ")", "\n", "if", "ok", "{", "return", "intVal", "\n", "}", "\n", "return", "0", "\n", "}" ]
// queryTimeout returns DirectiveQueryTimeout value if set, otherwise returns 0.
[ "queryTimeout", "returns", "DirectiveQueryTimeout", "value", "if", "set", "otherwise", "returns", "0", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/route.go#L580-L595
train
vitessio/vitess
go/vt/vtgate/planbuilder/builder.go
Build
func Build(query string, vschema ContextVSchema) (*engine.Plan, error) { stmt, err := sqlparser.Parse(query) if err != nil { return nil, err } return BuildFromStmt(query, stmt, vschema) }
go
func Build(query string, vschema ContextVSchema) (*engine.Plan, error) { stmt, err := sqlparser.Parse(query) if err != nil { return nil, err } return BuildFromStmt(query, stmt, vschema) }
[ "func", "Build", "(", "query", "string", ",", "vschema", "ContextVSchema", ")", "(", "*", "engine", ".", "Plan", ",", "error", ")", "{", "stmt", ",", "err", ":=", "sqlparser", ".", "Parse", "(", "query", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "BuildFromStmt", "(", "query", ",", "stmt", ",", "vschema", ")", "\n", "}" ]
// Build builds a plan for a query based on the specified vschema. // It's the main entry point for this package.
[ "Build", "builds", "a", "plan", "for", "a", "query", "based", "on", "the", "specified", "vschema", ".", "It", "s", "the", "main", "entry", "point", "for", "this", "package", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/builder.go#L120-L126
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
stateInfo
func stateInfo(state int64) string { if state == StateServing { return "SERVING" } return fmt.Sprintf("%s (%s)", stateName[state], stateDetail[state]) }
go
func stateInfo(state int64) string { if state == StateServing { return "SERVING" } return fmt.Sprintf("%s (%s)", stateName[state], stateDetail[state]) }
[ "func", "stateInfo", "(", "state", "int64", ")", "string", "{", "if", "state", "==", "StateServing", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "stateName", "[", "state", "]", ",", "stateDetail", "[", "state", "]", ")", "\n", "}" ]
// stateInfo returns a string representation of the state and optional detail // about the reason for the state transition
[ "stateInfo", "returns", "a", "string", "representation", "of", "the", "state", "and", "optional", "detail", "about", "the", "reason", "for", "the", "state", "transition" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L117-L122
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
NewServer
func NewServer(topoServer *topo.Server, alias topodatapb.TabletAlias) *TabletServer { return NewTabletServer(tabletenv.Config, topoServer, alias) }
go
func NewServer(topoServer *topo.Server, alias topodatapb.TabletAlias) *TabletServer { return NewTabletServer(tabletenv.Config, topoServer, alias) }
[ "func", "NewServer", "(", "topoServer", "*", "topo", ".", "Server", ",", "alias", "topodatapb", ".", "TabletAlias", ")", "*", "TabletServer", "{", "return", "NewTabletServer", "(", "tabletenv", ".", "Config", ",", "topoServer", ",", "alias", ")", "\n", "}" ]
// NewServer creates a new TabletServer based on the command line flags.
[ "NewServer", "creates", "a", "new", "TabletServer", "based", "on", "the", "command", "line", "flags", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L210-L212
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
NewTabletServerWithNilTopoServer
func NewTabletServerWithNilTopoServer(config tabletenv.TabletConfig) *TabletServer { return NewTabletServer(config, nil, topodatapb.TabletAlias{}) }
go
func NewTabletServerWithNilTopoServer(config tabletenv.TabletConfig) *TabletServer { return NewTabletServer(config, nil, topodatapb.TabletAlias{}) }
[ "func", "NewTabletServerWithNilTopoServer", "(", "config", "tabletenv", ".", "TabletConfig", ")", "*", "TabletServer", "{", "return", "NewTabletServer", "(", "config", ",", "nil", ",", "topodatapb", ".", "TabletAlias", "{", "}", ")", "\n", "}" ]
// NewTabletServerWithNilTopoServer is typically used in tests that // don't need a topoServer member.
[ "NewTabletServerWithNilTopoServer", "is", "typically", "used", "in", "tests", "that", "don", "t", "need", "a", "topoServer", "member", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L259-L261
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
NewTabletServer
func NewTabletServer(config tabletenv.TabletConfig, topoServer *topo.Server, alias topodatapb.TabletAlias) *TabletServer { tsv := &TabletServer{ QueryTimeout: sync2.NewAtomicDuration(time.Duration(config.QueryTimeout * 1e9)), BeginTimeout: sync2.NewAtomicDuration(time.Duration(config.TxPoolTimeout * 1e9)), TerseErrors: config.TerseErrors, enableHotRowProtection: config.EnableHotRowProtection || config.EnableHotRowProtectionDryRun, checkMySQLThrottler: sync2.NewSemaphore(1, 0), streamHealthMap: make(map[int]chan<- *querypb.StreamHealthResponse), history: history.New(10), topoServer: topoServer, alias: alias, } tsv.se = schema.NewEngine(tsv, config) tsv.qe = NewQueryEngine(tsv, tsv.se, config) tsv.te = NewTxEngine(tsv, config) tsv.teCtrl = tsv.te tsv.hw = heartbeat.NewWriter(tsv, alias, config) tsv.hr = heartbeat.NewReader(tsv, config) tsv.txThrottler = txthrottler.CreateTxThrottlerFromTabletConfig(topoServer) tsv.messager = messager.NewEngine(tsv, tsv.se, config) tsv.watcher = NewReplicationWatcher(tsv.se, config) tsv.updateStreamList = &binlog.StreamList{} // FIXME(alainjobart) could we move this to the Register method below? // So that vtcombo doesn't even call it once, on the first tablet. // And we can remove the tsOnce variable. tsOnce.Do(func() { srvTopoServer = srvtopo.NewResilientServer(topoServer, "TabletSrvTopo") stats.NewGaugeFunc("TabletState", "Tablet server state", func() int64 { tsv.mu.Lock() state := tsv.state tsv.mu.Unlock() return state }) stats.Publish("TabletStateName", stats.StringFunc(tsv.GetState)) // TabletServerState exports the same information as the above two stats (TabletState / TabletStateName), // but exported with TabletStateName as a label for Prometheus, which doesn't support exporting strings as stat values. stats.NewGaugesFuncWithMultiLabels("TabletServerState", "Tablet server state labeled by state name", []string{"name"}, func() map[string]int64 { return map[string]int64{tsv.GetState(): 1} }) stats.NewGaugeDurationFunc("QueryTimeout", "Tablet server query timeout", tsv.QueryTimeout.Get) stats.NewGaugeDurationFunc("QueryPoolTimeout", "Tablet server timeout to get a connection from the query pool", tsv.qe.connTimeout.Get) stats.NewGaugeDurationFunc("BeginTimeout", "Tablet server begin timeout", tsv.BeginTimeout.Get) }) // TODO(sougou): move this up once the stats naming problem is fixed. tsv.vstreamer = vstreamer.NewEngine(srvTopoServer, tsv.se) return tsv }
go
func NewTabletServer(config tabletenv.TabletConfig, topoServer *topo.Server, alias topodatapb.TabletAlias) *TabletServer { tsv := &TabletServer{ QueryTimeout: sync2.NewAtomicDuration(time.Duration(config.QueryTimeout * 1e9)), BeginTimeout: sync2.NewAtomicDuration(time.Duration(config.TxPoolTimeout * 1e9)), TerseErrors: config.TerseErrors, enableHotRowProtection: config.EnableHotRowProtection || config.EnableHotRowProtectionDryRun, checkMySQLThrottler: sync2.NewSemaphore(1, 0), streamHealthMap: make(map[int]chan<- *querypb.StreamHealthResponse), history: history.New(10), topoServer: topoServer, alias: alias, } tsv.se = schema.NewEngine(tsv, config) tsv.qe = NewQueryEngine(tsv, tsv.se, config) tsv.te = NewTxEngine(tsv, config) tsv.teCtrl = tsv.te tsv.hw = heartbeat.NewWriter(tsv, alias, config) tsv.hr = heartbeat.NewReader(tsv, config) tsv.txThrottler = txthrottler.CreateTxThrottlerFromTabletConfig(topoServer) tsv.messager = messager.NewEngine(tsv, tsv.se, config) tsv.watcher = NewReplicationWatcher(tsv.se, config) tsv.updateStreamList = &binlog.StreamList{} // FIXME(alainjobart) could we move this to the Register method below? // So that vtcombo doesn't even call it once, on the first tablet. // And we can remove the tsOnce variable. tsOnce.Do(func() { srvTopoServer = srvtopo.NewResilientServer(topoServer, "TabletSrvTopo") stats.NewGaugeFunc("TabletState", "Tablet server state", func() int64 { tsv.mu.Lock() state := tsv.state tsv.mu.Unlock() return state }) stats.Publish("TabletStateName", stats.StringFunc(tsv.GetState)) // TabletServerState exports the same information as the above two stats (TabletState / TabletStateName), // but exported with TabletStateName as a label for Prometheus, which doesn't support exporting strings as stat values. stats.NewGaugesFuncWithMultiLabels("TabletServerState", "Tablet server state labeled by state name", []string{"name"}, func() map[string]int64 { return map[string]int64{tsv.GetState(): 1} }) stats.NewGaugeDurationFunc("QueryTimeout", "Tablet server query timeout", tsv.QueryTimeout.Get) stats.NewGaugeDurationFunc("QueryPoolTimeout", "Tablet server timeout to get a connection from the query pool", tsv.qe.connTimeout.Get) stats.NewGaugeDurationFunc("BeginTimeout", "Tablet server begin timeout", tsv.BeginTimeout.Get) }) // TODO(sougou): move this up once the stats naming problem is fixed. tsv.vstreamer = vstreamer.NewEngine(srvTopoServer, tsv.se) return tsv }
[ "func", "NewTabletServer", "(", "config", "tabletenv", ".", "TabletConfig", ",", "topoServer", "*", "topo", ".", "Server", ",", "alias", "topodatapb", ".", "TabletAlias", ")", "*", "TabletServer", "{", "tsv", ":=", "&", "TabletServer", "{", "QueryTimeout", ":", "sync2", ".", "NewAtomicDuration", "(", "time", ".", "Duration", "(", "config", ".", "QueryTimeout", "*", "1e9", ")", ")", ",", "BeginTimeout", ":", "sync2", ".", "NewAtomicDuration", "(", "time", ".", "Duration", "(", "config", ".", "TxPoolTimeout", "*", "1e9", ")", ")", ",", "TerseErrors", ":", "config", ".", "TerseErrors", ",", "enableHotRowProtection", ":", "config", ".", "EnableHotRowProtection", "||", "config", ".", "EnableHotRowProtectionDryRun", ",", "checkMySQLThrottler", ":", "sync2", ".", "NewSemaphore", "(", "1", ",", "0", ")", ",", "streamHealthMap", ":", "make", "(", "map", "[", "int", "]", "chan", "<-", "*", "querypb", ".", "StreamHealthResponse", ")", ",", "history", ":", "history", ".", "New", "(", "10", ")", ",", "topoServer", ":", "topoServer", ",", "alias", ":", "alias", ",", "}", "\n", "tsv", ".", "se", "=", "schema", ".", "NewEngine", "(", "tsv", ",", "config", ")", "\n", "tsv", ".", "qe", "=", "NewQueryEngine", "(", "tsv", ",", "tsv", ".", "se", ",", "config", ")", "\n", "tsv", ".", "te", "=", "NewTxEngine", "(", "tsv", ",", "config", ")", "\n", "tsv", ".", "teCtrl", "=", "tsv", ".", "te", "\n", "tsv", ".", "hw", "=", "heartbeat", ".", "NewWriter", "(", "tsv", ",", "alias", ",", "config", ")", "\n", "tsv", ".", "hr", "=", "heartbeat", ".", "NewReader", "(", "tsv", ",", "config", ")", "\n", "tsv", ".", "txThrottler", "=", "txthrottler", ".", "CreateTxThrottlerFromTabletConfig", "(", "topoServer", ")", "\n", "tsv", ".", "messager", "=", "messager", ".", "NewEngine", "(", "tsv", ",", "tsv", ".", "se", ",", "config", ")", "\n", "tsv", ".", "watcher", "=", "NewReplicationWatcher", "(", "tsv", ".", "se", ",", "config", ")", "\n", "tsv", ".", "updateStreamList", "=", "&", "binlog", ".", "StreamList", "{", "}", "\n", "// FIXME(alainjobart) could we move this to the Register method below?", "// So that vtcombo doesn't even call it once, on the first tablet.", "// And we can remove the tsOnce variable.", "tsOnce", ".", "Do", "(", "func", "(", ")", "{", "srvTopoServer", "=", "srvtopo", ".", "NewResilientServer", "(", "topoServer", ",", "\"", "\"", ")", "\n", "stats", ".", "NewGaugeFunc", "(", "\"", "\"", ",", "\"", "\"", ",", "func", "(", ")", "int64", "{", "tsv", ".", "mu", ".", "Lock", "(", ")", "\n", "state", ":=", "tsv", ".", "state", "\n", "tsv", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "state", "\n", "}", ")", "\n", "stats", ".", "Publish", "(", "\"", "\"", ",", "stats", ".", "StringFunc", "(", "tsv", ".", "GetState", ")", ")", "\n\n", "// TabletServerState exports the same information as the above two stats (TabletState / TabletStateName),", "// but exported with TabletStateName as a label for Prometheus, which doesn't support exporting strings as stat values.", "stats", ".", "NewGaugesFuncWithMultiLabels", "(", "\"", "\"", ",", "\"", "\"", ",", "[", "]", "string", "{", "\"", "\"", "}", ",", "func", "(", ")", "map", "[", "string", "]", "int64", "{", "return", "map", "[", "string", "]", "int64", "{", "tsv", ".", "GetState", "(", ")", ":", "1", "}", "\n", "}", ")", "\n", "stats", ".", "NewGaugeDurationFunc", "(", "\"", "\"", ",", "\"", "\"", ",", "tsv", ".", "QueryTimeout", ".", "Get", ")", "\n", "stats", ".", "NewGaugeDurationFunc", "(", "\"", "\"", ",", "\"", "\"", ",", "tsv", ".", "qe", ".", "connTimeout", ".", "Get", ")", "\n", "stats", ".", "NewGaugeDurationFunc", "(", "\"", "\"", ",", "\"", "\"", ",", "tsv", ".", "BeginTimeout", ".", "Get", ")", "\n", "}", ")", "\n", "// TODO(sougou): move this up once the stats naming problem is fixed.", "tsv", ".", "vstreamer", "=", "vstreamer", ".", "NewEngine", "(", "srvTopoServer", ",", "tsv", ".", "se", ")", "\n", "return", "tsv", "\n", "}" ]
// NewTabletServer creates an instance of TabletServer. Only the first // instance of TabletServer will expose its state variables.
[ "NewTabletServer", "creates", "an", "instance", "of", "TabletServer", ".", "Only", "the", "first", "instance", "of", "TabletServer", "will", "expose", "its", "state", "variables", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L265-L312
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
Register
func (tsv *TabletServer) Register() { for _, f := range RegisterFunctions { f(tsv) } tsv.registerDebugHealthHandler() tsv.registerQueryzHandler() tsv.registerStreamQueryzHandlers() tsv.registerTwopczHandler() }
go
func (tsv *TabletServer) Register() { for _, f := range RegisterFunctions { f(tsv) } tsv.registerDebugHealthHandler() tsv.registerQueryzHandler() tsv.registerStreamQueryzHandlers() tsv.registerTwopczHandler() }
[ "func", "(", "tsv", "*", "TabletServer", ")", "Register", "(", ")", "{", "for", "_", ",", "f", ":=", "range", "RegisterFunctions", "{", "f", "(", "tsv", ")", "\n", "}", "\n", "tsv", ".", "registerDebugHealthHandler", "(", ")", "\n", "tsv", ".", "registerQueryzHandler", "(", ")", "\n", "tsv", ".", "registerStreamQueryzHandlers", "(", ")", "\n", "tsv", ".", "registerTwopczHandler", "(", ")", "\n", "}" ]
// Register prepares TabletServer for serving by calling // all the registrations functions.
[ "Register", "prepares", "TabletServer", "for", "serving", "by", "calling", "all", "the", "registrations", "functions", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L316-L324
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
RegisterQueryRuleSource
func (tsv *TabletServer) RegisterQueryRuleSource(ruleSource string) { tsv.qe.queryRuleSources.RegisterSource(ruleSource) }
go
func (tsv *TabletServer) RegisterQueryRuleSource(ruleSource string) { tsv.qe.queryRuleSources.RegisterSource(ruleSource) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "RegisterQueryRuleSource", "(", "ruleSource", "string", ")", "{", "tsv", ".", "qe", ".", "queryRuleSources", ".", "RegisterSource", "(", "ruleSource", ")", "\n", "}" ]
// RegisterQueryRuleSource registers ruleSource for setting query rules.
[ "RegisterQueryRuleSource", "registers", "ruleSource", "for", "setting", "query", "rules", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L327-L329
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
UnRegisterQueryRuleSource
func (tsv *TabletServer) UnRegisterQueryRuleSource(ruleSource string) { tsv.qe.queryRuleSources.UnRegisterSource(ruleSource) }
go
func (tsv *TabletServer) UnRegisterQueryRuleSource(ruleSource string) { tsv.qe.queryRuleSources.UnRegisterSource(ruleSource) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "UnRegisterQueryRuleSource", "(", "ruleSource", "string", ")", "{", "tsv", ".", "qe", ".", "queryRuleSources", ".", "UnRegisterSource", "(", "ruleSource", ")", "\n", "}" ]
// UnRegisterQueryRuleSource unregisters ruleSource from query rules.
[ "UnRegisterQueryRuleSource", "unregisters", "ruleSource", "from", "query", "rules", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L332-L334
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
SetQueryRules
func (tsv *TabletServer) SetQueryRules(ruleSource string, qrs *rules.Rules) error { err := tsv.qe.queryRuleSources.SetRules(ruleSource, qrs) if err != nil { return err } tsv.qe.ClearQueryPlanCache() return nil }
go
func (tsv *TabletServer) SetQueryRules(ruleSource string, qrs *rules.Rules) error { err := tsv.qe.queryRuleSources.SetRules(ruleSource, qrs) if err != nil { return err } tsv.qe.ClearQueryPlanCache() return nil }
[ "func", "(", "tsv", "*", "TabletServer", ")", "SetQueryRules", "(", "ruleSource", "string", ",", "qrs", "*", "rules", ".", "Rules", ")", "error", "{", "err", ":=", "tsv", ".", "qe", ".", "queryRuleSources", ".", "SetRules", "(", "ruleSource", ",", "qrs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "tsv", ".", "qe", ".", "ClearQueryPlanCache", "(", ")", "\n", "return", "nil", "\n", "}" ]
// SetQueryRules sets the query rules for a registered ruleSource.
[ "SetQueryRules", "sets", "the", "query", "rules", "for", "a", "registered", "ruleSource", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L337-L344
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
GetState
func (tsv *TabletServer) GetState() string { if tsv.lameduck.Get() != 0 { return "NOT_SERVING" } tsv.mu.Lock() name := stateName[tsv.state] tsv.mu.Unlock() return name }
go
func (tsv *TabletServer) GetState() string { if tsv.lameduck.Get() != 0 { return "NOT_SERVING" } tsv.mu.Lock() name := stateName[tsv.state] tsv.mu.Unlock() return name }
[ "func", "(", "tsv", "*", "TabletServer", ")", "GetState", "(", ")", "string", "{", "if", "tsv", ".", "lameduck", ".", "Get", "(", ")", "!=", "0", "{", "return", "\"", "\"", "\n", "}", "\n", "tsv", ".", "mu", ".", "Lock", "(", ")", "\n", "name", ":=", "stateName", "[", "tsv", ".", "state", "]", "\n", "tsv", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "name", "\n", "}" ]
// GetState returns the name of the current TabletServer state.
[ "GetState", "returns", "the", "name", "of", "the", "current", "TabletServer", "state", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L347-L355
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
setState
func (tsv *TabletServer) setState(state int64) { log.Infof("TabletServer state: %s -> %s", stateInfo(tsv.state), stateInfo(state)) tsv.state = state tsv.history.Add(&historyRecord{ Time: time.Now(), ServingState: stateInfo(state), TabletType: tsv.target.TabletType.String(), }) }
go
func (tsv *TabletServer) setState(state int64) { log.Infof("TabletServer state: %s -> %s", stateInfo(tsv.state), stateInfo(state)) tsv.state = state tsv.history.Add(&historyRecord{ Time: time.Now(), ServingState: stateInfo(state), TabletType: tsv.target.TabletType.String(), }) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "setState", "(", "state", "int64", ")", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "stateInfo", "(", "tsv", ".", "state", ")", ",", "stateInfo", "(", "state", ")", ")", "\n", "tsv", ".", "state", "=", "state", "\n", "tsv", ".", "history", ".", "Add", "(", "&", "historyRecord", "{", "Time", ":", "time", ".", "Now", "(", ")", ",", "ServingState", ":", "stateInfo", "(", "state", ")", ",", "TabletType", ":", "tsv", ".", "target", ".", "TabletType", ".", "String", "(", ")", ",", "}", ")", "\n", "}" ]
// setState changes the state and logs the event. // It requires the caller to hold a lock on mu.
[ "setState", "changes", "the", "state", "and", "logs", "the", "event", ".", "It", "requires", "the", "caller", "to", "hold", "a", "lock", "on", "mu", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L359-L367
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
transition
func (tsv *TabletServer) transition(newState int64) { tsv.mu.Lock() tsv.setState(newState) tsv.mu.Unlock() }
go
func (tsv *TabletServer) transition(newState int64) { tsv.mu.Lock() tsv.setState(newState) tsv.mu.Unlock() }
[ "func", "(", "tsv", "*", "TabletServer", ")", "transition", "(", "newState", "int64", ")", "{", "tsv", ".", "mu", ".", "Lock", "(", ")", "\n", "tsv", ".", "setState", "(", "newState", ")", "\n", "tsv", ".", "mu", ".", "Unlock", "(", ")", "\n", "}" ]
// transition obtains a lock and changes the state.
[ "transition", "obtains", "a", "lock", "and", "changes", "the", "state", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L370-L374
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
InitDBConfig
func (tsv *TabletServer) InitDBConfig(target querypb.Target, dbcfgs *dbconfigs.DBConfigs) error { tsv.mu.Lock() defer tsv.mu.Unlock() if tsv.state != StateNotConnected { return vterrors.Errorf(vtrpcpb.Code_UNKNOWN, "InitDBConfig failed, current state: %s", stateName[tsv.state]) } tsv.target = target tsv.dbconfigs = dbcfgs tsv.se.InitDBConfig(tsv.dbconfigs) tsv.qe.InitDBConfig(tsv.dbconfigs) tsv.teCtrl.InitDBConfig(tsv.dbconfigs) tsv.hw.InitDBConfig(tsv.dbconfigs) tsv.hr.InitDBConfig(tsv.dbconfigs) tsv.messager.InitDBConfig(tsv.dbconfigs) tsv.watcher.InitDBConfig(tsv.dbconfigs) tsv.vstreamer.InitDBConfig(tsv.dbconfigs) return nil }
go
func (tsv *TabletServer) InitDBConfig(target querypb.Target, dbcfgs *dbconfigs.DBConfigs) error { tsv.mu.Lock() defer tsv.mu.Unlock() if tsv.state != StateNotConnected { return vterrors.Errorf(vtrpcpb.Code_UNKNOWN, "InitDBConfig failed, current state: %s", stateName[tsv.state]) } tsv.target = target tsv.dbconfigs = dbcfgs tsv.se.InitDBConfig(tsv.dbconfigs) tsv.qe.InitDBConfig(tsv.dbconfigs) tsv.teCtrl.InitDBConfig(tsv.dbconfigs) tsv.hw.InitDBConfig(tsv.dbconfigs) tsv.hr.InitDBConfig(tsv.dbconfigs) tsv.messager.InitDBConfig(tsv.dbconfigs) tsv.watcher.InitDBConfig(tsv.dbconfigs) tsv.vstreamer.InitDBConfig(tsv.dbconfigs) return nil }
[ "func", "(", "tsv", "*", "TabletServer", ")", "InitDBConfig", "(", "target", "querypb", ".", "Target", ",", "dbcfgs", "*", "dbconfigs", ".", "DBConfigs", ")", "error", "{", "tsv", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "tsv", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "tsv", ".", "state", "!=", "StateNotConnected", "{", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_UNKNOWN", ",", "\"", "\"", ",", "stateName", "[", "tsv", ".", "state", "]", ")", "\n", "}", "\n", "tsv", ".", "target", "=", "target", "\n", "tsv", ".", "dbconfigs", "=", "dbcfgs", "\n\n", "tsv", ".", "se", ".", "InitDBConfig", "(", "tsv", ".", "dbconfigs", ")", "\n", "tsv", ".", "qe", ".", "InitDBConfig", "(", "tsv", ".", "dbconfigs", ")", "\n", "tsv", ".", "teCtrl", ".", "InitDBConfig", "(", "tsv", ".", "dbconfigs", ")", "\n", "tsv", ".", "hw", ".", "InitDBConfig", "(", "tsv", ".", "dbconfigs", ")", "\n", "tsv", ".", "hr", ".", "InitDBConfig", "(", "tsv", ".", "dbconfigs", ")", "\n", "tsv", ".", "messager", ".", "InitDBConfig", "(", "tsv", ".", "dbconfigs", ")", "\n", "tsv", ".", "watcher", ".", "InitDBConfig", "(", "tsv", ".", "dbconfigs", ")", "\n", "tsv", ".", "vstreamer", ".", "InitDBConfig", "(", "tsv", ".", "dbconfigs", ")", "\n", "return", "nil", "\n", "}" ]
// InitDBConfig initializes the db config variables for TabletServer. You must call this function before // calling SetServingType.
[ "InitDBConfig", "initializes", "the", "db", "config", "variables", "for", "TabletServer", ".", "You", "must", "call", "this", "function", "before", "calling", "SetServingType", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L383-L401
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
InitACL
func (tsv *TabletServer) InitACL(tableACLConfigFile string, enforceTableACLConfig bool) { tsv.initACL(tableACLConfigFile, enforceTableACLConfig) sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGHUP) go func() { for range sigChan { tsv.initACL(tableACLConfigFile, enforceTableACLConfig) } }() }
go
func (tsv *TabletServer) InitACL(tableACLConfigFile string, enforceTableACLConfig bool) { tsv.initACL(tableACLConfigFile, enforceTableACLConfig) sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGHUP) go func() { for range sigChan { tsv.initACL(tableACLConfigFile, enforceTableACLConfig) } }() }
[ "func", "(", "tsv", "*", "TabletServer", ")", "InitACL", "(", "tableACLConfigFile", "string", ",", "enforceTableACLConfig", "bool", ")", "{", "tsv", ".", "initACL", "(", "tableACLConfigFile", ",", "enforceTableACLConfig", ")", "\n\n", "sigChan", ":=", "make", "(", "chan", "os", ".", "Signal", ",", "1", ")", "\n", "signal", ".", "Notify", "(", "sigChan", ",", "syscall", ".", "SIGHUP", ")", "\n", "go", "func", "(", ")", "{", "for", "range", "sigChan", "{", "tsv", ".", "initACL", "(", "tableACLConfigFile", ",", "enforceTableACLConfig", ")", "\n", "}", "\n", "}", "(", ")", "\n", "}" ]
// InitACL loads the table ACL and sets up a SIGHUP handler for reloading it.
[ "InitACL", "loads", "the", "table", "ACL", "and", "sets", "up", "a", "SIGHUP", "handler", "for", "reloading", "it", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L420-L430
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
StartService
func (tsv *TabletServer) StartService(target querypb.Target, dbcfgs *dbconfigs.DBConfigs) (err error) { // Save tablet type away to prevent data races tabletType := target.TabletType err = tsv.InitDBConfig(target, dbcfgs) if err != nil { return err } _ /* state changed */, err = tsv.SetServingType(tabletType, true, nil) return err }
go
func (tsv *TabletServer) StartService(target querypb.Target, dbcfgs *dbconfigs.DBConfigs) (err error) { // Save tablet type away to prevent data races tabletType := target.TabletType err = tsv.InitDBConfig(target, dbcfgs) if err != nil { return err } _ /* state changed */, err = tsv.SetServingType(tabletType, true, nil) return err }
[ "func", "(", "tsv", "*", "TabletServer", ")", "StartService", "(", "target", "querypb", ".", "Target", ",", "dbcfgs", "*", "dbconfigs", ".", "DBConfigs", ")", "(", "err", "error", ")", "{", "// Save tablet type away to prevent data races", "tabletType", ":=", "target", ".", "TabletType", "\n", "err", "=", "tsv", ".", "InitDBConfig", "(", "target", ",", "dbcfgs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", "/* state changed */", ",", "err", "=", "tsv", ".", "SetServingType", "(", "tabletType", ",", "true", ",", "nil", ")", "\n", "return", "err", "\n", "}" ]
// StartService is a convenience function for InitDBConfig->SetServingType // with serving=true.
[ "StartService", "is", "a", "convenience", "function", "for", "InitDBConfig", "-", ">", "SetServingType", "with", "serving", "=", "true", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L434-L443
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
SetServingType
func (tsv *TabletServer) SetServingType(tabletType topodatapb.TabletType, serving bool, alsoAllow []topodatapb.TabletType) (stateChanged bool, err error) { defer tsv.ExitLameduck() action, err := tsv.decideAction(tabletType, serving, alsoAllow) if err != nil { return false, err } switch action { case actionNone: return false, nil case actionFullStart: if err := tsv.fullStart(); err != nil { tsv.closeAll() return true, err } return true, nil case actionServeNewType: if err := tsv.serveNewType(); err != nil { tsv.closeAll() return true, err } return true, nil case actionGracefulStop: tsv.gracefulStop() return true, nil } panic("unreachable") }
go
func (tsv *TabletServer) SetServingType(tabletType topodatapb.TabletType, serving bool, alsoAllow []topodatapb.TabletType) (stateChanged bool, err error) { defer tsv.ExitLameduck() action, err := tsv.decideAction(tabletType, serving, alsoAllow) if err != nil { return false, err } switch action { case actionNone: return false, nil case actionFullStart: if err := tsv.fullStart(); err != nil { tsv.closeAll() return true, err } return true, nil case actionServeNewType: if err := tsv.serveNewType(); err != nil { tsv.closeAll() return true, err } return true, nil case actionGracefulStop: tsv.gracefulStop() return true, nil } panic("unreachable") }
[ "func", "(", "tsv", "*", "TabletServer", ")", "SetServingType", "(", "tabletType", "topodatapb", ".", "TabletType", ",", "serving", "bool", ",", "alsoAllow", "[", "]", "topodatapb", ".", "TabletType", ")", "(", "stateChanged", "bool", ",", "err", "error", ")", "{", "defer", "tsv", ".", "ExitLameduck", "(", ")", "\n\n", "action", ",", "err", ":=", "tsv", ".", "decideAction", "(", "tabletType", ",", "serving", ",", "alsoAllow", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "switch", "action", "{", "case", "actionNone", ":", "return", "false", ",", "nil", "\n", "case", "actionFullStart", ":", "if", "err", ":=", "tsv", ".", "fullStart", "(", ")", ";", "err", "!=", "nil", "{", "tsv", ".", "closeAll", "(", ")", "\n", "return", "true", ",", "err", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "case", "actionServeNewType", ":", "if", "err", ":=", "tsv", ".", "serveNewType", "(", ")", ";", "err", "!=", "nil", "{", "tsv", ".", "closeAll", "(", ")", "\n", "return", "true", ",", "err", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "case", "actionGracefulStop", ":", "tsv", ".", "gracefulStop", "(", ")", "\n", "return", "true", ",", "nil", "\n", "}", "\n", "panic", "(", "\"", "\"", ")", "\n", "}" ]
// SetServingType changes the serving type of the tabletserver. It starts or // stops internal services as deemed necessary. The tabletType determines the // primary serving type, while alsoAllow specifies other tablet types that // should also be honored for serving. // Returns true if the state of QueryService or the tablet type changed.
[ "SetServingType", "changes", "the", "serving", "type", "of", "the", "tabletserver", ".", "It", "starts", "or", "stops", "internal", "services", "as", "deemed", "necessary", ".", "The", "tabletType", "determines", "the", "primary", "serving", "type", "while", "alsoAllow", "specifies", "other", "tablet", "types", "that", "should", "also", "be", "honored", "for", "serving", ".", "Returns", "true", "if", "the", "state", "of", "QueryService", "or", "the", "tablet", "type", "changed", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L470-L497
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
StopService
func (tsv *TabletServer) StopService() { defer close(tsv.setTimeBomb()) defer tabletenv.LogError() tsv.mu.Lock() if tsv.state != StateServing && tsv.state != StateNotServing { tsv.mu.Unlock() return } tsv.setState(StateShuttingDown) tsv.mu.Unlock() log.Infof("Executing complete shutdown.") tsv.waitForShutdown() tsv.vstreamer.Close() tsv.qe.Close() tsv.se.Close() tsv.hw.Close() tsv.hr.Close() log.Infof("Shutdown complete.") tsv.transition(StateNotConnected) }
go
func (tsv *TabletServer) StopService() { defer close(tsv.setTimeBomb()) defer tabletenv.LogError() tsv.mu.Lock() if tsv.state != StateServing && tsv.state != StateNotServing { tsv.mu.Unlock() return } tsv.setState(StateShuttingDown) tsv.mu.Unlock() log.Infof("Executing complete shutdown.") tsv.waitForShutdown() tsv.vstreamer.Close() tsv.qe.Close() tsv.se.Close() tsv.hw.Close() tsv.hr.Close() log.Infof("Shutdown complete.") tsv.transition(StateNotConnected) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "StopService", "(", ")", "{", "defer", "close", "(", "tsv", ".", "setTimeBomb", "(", ")", ")", "\n", "defer", "tabletenv", ".", "LogError", "(", ")", "\n\n", "tsv", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "tsv", ".", "state", "!=", "StateServing", "&&", "tsv", ".", "state", "!=", "StateNotServing", "{", "tsv", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n", "tsv", ".", "setState", "(", "StateShuttingDown", ")", "\n", "tsv", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "log", ".", "Infof", "(", "\"", "\"", ")", "\n", "tsv", ".", "waitForShutdown", "(", ")", "\n", "tsv", ".", "vstreamer", ".", "Close", "(", ")", "\n", "tsv", ".", "qe", ".", "Close", "(", ")", "\n", "tsv", ".", "se", ".", "Close", "(", ")", "\n", "tsv", ".", "hw", ".", "Close", "(", ")", "\n", "tsv", ".", "hr", ".", "Close", "(", ")", "\n", "log", ".", "Infof", "(", "\"", "\"", ")", "\n", "tsv", ".", "transition", "(", "StateNotConnected", ")", "\n", "}" ]
// StopService shuts down the tabletserver to the uninitialized state. // It first transitions to StateShuttingDown, then waits for active // services to shut down. Then it shuts down QueryEngine. This function // should be called before process termination, or if MySQL is unreachable. // Under normal circumstances, SetServingType should be called, which will // keep QueryEngine open.
[ "StopService", "shuts", "down", "the", "tabletserver", "to", "the", "uninitialized", "state", ".", "It", "first", "transitions", "to", "StateShuttingDown", "then", "waits", "for", "active", "services", "to", "shut", "down", ".", "Then", "it", "shuts", "down", "QueryEngine", ".", "This", "function", "should", "be", "called", "before", "process", "termination", "or", "if", "MySQL", "is", "unreachable", ".", "Under", "normal", "circumstances", "SetServingType", "should", "be", "called", "which", "will", "keep", "QueryEngine", "open", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L608-L629
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
closeAll
func (tsv *TabletServer) closeAll() { tsv.messager.Close() tsv.hr.Close() tsv.hw.Close() tsv.teCtrl.StopGently() tsv.watcher.Close() tsv.updateStreamList.Stop() tsv.qe.Close() tsv.se.Close() tsv.txThrottler.Close() tsv.transition(StateNotConnected) }
go
func (tsv *TabletServer) closeAll() { tsv.messager.Close() tsv.hr.Close() tsv.hw.Close() tsv.teCtrl.StopGently() tsv.watcher.Close() tsv.updateStreamList.Stop() tsv.qe.Close() tsv.se.Close() tsv.txThrottler.Close() tsv.transition(StateNotConnected) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "closeAll", "(", ")", "{", "tsv", ".", "messager", ".", "Close", "(", ")", "\n", "tsv", ".", "hr", ".", "Close", "(", ")", "\n", "tsv", ".", "hw", ".", "Close", "(", ")", "\n", "tsv", ".", "teCtrl", ".", "StopGently", "(", ")", "\n", "tsv", ".", "watcher", ".", "Close", "(", ")", "\n", "tsv", ".", "updateStreamList", ".", "Stop", "(", ")", "\n", "tsv", ".", "qe", ".", "Close", "(", ")", "\n", "tsv", ".", "se", ".", "Close", "(", ")", "\n", "tsv", ".", "txThrottler", ".", "Close", "(", ")", "\n", "tsv", ".", "transition", "(", "StateNotConnected", ")", "\n", "}" ]
// closeAll is called if TabletServer fails to start. // It forcibly shuts down everything.
[ "closeAll", "is", "called", "if", "TabletServer", "fails", "to", "start", ".", "It", "forcibly", "shuts", "down", "everything", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L648-L659
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
CheckMySQL
func (tsv *TabletServer) CheckMySQL() { if !tsv.checkMySQLThrottler.TryAcquire() { return } go func() { defer func() { tabletenv.LogError() time.Sleep(1 * time.Second) tsv.checkMySQLThrottler.Release() }() if tsv.isMySQLReachable() { return } log.Info("Check MySQL failed. Shutting down query service") tsv.StopService() }() }
go
func (tsv *TabletServer) CheckMySQL() { if !tsv.checkMySQLThrottler.TryAcquire() { return } go func() { defer func() { tabletenv.LogError() time.Sleep(1 * time.Second) tsv.checkMySQLThrottler.Release() }() if tsv.isMySQLReachable() { return } log.Info("Check MySQL failed. Shutting down query service") tsv.StopService() }() }
[ "func", "(", "tsv", "*", "TabletServer", ")", "CheckMySQL", "(", ")", "{", "if", "!", "tsv", ".", "checkMySQLThrottler", ".", "TryAcquire", "(", ")", "{", "return", "\n", "}", "\n", "go", "func", "(", ")", "{", "defer", "func", "(", ")", "{", "tabletenv", ".", "LogError", "(", ")", "\n", "time", ".", "Sleep", "(", "1", "*", "time", ".", "Second", ")", "\n", "tsv", ".", "checkMySQLThrottler", ".", "Release", "(", ")", "\n", "}", "(", ")", "\n", "if", "tsv", ".", "isMySQLReachable", "(", ")", "{", "return", "\n", "}", "\n", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "tsv", ".", "StopService", "(", ")", "\n", "}", "(", ")", "\n", "}" ]
// CheckMySQL initiates a check to see if MySQL is reachable. // If not, it shuts down the query service. The check is rate-limited // to no more than once per second.
[ "CheckMySQL", "initiates", "a", "check", "to", "see", "if", "MySQL", "is", "reachable", ".", "If", "not", "it", "shuts", "down", "the", "query", "service", ".", "The", "check", "is", "rate", "-", "limited", "to", "no", "more", "than", "once", "per", "second", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L705-L721
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
isMySQLReachable
func (tsv *TabletServer) isMySQLReachable() bool { tsv.mu.Lock() switch tsv.state { case StateServing: // Prevent transition out of this state by // reserving a request. tsv.requests.Add(1) defer tsv.requests.Done() case StateNotServing: // Prevent transition out of this state by // temporarily switching to StateTransitioning. tsv.setState(StateTransitioning) defer func() { tsv.transition(StateNotServing) }() default: tsv.mu.Unlock() return true } tsv.mu.Unlock() return tsv.qe.IsMySQLReachable() }
go
func (tsv *TabletServer) isMySQLReachable() bool { tsv.mu.Lock() switch tsv.state { case StateServing: // Prevent transition out of this state by // reserving a request. tsv.requests.Add(1) defer tsv.requests.Done() case StateNotServing: // Prevent transition out of this state by // temporarily switching to StateTransitioning. tsv.setState(StateTransitioning) defer func() { tsv.transition(StateNotServing) }() default: tsv.mu.Unlock() return true } tsv.mu.Unlock() return tsv.qe.IsMySQLReachable() }
[ "func", "(", "tsv", "*", "TabletServer", ")", "isMySQLReachable", "(", ")", "bool", "{", "tsv", ".", "mu", ".", "Lock", "(", ")", "\n", "switch", "tsv", ".", "state", "{", "case", "StateServing", ":", "// Prevent transition out of this state by", "// reserving a request.", "tsv", ".", "requests", ".", "Add", "(", "1", ")", "\n", "defer", "tsv", ".", "requests", ".", "Done", "(", ")", "\n", "case", "StateNotServing", ":", "// Prevent transition out of this state by", "// temporarily switching to StateTransitioning.", "tsv", ".", "setState", "(", "StateTransitioning", ")", "\n", "defer", "func", "(", ")", "{", "tsv", ".", "transition", "(", "StateNotServing", ")", "\n", "}", "(", ")", "\n", "default", ":", "tsv", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "true", "\n", "}", "\n", "tsv", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "tsv", ".", "qe", ".", "IsMySQLReachable", "(", ")", "\n", "}" ]
// isMySQLReachable returns true if we can connect to MySQL. // The function returns false only if the query service is // in StateServing or StateNotServing.
[ "isMySQLReachable", "returns", "true", "if", "we", "can", "connect", "to", "MySQL", ".", "The", "function", "returns", "false", "only", "if", "the", "query", "service", "is", "in", "StateServing", "or", "StateNotServing", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L726-L747
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
ReloadSchema
func (tsv *TabletServer) ReloadSchema(ctx context.Context) error { return tsv.se.Reload(ctx) }
go
func (tsv *TabletServer) ReloadSchema(ctx context.Context) error { return tsv.se.Reload(ctx) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "ReloadSchema", "(", "ctx", "context", ".", "Context", ")", "error", "{", "return", "tsv", ".", "se", ".", "Reload", "(", "ctx", ")", "\n", "}" ]
// ReloadSchema reloads the schema.
[ "ReloadSchema", "reloads", "the", "schema", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L750-L752
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
Begin
func (tsv *TabletServer) Begin(ctx context.Context, target *querypb.Target, options *querypb.ExecuteOptions) (transactionID int64, err error) { err = tsv.execRequest( ctx, tsv.BeginTimeout.Get(), "Begin", "begin", nil, target, options, true /* isBegin */, false, /* allowOnShutdown */ func(ctx context.Context, logStats *tabletenv.LogStats) error { startTime := time.Now() if tsv.txThrottler.Throttle() { // TODO(erez): I think this should be RESOURCE_EXHAUSTED. return vterrors.Errorf(vtrpcpb.Code_UNAVAILABLE, "Transaction throttled") } var beginSQL string transactionID, beginSQL, err = tsv.teCtrl.Begin(ctx, options) logStats.TransactionID = transactionID // Record the actual statements that were executed in the logStats. // If nothing was actually executed, don't count the operation in // the tablet metrics, and clear out the logStats Method so that // handlePanicAndSendLogStats doesn't log the no-op. logStats.OriginalSQL = beginSQL if beginSQL != "" { tabletenv.QueryStats.Record("BEGIN", startTime) } else { logStats.Method = "" } return err }, ) return transactionID, err }
go
func (tsv *TabletServer) Begin(ctx context.Context, target *querypb.Target, options *querypb.ExecuteOptions) (transactionID int64, err error) { err = tsv.execRequest( ctx, tsv.BeginTimeout.Get(), "Begin", "begin", nil, target, options, true /* isBegin */, false, /* allowOnShutdown */ func(ctx context.Context, logStats *tabletenv.LogStats) error { startTime := time.Now() if tsv.txThrottler.Throttle() { // TODO(erez): I think this should be RESOURCE_EXHAUSTED. return vterrors.Errorf(vtrpcpb.Code_UNAVAILABLE, "Transaction throttled") } var beginSQL string transactionID, beginSQL, err = tsv.teCtrl.Begin(ctx, options) logStats.TransactionID = transactionID // Record the actual statements that were executed in the logStats. // If nothing was actually executed, don't count the operation in // the tablet metrics, and clear out the logStats Method so that // handlePanicAndSendLogStats doesn't log the no-op. logStats.OriginalSQL = beginSQL if beginSQL != "" { tabletenv.QueryStats.Record("BEGIN", startTime) } else { logStats.Method = "" } return err }, ) return transactionID, err }
[ "func", "(", "tsv", "*", "TabletServer", ")", "Begin", "(", "ctx", "context", ".", "Context", ",", "target", "*", "querypb", ".", "Target", ",", "options", "*", "querypb", ".", "ExecuteOptions", ")", "(", "transactionID", "int64", ",", "err", "error", ")", "{", "err", "=", "tsv", ".", "execRequest", "(", "ctx", ",", "tsv", ".", "BeginTimeout", ".", "Get", "(", ")", ",", "\"", "\"", ",", "\"", "\"", ",", "nil", ",", "target", ",", "options", ",", "true", "/* isBegin */", ",", "false", ",", "/* allowOnShutdown */", "func", "(", "ctx", "context", ".", "Context", ",", "logStats", "*", "tabletenv", ".", "LogStats", ")", "error", "{", "startTime", ":=", "time", ".", "Now", "(", ")", "\n", "if", "tsv", ".", "txThrottler", ".", "Throttle", "(", ")", "{", "// TODO(erez): I think this should be RESOURCE_EXHAUSTED.", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_UNAVAILABLE", ",", "\"", "\"", ")", "\n", "}", "\n", "var", "beginSQL", "string", "\n", "transactionID", ",", "beginSQL", ",", "err", "=", "tsv", ".", "teCtrl", ".", "Begin", "(", "ctx", ",", "options", ")", "\n", "logStats", ".", "TransactionID", "=", "transactionID", "\n\n", "// Record the actual statements that were executed in the logStats.", "// If nothing was actually executed, don't count the operation in", "// the tablet metrics, and clear out the logStats Method so that", "// handlePanicAndSendLogStats doesn't log the no-op.", "logStats", ".", "OriginalSQL", "=", "beginSQL", "\n", "if", "beginSQL", "!=", "\"", "\"", "{", "tabletenv", ".", "QueryStats", ".", "Record", "(", "\"", "\"", ",", "startTime", ")", "\n", "}", "else", "{", "logStats", ".", "Method", "=", "\"", "\"", "\n", "}", "\n", "return", "err", "\n", "}", ",", ")", "\n", "return", "transactionID", ",", "err", "\n", "}" ]
// Begin starts a new transaction. This is allowed only if the state is StateServing.
[ "Begin", "starts", "a", "new", "transaction", ".", "This", "is", "allowed", "only", "if", "the", "state", "is", "StateServing", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L773-L802
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
Rollback
func (tsv *TabletServer) Rollback(ctx context.Context, target *querypb.Target, transactionID int64) (err error) { return tsv.execRequest( ctx, tsv.QueryTimeout.Get(), "Rollback", "rollback", nil, target, nil, false /* isBegin */, true, /* allowOnShutdown */ func(ctx context.Context, logStats *tabletenv.LogStats) error { defer tabletenv.QueryStats.Record("ROLLBACK", time.Now()) logStats.TransactionID = transactionID return tsv.teCtrl.Rollback(ctx, transactionID) }, ) }
go
func (tsv *TabletServer) Rollback(ctx context.Context, target *querypb.Target, transactionID int64) (err error) { return tsv.execRequest( ctx, tsv.QueryTimeout.Get(), "Rollback", "rollback", nil, target, nil, false /* isBegin */, true, /* allowOnShutdown */ func(ctx context.Context, logStats *tabletenv.LogStats) error { defer tabletenv.QueryStats.Record("ROLLBACK", time.Now()) logStats.TransactionID = transactionID return tsv.teCtrl.Rollback(ctx, transactionID) }, ) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "Rollback", "(", "ctx", "context", ".", "Context", ",", "target", "*", "querypb", ".", "Target", ",", "transactionID", "int64", ")", "(", "err", "error", ")", "{", "return", "tsv", ".", "execRequest", "(", "ctx", ",", "tsv", ".", "QueryTimeout", ".", "Get", "(", ")", ",", "\"", "\"", ",", "\"", "\"", ",", "nil", ",", "target", ",", "nil", ",", "false", "/* isBegin */", ",", "true", ",", "/* allowOnShutdown */", "func", "(", "ctx", "context", ".", "Context", ",", "logStats", "*", "tabletenv", ".", "LogStats", ")", "error", "{", "defer", "tabletenv", ".", "QueryStats", ".", "Record", "(", "\"", "\"", ",", "time", ".", "Now", "(", ")", ")", "\n", "logStats", ".", "TransactionID", "=", "transactionID", "\n", "return", "tsv", ".", "teCtrl", ".", "Rollback", "(", "ctx", ",", "transactionID", ")", "\n", "}", ",", ")", "\n", "}" ]
// Rollback rollsback the specified transaction.
[ "Rollback", "rollsback", "the", "specified", "transaction", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L831-L842
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
Execute
func (tsv *TabletServer) Execute(ctx context.Context, target *querypb.Target, sql string, bindVariables map[string]*querypb.BindVariable, transactionID int64, options *querypb.ExecuteOptions) (result *sqltypes.Result, err error) { span, ctx := trace.NewSpan(ctx, "TabletServer.Execute") trace.AnnotateSQL(span, sql) defer span.Finish() allowOnShutdown := (transactionID != 0) err = tsv.execRequest( ctx, tsv.QueryTimeout.Get(), "Execute", sql, bindVariables, target, options, false /* isBegin */, allowOnShutdown, func(ctx context.Context, logStats *tabletenv.LogStats) error { if bindVariables == nil { bindVariables = make(map[string]*querypb.BindVariable) } query, comments := sqlparser.SplitMarginComments(sql) plan, err := tsv.qe.GetPlan(ctx, logStats, query, skipQueryPlanCache(options)) if err != nil { return err } qre := &QueryExecutor{ query: query, marginComments: comments, bindVars: bindVariables, transactionID: transactionID, options: options, plan: plan, ctx: ctx, logStats: logStats, tsv: tsv, } extras := tsv.watcher.ComputeExtras(options) result, err = qre.Execute() if err != nil { return err } result.Extras = extras result = result.StripMetadata(sqltypes.IncludeFieldsOrDefault(options)) return nil }, ) return result, err }
go
func (tsv *TabletServer) Execute(ctx context.Context, target *querypb.Target, sql string, bindVariables map[string]*querypb.BindVariable, transactionID int64, options *querypb.ExecuteOptions) (result *sqltypes.Result, err error) { span, ctx := trace.NewSpan(ctx, "TabletServer.Execute") trace.AnnotateSQL(span, sql) defer span.Finish() allowOnShutdown := (transactionID != 0) err = tsv.execRequest( ctx, tsv.QueryTimeout.Get(), "Execute", sql, bindVariables, target, options, false /* isBegin */, allowOnShutdown, func(ctx context.Context, logStats *tabletenv.LogStats) error { if bindVariables == nil { bindVariables = make(map[string]*querypb.BindVariable) } query, comments := sqlparser.SplitMarginComments(sql) plan, err := tsv.qe.GetPlan(ctx, logStats, query, skipQueryPlanCache(options)) if err != nil { return err } qre := &QueryExecutor{ query: query, marginComments: comments, bindVars: bindVariables, transactionID: transactionID, options: options, plan: plan, ctx: ctx, logStats: logStats, tsv: tsv, } extras := tsv.watcher.ComputeExtras(options) result, err = qre.Execute() if err != nil { return err } result.Extras = extras result = result.StripMetadata(sqltypes.IncludeFieldsOrDefault(options)) return nil }, ) return result, err }
[ "func", "(", "tsv", "*", "TabletServer", ")", "Execute", "(", "ctx", "context", ".", "Context", ",", "target", "*", "querypb", ".", "Target", ",", "sql", "string", ",", "bindVariables", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "transactionID", "int64", ",", "options", "*", "querypb", ".", "ExecuteOptions", ")", "(", "result", "*", "sqltypes", ".", "Result", ",", "err", "error", ")", "{", "span", ",", "ctx", ":=", "trace", ".", "NewSpan", "(", "ctx", ",", "\"", "\"", ")", "\n", "trace", ".", "AnnotateSQL", "(", "span", ",", "sql", ")", "\n", "defer", "span", ".", "Finish", "(", ")", "\n\n", "allowOnShutdown", ":=", "(", "transactionID", "!=", "0", ")", "\n", "err", "=", "tsv", ".", "execRequest", "(", "ctx", ",", "tsv", ".", "QueryTimeout", ".", "Get", "(", ")", ",", "\"", "\"", ",", "sql", ",", "bindVariables", ",", "target", ",", "options", ",", "false", "/* isBegin */", ",", "allowOnShutdown", ",", "func", "(", "ctx", "context", ".", "Context", ",", "logStats", "*", "tabletenv", ".", "LogStats", ")", "error", "{", "if", "bindVariables", "==", "nil", "{", "bindVariables", "=", "make", "(", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "\n", "}", "\n", "query", ",", "comments", ":=", "sqlparser", ".", "SplitMarginComments", "(", "sql", ")", "\n", "plan", ",", "err", ":=", "tsv", ".", "qe", ".", "GetPlan", "(", "ctx", ",", "logStats", ",", "query", ",", "skipQueryPlanCache", "(", "options", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "qre", ":=", "&", "QueryExecutor", "{", "query", ":", "query", ",", "marginComments", ":", "comments", ",", "bindVars", ":", "bindVariables", ",", "transactionID", ":", "transactionID", ",", "options", ":", "options", ",", "plan", ":", "plan", ",", "ctx", ":", "ctx", ",", "logStats", ":", "logStats", ",", "tsv", ":", "tsv", ",", "}", "\n", "extras", ":=", "tsv", ".", "watcher", ".", "ComputeExtras", "(", "options", ")", "\n", "result", ",", "err", "=", "qre", ".", "Execute", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "result", ".", "Extras", "=", "extras", "\n", "result", "=", "result", ".", "StripMetadata", "(", "sqltypes", ".", "IncludeFieldsOrDefault", "(", "options", ")", ")", "\n", "return", "nil", "\n", "}", ",", ")", "\n", "return", "result", ",", "err", "\n", "}" ]
// Execute executes the query and returns the result as response.
[ "Execute", "executes", "the", "query", "and", "returns", "the", "result", "as", "response", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L994-L1035
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
ExecuteBatch
func (tsv *TabletServer) ExecuteBatch(ctx context.Context, target *querypb.Target, queries []*querypb.BoundQuery, asTransaction bool, transactionID int64, options *querypb.ExecuteOptions) (results []sqltypes.Result, err error) { span, ctx := trace.NewSpan(ctx, "TabletServer.ExecuteBatch") defer span.Finish() if len(queries) == 0 { return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "Empty query list") } if asTransaction && transactionID != 0 { return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "cannot start a new transaction in the scope of an existing one") } if tsv.enableHotRowProtection && asTransaction { // Serialize transactions which target the same hot row range. // NOTE: We put this intentionally at this place *before* tsv.startRequest() // gets called below. Otherwise, the startRequest()/endRequest() section from // below would overlap with the startRequest()/endRequest() section executed // by tsv.beginWaitForSameRangeTransactions(). txDone, err := tsv.beginWaitForSameRangeTransactions(ctx, target, options, queries[0].Sql, queries[0].BindVariables) if err != nil { return nil, err } if txDone != nil { defer txDone() } } allowOnShutdown := (transactionID != 0) // TODO(sougou): Convert startRequest/endRequest pattern to use wrapper // function tsv.execRequest() instead. // Note that below we always return "err" right away and do not call // tsv.convertAndLogError. That's because the methods which returned "err", // e.g. tsv.Execute(), already called that function and therefore already // converted and logged the error. if err = tsv.startRequest(ctx, target, false /* isBegin */, allowOnShutdown); err != nil { return nil, err } defer tsv.endRequest(false) defer tsv.handlePanicAndSendLogStats("batch", nil, nil) if options == nil { options = &querypb.ExecuteOptions{} } // When all these conditions are met, we send the queries directly // to the MySQL without creating a transaction. This optimization // yields better throughput. // Setting ExecuteOptions_AUTOCOMMIT will get a connection out of the // pool without actually begin/commit the transaction. if (options.TransactionIsolation == querypb.ExecuteOptions_DEFAULT) && tsv.qe.autoCommit.Get() && asTransaction && tsv.qe.passthroughDMLs.Get() { options.TransactionIsolation = querypb.ExecuteOptions_AUTOCOMMIT } if asTransaction { transactionID, err = tsv.Begin(ctx, target, options) if err != nil { return nil, err } // If transaction was not committed by the end, it means // that there was an error, roll it back. defer func() { if transactionID != 0 { tsv.Rollback(ctx, target, transactionID) } }() } results = make([]sqltypes.Result, 0, len(queries)) for _, bound := range queries { localReply, err := tsv.Execute(ctx, target, bound.Sql, bound.BindVariables, transactionID, options) if err != nil { return nil, err } results = append(results, *localReply) } if asTransaction { if err = tsv.Commit(ctx, target, transactionID); err != nil { transactionID = 0 return nil, err } transactionID = 0 } return results, nil }
go
func (tsv *TabletServer) ExecuteBatch(ctx context.Context, target *querypb.Target, queries []*querypb.BoundQuery, asTransaction bool, transactionID int64, options *querypb.ExecuteOptions) (results []sqltypes.Result, err error) { span, ctx := trace.NewSpan(ctx, "TabletServer.ExecuteBatch") defer span.Finish() if len(queries) == 0 { return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "Empty query list") } if asTransaction && transactionID != 0 { return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "cannot start a new transaction in the scope of an existing one") } if tsv.enableHotRowProtection && asTransaction { // Serialize transactions which target the same hot row range. // NOTE: We put this intentionally at this place *before* tsv.startRequest() // gets called below. Otherwise, the startRequest()/endRequest() section from // below would overlap with the startRequest()/endRequest() section executed // by tsv.beginWaitForSameRangeTransactions(). txDone, err := tsv.beginWaitForSameRangeTransactions(ctx, target, options, queries[0].Sql, queries[0].BindVariables) if err != nil { return nil, err } if txDone != nil { defer txDone() } } allowOnShutdown := (transactionID != 0) // TODO(sougou): Convert startRequest/endRequest pattern to use wrapper // function tsv.execRequest() instead. // Note that below we always return "err" right away and do not call // tsv.convertAndLogError. That's because the methods which returned "err", // e.g. tsv.Execute(), already called that function and therefore already // converted and logged the error. if err = tsv.startRequest(ctx, target, false /* isBegin */, allowOnShutdown); err != nil { return nil, err } defer tsv.endRequest(false) defer tsv.handlePanicAndSendLogStats("batch", nil, nil) if options == nil { options = &querypb.ExecuteOptions{} } // When all these conditions are met, we send the queries directly // to the MySQL without creating a transaction. This optimization // yields better throughput. // Setting ExecuteOptions_AUTOCOMMIT will get a connection out of the // pool without actually begin/commit the transaction. if (options.TransactionIsolation == querypb.ExecuteOptions_DEFAULT) && tsv.qe.autoCommit.Get() && asTransaction && tsv.qe.passthroughDMLs.Get() { options.TransactionIsolation = querypb.ExecuteOptions_AUTOCOMMIT } if asTransaction { transactionID, err = tsv.Begin(ctx, target, options) if err != nil { return nil, err } // If transaction was not committed by the end, it means // that there was an error, roll it back. defer func() { if transactionID != 0 { tsv.Rollback(ctx, target, transactionID) } }() } results = make([]sqltypes.Result, 0, len(queries)) for _, bound := range queries { localReply, err := tsv.Execute(ctx, target, bound.Sql, bound.BindVariables, transactionID, options) if err != nil { return nil, err } results = append(results, *localReply) } if asTransaction { if err = tsv.Commit(ctx, target, transactionID); err != nil { transactionID = 0 return nil, err } transactionID = 0 } return results, nil }
[ "func", "(", "tsv", "*", "TabletServer", ")", "ExecuteBatch", "(", "ctx", "context", ".", "Context", ",", "target", "*", "querypb", ".", "Target", ",", "queries", "[", "]", "*", "querypb", ".", "BoundQuery", ",", "asTransaction", "bool", ",", "transactionID", "int64", ",", "options", "*", "querypb", ".", "ExecuteOptions", ")", "(", "results", "[", "]", "sqltypes", ".", "Result", ",", "err", "error", ")", "{", "span", ",", "ctx", ":=", "trace", ".", "NewSpan", "(", "ctx", ",", "\"", "\"", ")", "\n", "defer", "span", ".", "Finish", "(", ")", "\n\n", "if", "len", "(", "queries", ")", "==", "0", "{", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "asTransaction", "&&", "transactionID", "!=", "0", "{", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "tsv", ".", "enableHotRowProtection", "&&", "asTransaction", "{", "// Serialize transactions which target the same hot row range.", "// NOTE: We put this intentionally at this place *before* tsv.startRequest()", "// gets called below. Otherwise, the startRequest()/endRequest() section from", "// below would overlap with the startRequest()/endRequest() section executed", "// by tsv.beginWaitForSameRangeTransactions().", "txDone", ",", "err", ":=", "tsv", ".", "beginWaitForSameRangeTransactions", "(", "ctx", ",", "target", ",", "options", ",", "queries", "[", "0", "]", ".", "Sql", ",", "queries", "[", "0", "]", ".", "BindVariables", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "txDone", "!=", "nil", "{", "defer", "txDone", "(", ")", "\n", "}", "\n", "}", "\n\n", "allowOnShutdown", ":=", "(", "transactionID", "!=", "0", ")", "\n", "// TODO(sougou): Convert startRequest/endRequest pattern to use wrapper", "// function tsv.execRequest() instead.", "// Note that below we always return \"err\" right away and do not call", "// tsv.convertAndLogError. That's because the methods which returned \"err\",", "// e.g. tsv.Execute(), already called that function and therefore already", "// converted and logged the error.", "if", "err", "=", "tsv", ".", "startRequest", "(", "ctx", ",", "target", ",", "false", "/* isBegin */", ",", "allowOnShutdown", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "tsv", ".", "endRequest", "(", "false", ")", "\n", "defer", "tsv", ".", "handlePanicAndSendLogStats", "(", "\"", "\"", ",", "nil", ",", "nil", ")", "\n\n", "if", "options", "==", "nil", "{", "options", "=", "&", "querypb", ".", "ExecuteOptions", "{", "}", "\n", "}", "\n\n", "// When all these conditions are met, we send the queries directly", "// to the MySQL without creating a transaction. This optimization", "// yields better throughput.", "// Setting ExecuteOptions_AUTOCOMMIT will get a connection out of the", "// pool without actually begin/commit the transaction.", "if", "(", "options", ".", "TransactionIsolation", "==", "querypb", ".", "ExecuteOptions_DEFAULT", ")", "&&", "tsv", ".", "qe", ".", "autoCommit", ".", "Get", "(", ")", "&&", "asTransaction", "&&", "tsv", ".", "qe", ".", "passthroughDMLs", ".", "Get", "(", ")", "{", "options", ".", "TransactionIsolation", "=", "querypb", ".", "ExecuteOptions_AUTOCOMMIT", "\n", "}", "\n\n", "if", "asTransaction", "{", "transactionID", ",", "err", "=", "tsv", ".", "Begin", "(", "ctx", ",", "target", ",", "options", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// If transaction was not committed by the end, it means", "// that there was an error, roll it back.", "defer", "func", "(", ")", "{", "if", "transactionID", "!=", "0", "{", "tsv", ".", "Rollback", "(", "ctx", ",", "target", ",", "transactionID", ")", "\n", "}", "\n", "}", "(", ")", "\n", "}", "\n", "results", "=", "make", "(", "[", "]", "sqltypes", ".", "Result", ",", "0", ",", "len", "(", "queries", ")", ")", "\n", "for", "_", ",", "bound", ":=", "range", "queries", "{", "localReply", ",", "err", ":=", "tsv", ".", "Execute", "(", "ctx", ",", "target", ",", "bound", ".", "Sql", ",", "bound", ".", "BindVariables", ",", "transactionID", ",", "options", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "results", "=", "append", "(", "results", ",", "*", "localReply", ")", "\n", "}", "\n", "if", "asTransaction", "{", "if", "err", "=", "tsv", ".", "Commit", "(", "ctx", ",", "target", ",", "transactionID", ")", ";", "err", "!=", "nil", "{", "transactionID", "=", "0", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "transactionID", "=", "0", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// ExecuteBatch executes a group of queries and returns their results as a list. // ExecuteBatch can be called for an existing transaction, or it can be called with // the AsTransaction flag which will execute all statements inside an independent // transaction. If AsTransaction is true, TransactionId must be 0.
[ "ExecuteBatch", "executes", "a", "group", "of", "queries", "and", "returns", "their", "results", "as", "a", "list", ".", "ExecuteBatch", "can", "be", "called", "for", "an", "existing", "transaction", "or", "it", "can", "be", "called", "with", "the", "AsTransaction", "flag", "which", "will", "execute", "all", "statements", "inside", "an", "independent", "transaction", ".", "If", "AsTransaction", "is", "true", "TransactionId", "must", "be", "0", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L1074-L1158
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
BeginExecute
func (tsv *TabletServer) BeginExecute(ctx context.Context, target *querypb.Target, sql string, bindVariables map[string]*querypb.BindVariable, options *querypb.ExecuteOptions) (*sqltypes.Result, int64, error) { if tsv.enableHotRowProtection { txDone, err := tsv.beginWaitForSameRangeTransactions(ctx, target, options, sql, bindVariables) if err != nil { return nil, 0, err } if txDone != nil { defer txDone() } } transactionID, err := tsv.Begin(ctx, target, options) if err != nil { return nil, 0, err } result, err := tsv.Execute(ctx, target, sql, bindVariables, transactionID, options) return result, transactionID, err }
go
func (tsv *TabletServer) BeginExecute(ctx context.Context, target *querypb.Target, sql string, bindVariables map[string]*querypb.BindVariable, options *querypb.ExecuteOptions) (*sqltypes.Result, int64, error) { if tsv.enableHotRowProtection { txDone, err := tsv.beginWaitForSameRangeTransactions(ctx, target, options, sql, bindVariables) if err != nil { return nil, 0, err } if txDone != nil { defer txDone() } } transactionID, err := tsv.Begin(ctx, target, options) if err != nil { return nil, 0, err } result, err := tsv.Execute(ctx, target, sql, bindVariables, transactionID, options) return result, transactionID, err }
[ "func", "(", "tsv", "*", "TabletServer", ")", "BeginExecute", "(", "ctx", "context", ".", "Context", ",", "target", "*", "querypb", ".", "Target", ",", "sql", "string", ",", "bindVariables", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "options", "*", "querypb", ".", "ExecuteOptions", ")", "(", "*", "sqltypes", ".", "Result", ",", "int64", ",", "error", ")", "{", "if", "tsv", ".", "enableHotRowProtection", "{", "txDone", ",", "err", ":=", "tsv", ".", "beginWaitForSameRangeTransactions", "(", "ctx", ",", "target", ",", "options", ",", "sql", ",", "bindVariables", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n", "if", "txDone", "!=", "nil", "{", "defer", "txDone", "(", ")", "\n", "}", "\n", "}", "\n\n", "transactionID", ",", "err", ":=", "tsv", ".", "Begin", "(", "ctx", ",", "target", ",", "options", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n\n", "result", ",", "err", ":=", "tsv", ".", "Execute", "(", "ctx", ",", "target", ",", "sql", ",", "bindVariables", ",", "transactionID", ",", "options", ")", "\n", "return", "result", ",", "transactionID", ",", "err", "\n", "}" ]
// BeginExecute combines Begin and Execute.
[ "BeginExecute", "combines", "Begin", "and", "Execute", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L1161-L1179
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
MessageStream
func (tsv *TabletServer) MessageStream(ctx context.Context, target *querypb.Target, name string, callback func(*sqltypes.Result) error) (err error) { return tsv.execRequest( ctx, 0, "MessageStream", "stream", nil, target, nil, false /* isBegin */, false, /* allowOnShutdown */ func(ctx context.Context, logStats *tabletenv.LogStats) error { plan, err := tsv.qe.GetMessageStreamPlan(name) if err != nil { return err } qre := &QueryExecutor{ query: "stream from msg", plan: plan, ctx: ctx, logStats: logStats, tsv: tsv, } return qre.MessageStream(callback) }, ) }
go
func (tsv *TabletServer) MessageStream(ctx context.Context, target *querypb.Target, name string, callback func(*sqltypes.Result) error) (err error) { return tsv.execRequest( ctx, 0, "MessageStream", "stream", nil, target, nil, false /* isBegin */, false, /* allowOnShutdown */ func(ctx context.Context, logStats *tabletenv.LogStats) error { plan, err := tsv.qe.GetMessageStreamPlan(name) if err != nil { return err } qre := &QueryExecutor{ query: "stream from msg", plan: plan, ctx: ctx, logStats: logStats, tsv: tsv, } return qre.MessageStream(callback) }, ) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "MessageStream", "(", "ctx", "context", ".", "Context", ",", "target", "*", "querypb", ".", "Target", ",", "name", "string", ",", "callback", "func", "(", "*", "sqltypes", ".", "Result", ")", "error", ")", "(", "err", "error", ")", "{", "return", "tsv", ".", "execRequest", "(", "ctx", ",", "0", ",", "\"", "\"", ",", "\"", "\"", ",", "nil", ",", "target", ",", "nil", ",", "false", "/* isBegin */", ",", "false", ",", "/* allowOnShutdown */", "func", "(", "ctx", "context", ".", "Context", ",", "logStats", "*", "tabletenv", ".", "LogStats", ")", "error", "{", "plan", ",", "err", ":=", "tsv", ".", "qe", ".", "GetMessageStreamPlan", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "qre", ":=", "&", "QueryExecutor", "{", "query", ":", "\"", "\"", ",", "plan", ":", "plan", ",", "ctx", ":", "ctx", ",", "logStats", ":", "logStats", ",", "tsv", ":", "tsv", ",", "}", "\n", "return", "qre", ".", "MessageStream", "(", "callback", ")", "\n", "}", ",", ")", "\n", "}" ]
// MessageStream streams messages from the requested table.
[ "MessageStream", "streams", "messages", "from", "the", "requested", "table", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L1270-L1290
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
MessageAck
func (tsv *TabletServer) MessageAck(ctx context.Context, target *querypb.Target, name string, ids []*querypb.Value) (count int64, err error) { sids := make([]string, 0, len(ids)) for _, val := range ids { sids = append(sids, sqltypes.ProtoToValue(val).ToString()) } count, err = tsv.execDML(ctx, target, func() (string, map[string]*querypb.BindVariable, error) { return tsv.messager.GenerateAckQuery(name, sids) }) if err != nil { return 0, err } messager.MessageStats.Add([]string{name, "Acked"}, count) return count, nil }
go
func (tsv *TabletServer) MessageAck(ctx context.Context, target *querypb.Target, name string, ids []*querypb.Value) (count int64, err error) { sids := make([]string, 0, len(ids)) for _, val := range ids { sids = append(sids, sqltypes.ProtoToValue(val).ToString()) } count, err = tsv.execDML(ctx, target, func() (string, map[string]*querypb.BindVariable, error) { return tsv.messager.GenerateAckQuery(name, sids) }) if err != nil { return 0, err } messager.MessageStats.Add([]string{name, "Acked"}, count) return count, nil }
[ "func", "(", "tsv", "*", "TabletServer", ")", "MessageAck", "(", "ctx", "context", ".", "Context", ",", "target", "*", "querypb", ".", "Target", ",", "name", "string", ",", "ids", "[", "]", "*", "querypb", ".", "Value", ")", "(", "count", "int64", ",", "err", "error", ")", "{", "sids", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "ids", ")", ")", "\n", "for", "_", ",", "val", ":=", "range", "ids", "{", "sids", "=", "append", "(", "sids", ",", "sqltypes", ".", "ProtoToValue", "(", "val", ")", ".", "ToString", "(", ")", ")", "\n", "}", "\n", "count", ",", "err", "=", "tsv", ".", "execDML", "(", "ctx", ",", "target", ",", "func", "(", ")", "(", "string", ",", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "error", ")", "{", "return", "tsv", ".", "messager", ".", "GenerateAckQuery", "(", "name", ",", "sids", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "messager", ".", "MessageStats", ".", "Add", "(", "[", "]", "string", "{", "name", ",", "\"", "\"", "}", ",", "count", ")", "\n", "return", "count", ",", "nil", "\n", "}" ]
// MessageAck acks the list of messages for a given message table. // It returns the number of messages successfully acked.
[ "MessageAck", "acks", "the", "list", "of", "messages", "for", "a", "given", "message", "table", ".", "It", "returns", "the", "number", "of", "messages", "successfully", "acked", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L1294-L1307
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
PostponeMessages
func (tsv *TabletServer) PostponeMessages(ctx context.Context, target *querypb.Target, name string, ids []string) (count int64, err error) { return tsv.execDML(ctx, target, func() (string, map[string]*querypb.BindVariable, error) { return tsv.messager.GeneratePostponeQuery(name, ids) }) }
go
func (tsv *TabletServer) PostponeMessages(ctx context.Context, target *querypb.Target, name string, ids []string) (count int64, err error) { return tsv.execDML(ctx, target, func() (string, map[string]*querypb.BindVariable, error) { return tsv.messager.GeneratePostponeQuery(name, ids) }) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "PostponeMessages", "(", "ctx", "context", ".", "Context", ",", "target", "*", "querypb", ".", "Target", ",", "name", "string", ",", "ids", "[", "]", "string", ")", "(", "count", "int64", ",", "err", "error", ")", "{", "return", "tsv", ".", "execDML", "(", "ctx", ",", "target", ",", "func", "(", ")", "(", "string", ",", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "error", ")", "{", "return", "tsv", ".", "messager", ".", "GeneratePostponeQuery", "(", "name", ",", "ids", ")", "\n", "}", ")", "\n", "}" ]
// PostponeMessages postpones the list of messages for a given message table. // It returns the number of messages successfully postponed.
[ "PostponeMessages", "postpones", "the", "list", "of", "messages", "for", "a", "given", "message", "table", ".", "It", "returns", "the", "number", "of", "messages", "successfully", "postponed", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L1311-L1315
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
PurgeMessages
func (tsv *TabletServer) PurgeMessages(ctx context.Context, target *querypb.Target, name string, timeCutoff int64) (count int64, err error) { return tsv.execDML(ctx, target, func() (string, map[string]*querypb.BindVariable, error) { return tsv.messager.GeneratePurgeQuery(name, timeCutoff) }) }
go
func (tsv *TabletServer) PurgeMessages(ctx context.Context, target *querypb.Target, name string, timeCutoff int64) (count int64, err error) { return tsv.execDML(ctx, target, func() (string, map[string]*querypb.BindVariable, error) { return tsv.messager.GeneratePurgeQuery(name, timeCutoff) }) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "PurgeMessages", "(", "ctx", "context", ".", "Context", ",", "target", "*", "querypb", ".", "Target", ",", "name", "string", ",", "timeCutoff", "int64", ")", "(", "count", "int64", ",", "err", "error", ")", "{", "return", "tsv", ".", "execDML", "(", "ctx", ",", "target", ",", "func", "(", ")", "(", "string", ",", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "error", ")", "{", "return", "tsv", ".", "messager", ".", "GeneratePurgeQuery", "(", "name", ",", "timeCutoff", ")", "\n", "}", ")", "\n", "}" ]
// PurgeMessages purges messages older than specified time in Unix Nanoseconds. // It purges at most 500 messages. It returns the number of messages successfully purged.
[ "PurgeMessages", "purges", "messages", "older", "than", "specified", "time", "in", "Unix", "Nanoseconds", ".", "It", "purges", "at", "most", "500", "messages", ".", "It", "returns", "the", "number", "of", "messages", "successfully", "purged", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L1319-L1323
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
VStream
func (tsv *TabletServer) VStream(ctx context.Context, target *querypb.Target, startPos string, filter *binlogdatapb.Filter, send func([]*binlogdatapb.VEvent) error) error { if err := tsv.verifyTarget(ctx, target); err != nil { return err } return tsv.vstreamer.Stream(ctx, startPos, filter, send) }
go
func (tsv *TabletServer) VStream(ctx context.Context, target *querypb.Target, startPos string, filter *binlogdatapb.Filter, send func([]*binlogdatapb.VEvent) error) error { if err := tsv.verifyTarget(ctx, target); err != nil { return err } return tsv.vstreamer.Stream(ctx, startPos, filter, send) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "VStream", "(", "ctx", "context", ".", "Context", ",", "target", "*", "querypb", ".", "Target", ",", "startPos", "string", ",", "filter", "*", "binlogdatapb", ".", "Filter", ",", "send", "func", "(", "[", "]", "*", "binlogdatapb", ".", "VEvent", ")", "error", ")", "error", "{", "if", "err", ":=", "tsv", ".", "verifyTarget", "(", "ctx", ",", "target", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "tsv", ".", "vstreamer", ".", "Stream", "(", "ctx", ",", "startPos", ",", "filter", ",", "send", ")", "\n", "}" ]
// VStream streams VReplication events.
[ "VStream", "streams", "VReplication", "events", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L1361-L1366
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
VStreamRows
func (tsv *TabletServer) VStreamRows(ctx context.Context, target *querypb.Target, query string, lastpk *querypb.QueryResult, send func(*binlogdatapb.VStreamRowsResponse) error) error { if err := tsv.verifyTarget(ctx, target); err != nil { return err } var row []sqltypes.Value if lastpk != nil { r := sqltypes.Proto3ToResult(lastpk) if len(r.Rows) != 1 { return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unexpected lastpk input: %v", lastpk) } row = r.Rows[0] } return tsv.vstreamer.StreamRows(ctx, query, row, send) }
go
func (tsv *TabletServer) VStreamRows(ctx context.Context, target *querypb.Target, query string, lastpk *querypb.QueryResult, send func(*binlogdatapb.VStreamRowsResponse) error) error { if err := tsv.verifyTarget(ctx, target); err != nil { return err } var row []sqltypes.Value if lastpk != nil { r := sqltypes.Proto3ToResult(lastpk) if len(r.Rows) != 1 { return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unexpected lastpk input: %v", lastpk) } row = r.Rows[0] } return tsv.vstreamer.StreamRows(ctx, query, row, send) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "VStreamRows", "(", "ctx", "context", ".", "Context", ",", "target", "*", "querypb", ".", "Target", ",", "query", "string", ",", "lastpk", "*", "querypb", ".", "QueryResult", ",", "send", "func", "(", "*", "binlogdatapb", ".", "VStreamRowsResponse", ")", "error", ")", "error", "{", "if", "err", ":=", "tsv", ".", "verifyTarget", "(", "ctx", ",", "target", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "var", "row", "[", "]", "sqltypes", ".", "Value", "\n", "if", "lastpk", "!=", "nil", "{", "r", ":=", "sqltypes", ".", "Proto3ToResult", "(", "lastpk", ")", "\n", "if", "len", "(", "r", ".", "Rows", ")", "!=", "1", "{", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "lastpk", ")", "\n", "}", "\n", "row", "=", "r", ".", "Rows", "[", "0", "]", "\n", "}", "\n", "return", "tsv", ".", "vstreamer", ".", "StreamRows", "(", "ctx", ",", "query", ",", "row", ",", "send", ")", "\n", "}" ]
// VStreamRows streams rows from the specified starting point.
[ "VStreamRows", "streams", "rows", "from", "the", "specified", "starting", "point", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L1369-L1382
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
execRequest
func (tsv *TabletServer) execRequest( ctx context.Context, timeout time.Duration, requestName, sql string, bindVariables map[string]*querypb.BindVariable, target *querypb.Target, options *querypb.ExecuteOptions, isBegin, allowOnShutdown bool, exec func(ctx context.Context, logStats *tabletenv.LogStats) error, ) (err error) { span, ctx := trace.NewSpan(ctx, "TabletServer."+requestName) if options != nil { span.Annotate("isolation-level", options.TransactionIsolation) } trace.AnnotateSQL(span, sql) if target != nil { span.Annotate("cell", target.Cell) span.Annotate("shard", target.Shard) span.Annotate("keyspace", target.Keyspace) } defer span.Finish() logStats := tabletenv.NewLogStats(ctx, requestName) logStats.Target = target logStats.OriginalSQL = sql logStats.BindVariables = bindVariables defer tsv.handlePanicAndSendLogStats(sql, bindVariables, logStats) if err = tsv.startRequest(ctx, target, isBegin, allowOnShutdown); err != nil { return err } ctx, cancel := withTimeout(ctx, timeout, options) defer func() { cancel() tsv.endRequest(isBegin) }() err = exec(ctx, logStats) if err != nil { return tsv.convertAndLogError(ctx, sql, bindVariables, err, logStats) } return nil }
go
func (tsv *TabletServer) execRequest( ctx context.Context, timeout time.Duration, requestName, sql string, bindVariables map[string]*querypb.BindVariable, target *querypb.Target, options *querypb.ExecuteOptions, isBegin, allowOnShutdown bool, exec func(ctx context.Context, logStats *tabletenv.LogStats) error, ) (err error) { span, ctx := trace.NewSpan(ctx, "TabletServer."+requestName) if options != nil { span.Annotate("isolation-level", options.TransactionIsolation) } trace.AnnotateSQL(span, sql) if target != nil { span.Annotate("cell", target.Cell) span.Annotate("shard", target.Shard) span.Annotate("keyspace", target.Keyspace) } defer span.Finish() logStats := tabletenv.NewLogStats(ctx, requestName) logStats.Target = target logStats.OriginalSQL = sql logStats.BindVariables = bindVariables defer tsv.handlePanicAndSendLogStats(sql, bindVariables, logStats) if err = tsv.startRequest(ctx, target, isBegin, allowOnShutdown); err != nil { return err } ctx, cancel := withTimeout(ctx, timeout, options) defer func() { cancel() tsv.endRequest(isBegin) }() err = exec(ctx, logStats) if err != nil { return tsv.convertAndLogError(ctx, sql, bindVariables, err, logStats) } return nil }
[ "func", "(", "tsv", "*", "TabletServer", ")", "execRequest", "(", "ctx", "context", ".", "Context", ",", "timeout", "time", ".", "Duration", ",", "requestName", ",", "sql", "string", ",", "bindVariables", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "target", "*", "querypb", ".", "Target", ",", "options", "*", "querypb", ".", "ExecuteOptions", ",", "isBegin", ",", "allowOnShutdown", "bool", ",", "exec", "func", "(", "ctx", "context", ".", "Context", ",", "logStats", "*", "tabletenv", ".", "LogStats", ")", "error", ",", ")", "(", "err", "error", ")", "{", "span", ",", "ctx", ":=", "trace", ".", "NewSpan", "(", "ctx", ",", "\"", "\"", "+", "requestName", ")", "\n", "if", "options", "!=", "nil", "{", "span", ".", "Annotate", "(", "\"", "\"", ",", "options", ".", "TransactionIsolation", ")", "\n", "}", "\n", "trace", ".", "AnnotateSQL", "(", "span", ",", "sql", ")", "\n", "if", "target", "!=", "nil", "{", "span", ".", "Annotate", "(", "\"", "\"", ",", "target", ".", "Cell", ")", "\n", "span", ".", "Annotate", "(", "\"", "\"", ",", "target", ".", "Shard", ")", "\n", "span", ".", "Annotate", "(", "\"", "\"", ",", "target", ".", "Keyspace", ")", "\n", "}", "\n", "defer", "span", ".", "Finish", "(", ")", "\n\n", "logStats", ":=", "tabletenv", ".", "NewLogStats", "(", "ctx", ",", "requestName", ")", "\n", "logStats", ".", "Target", "=", "target", "\n", "logStats", ".", "OriginalSQL", "=", "sql", "\n", "logStats", ".", "BindVariables", "=", "bindVariables", "\n", "defer", "tsv", ".", "handlePanicAndSendLogStats", "(", "sql", ",", "bindVariables", ",", "logStats", ")", "\n", "if", "err", "=", "tsv", ".", "startRequest", "(", "ctx", ",", "target", ",", "isBegin", ",", "allowOnShutdown", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "ctx", ",", "cancel", ":=", "withTimeout", "(", "ctx", ",", "timeout", ",", "options", ")", "\n", "defer", "func", "(", ")", "{", "cancel", "(", ")", "\n", "tsv", ".", "endRequest", "(", "isBegin", ")", "\n", "}", "(", ")", "\n\n", "err", "=", "exec", "(", "ctx", ",", "logStats", ")", "\n", "if", "err", "!=", "nil", "{", "return", "tsv", ".", "convertAndLogError", "(", "ctx", ",", "sql", ",", "bindVariables", ",", "err", ",", "logStats", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// execRequest performs verifications, sets up the necessary environments // and calls the supplied function for executing the request.
[ "execRequest", "performs", "verifications", "sets", "up", "the", "necessary", "environments", "and", "calls", "the", "supplied", "function", "for", "executing", "the", "request", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L1449-L1487
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
verifyTarget
func (tsv *TabletServer) verifyTarget(ctx context.Context, target *querypb.Target) error { tsv.mu.Lock() defer tsv.mu.Unlock() if target != nil { // a valid target needs to be used switch { case target.Keyspace != tsv.target.Keyspace: return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "invalid keyspace %v", target.Keyspace) case target.Shard != tsv.target.Shard: return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "invalid shard %v", target.Shard) case target.TabletType != tsv.target.TabletType: for _, otherType := range tsv.alsoAllow { if target.TabletType == otherType { return nil } } return vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "invalid tablet type: %v, want: %v or %v", target.TabletType, tsv.target.TabletType, tsv.alsoAllow) } } else if !tabletenv.IsLocalContext(ctx) { return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "No target") } return nil }
go
func (tsv *TabletServer) verifyTarget(ctx context.Context, target *querypb.Target) error { tsv.mu.Lock() defer tsv.mu.Unlock() if target != nil { // a valid target needs to be used switch { case target.Keyspace != tsv.target.Keyspace: return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "invalid keyspace %v", target.Keyspace) case target.Shard != tsv.target.Shard: return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "invalid shard %v", target.Shard) case target.TabletType != tsv.target.TabletType: for _, otherType := range tsv.alsoAllow { if target.TabletType == otherType { return nil } } return vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "invalid tablet type: %v, want: %v or %v", target.TabletType, tsv.target.TabletType, tsv.alsoAllow) } } else if !tabletenv.IsLocalContext(ctx) { return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "No target") } return nil }
[ "func", "(", "tsv", "*", "TabletServer", ")", "verifyTarget", "(", "ctx", "context", ".", "Context", ",", "target", "*", "querypb", ".", "Target", ")", "error", "{", "tsv", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "tsv", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "target", "!=", "nil", "{", "// a valid target needs to be used", "switch", "{", "case", "target", ".", "Keyspace", "!=", "tsv", ".", "target", ".", "Keyspace", ":", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "target", ".", "Keyspace", ")", "\n", "case", "target", ".", "Shard", "!=", "tsv", ".", "target", ".", "Shard", ":", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "target", ".", "Shard", ")", "\n", "case", "target", ".", "TabletType", "!=", "tsv", ".", "target", ".", "TabletType", ":", "for", "_", ",", "otherType", ":=", "range", "tsv", ".", "alsoAllow", "{", "if", "target", ".", "TabletType", "==", "otherType", "{", "return", "nil", "\n", "}", "\n", "}", "\n", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_FAILED_PRECONDITION", ",", "\"", "\"", ",", "target", ".", "TabletType", ",", "tsv", ".", "target", ".", "TabletType", ",", "tsv", ".", "alsoAllow", ")", "\n", "}", "\n", "}", "else", "if", "!", "tabletenv", ".", "IsLocalContext", "(", "ctx", ")", "{", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// verifyTarget allows requests to be executed even in non-serving state.
[ "verifyTarget", "allows", "requests", "to", "be", "executed", "even", "in", "non", "-", "serving", "state", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L1490-L1513
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
validateSplitQueryParameters
func validateSplitQueryParameters( target *querypb.Target, query *querypb.BoundQuery, splitCount int64, numRowsPerQueryPart int64, algorithm querypb.SplitQueryRequest_Algorithm, ) error { // Check that the caller requested a RDONLY tablet. // Since we're called by VTGate this should not normally be violated. if target.TabletType != topodatapb.TabletType_RDONLY { return vterrors.Errorf( vtrpcpb.Code_INVALID_ARGUMENT, "SplitQuery must be called with a RDONLY tablet. TableType passed is: %v", target.TabletType) } if numRowsPerQueryPart < 0 { return vterrors.Errorf( vtrpcpb.Code_INVALID_ARGUMENT, "splitQuery: numRowsPerQueryPart must be non-negative. Got: %v. SQL: %v", numRowsPerQueryPart, queryAsString(query.Sql, query.BindVariables)) } if splitCount < 0 { return vterrors.Errorf( vtrpcpb.Code_INVALID_ARGUMENT, "splitQuery: splitCount must be non-negative. Got: %v. SQL: %v", splitCount, queryAsString(query.Sql, query.BindVariables)) } if (splitCount == 0 && numRowsPerQueryPart == 0) || (splitCount != 0 && numRowsPerQueryPart != 0) { return vterrors.Errorf( vtrpcpb.Code_INVALID_ARGUMENT, "splitQuery: exactly one of {numRowsPerQueryPart, splitCount} must be"+ " non zero. Got: numRowsPerQueryPart=%v, splitCount=%v. SQL: %v", numRowsPerQueryPart, splitCount, queryAsString(query.Sql, query.BindVariables)) } if algorithm != querypb.SplitQueryRequest_EQUAL_SPLITS && algorithm != querypb.SplitQueryRequest_FULL_SCAN { return vterrors.Errorf( vtrpcpb.Code_INVALID_ARGUMENT, "splitquery: unsupported algorithm: %v. SQL: %v", algorithm, queryAsString(query.Sql, query.BindVariables)) } return nil }
go
func validateSplitQueryParameters( target *querypb.Target, query *querypb.BoundQuery, splitCount int64, numRowsPerQueryPart int64, algorithm querypb.SplitQueryRequest_Algorithm, ) error { // Check that the caller requested a RDONLY tablet. // Since we're called by VTGate this should not normally be violated. if target.TabletType != topodatapb.TabletType_RDONLY { return vterrors.Errorf( vtrpcpb.Code_INVALID_ARGUMENT, "SplitQuery must be called with a RDONLY tablet. TableType passed is: %v", target.TabletType) } if numRowsPerQueryPart < 0 { return vterrors.Errorf( vtrpcpb.Code_INVALID_ARGUMENT, "splitQuery: numRowsPerQueryPart must be non-negative. Got: %v. SQL: %v", numRowsPerQueryPart, queryAsString(query.Sql, query.BindVariables)) } if splitCount < 0 { return vterrors.Errorf( vtrpcpb.Code_INVALID_ARGUMENT, "splitQuery: splitCount must be non-negative. Got: %v. SQL: %v", splitCount, queryAsString(query.Sql, query.BindVariables)) } if (splitCount == 0 && numRowsPerQueryPart == 0) || (splitCount != 0 && numRowsPerQueryPart != 0) { return vterrors.Errorf( vtrpcpb.Code_INVALID_ARGUMENT, "splitQuery: exactly one of {numRowsPerQueryPart, splitCount} must be"+ " non zero. Got: numRowsPerQueryPart=%v, splitCount=%v. SQL: %v", numRowsPerQueryPart, splitCount, queryAsString(query.Sql, query.BindVariables)) } if algorithm != querypb.SplitQueryRequest_EQUAL_SPLITS && algorithm != querypb.SplitQueryRequest_FULL_SCAN { return vterrors.Errorf( vtrpcpb.Code_INVALID_ARGUMENT, "splitquery: unsupported algorithm: %v. SQL: %v", algorithm, queryAsString(query.Sql, query.BindVariables)) } return nil }
[ "func", "validateSplitQueryParameters", "(", "target", "*", "querypb", ".", "Target", ",", "query", "*", "querypb", ".", "BoundQuery", ",", "splitCount", "int64", ",", "numRowsPerQueryPart", "int64", ",", "algorithm", "querypb", ".", "SplitQueryRequest_Algorithm", ",", ")", "error", "{", "// Check that the caller requested a RDONLY tablet.", "// Since we're called by VTGate this should not normally be violated.", "if", "target", ".", "TabletType", "!=", "topodatapb", ".", "TabletType_RDONLY", "{", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "target", ".", "TabletType", ")", "\n", "}", "\n", "if", "numRowsPerQueryPart", "<", "0", "{", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "numRowsPerQueryPart", ",", "queryAsString", "(", "query", ".", "Sql", ",", "query", ".", "BindVariables", ")", ")", "\n", "}", "\n", "if", "splitCount", "<", "0", "{", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "splitCount", ",", "queryAsString", "(", "query", ".", "Sql", ",", "query", ".", "BindVariables", ")", ")", "\n", "}", "\n", "if", "(", "splitCount", "==", "0", "&&", "numRowsPerQueryPart", "==", "0", ")", "||", "(", "splitCount", "!=", "0", "&&", "numRowsPerQueryPart", "!=", "0", ")", "{", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", "+", "\"", "\"", ",", "numRowsPerQueryPart", ",", "splitCount", ",", "queryAsString", "(", "query", ".", "Sql", ",", "query", ".", "BindVariables", ")", ")", "\n", "}", "\n", "if", "algorithm", "!=", "querypb", ".", "SplitQueryRequest_EQUAL_SPLITS", "&&", "algorithm", "!=", "querypb", ".", "SplitQueryRequest_FULL_SCAN", "{", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "algorithm", ",", "queryAsString", "(", "query", ".", "Sql", ",", "query", ".", "BindVariables", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validateSplitQueryParameters perform some validations on the SplitQuery parameters // returns an error that can be returned to the user if a validation fails.
[ "validateSplitQueryParameters", "perform", "some", "validations", "on", "the", "SplitQuery", "parameters", "returns", "an", "error", "that", "can", "be", "returned", "to", "the", "user", "if", "a", "validation", "fails", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L1723-L1771
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
newSplitQuerySQLExecuter
func newSplitQuerySQLExecuter( ctx context.Context, logStats *tabletenv.LogStats, tsv *TabletServer, ) (*splitQuerySQLExecuter, error) { queryExecutor := &QueryExecutor{ ctx: ctx, logStats: logStats, tsv: tsv, } result := &splitQuerySQLExecuter{ queryExecutor: queryExecutor, } var err error result.conn, err = queryExecutor.getConn() if err != nil { return nil, err } return result, nil }
go
func newSplitQuerySQLExecuter( ctx context.Context, logStats *tabletenv.LogStats, tsv *TabletServer, ) (*splitQuerySQLExecuter, error) { queryExecutor := &QueryExecutor{ ctx: ctx, logStats: logStats, tsv: tsv, } result := &splitQuerySQLExecuter{ queryExecutor: queryExecutor, } var err error result.conn, err = queryExecutor.getConn() if err != nil { return nil, err } return result, nil }
[ "func", "newSplitQuerySQLExecuter", "(", "ctx", "context", ".", "Context", ",", "logStats", "*", "tabletenv", ".", "LogStats", ",", "tsv", "*", "TabletServer", ",", ")", "(", "*", "splitQuerySQLExecuter", ",", "error", ")", "{", "queryExecutor", ":=", "&", "QueryExecutor", "{", "ctx", ":", "ctx", ",", "logStats", ":", "logStats", ",", "tsv", ":", "tsv", ",", "}", "\n", "result", ":=", "&", "splitQuerySQLExecuter", "{", "queryExecutor", ":", "queryExecutor", ",", "}", "\n", "var", "err", "error", "\n", "result", ".", "conn", ",", "err", "=", "queryExecutor", ".", "getConn", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// Constructs a new splitQuerySQLExecuter object. The 'done' method must be called on // the object after it's no longer used, to recycle the database connection.
[ "Constructs", "a", "new", "splitQuerySQLExecuter", "object", ".", "The", "done", "method", "must", "be", "called", "on", "the", "object", "after", "it", "s", "no", "longer", "used", "to", "recycle", "the", "database", "connection", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L1806-L1823
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
SQLExecute
func (se *splitQuerySQLExecuter) SQLExecute( sql string, bindVariables map[string]*querypb.BindVariable, ) (*sqltypes.Result, error) { // We need to parse the query since we're dealing with bind-vars. // TODO(erez): Add an SQLExecute() to SQLExecuterInterface that gets a parsed query so that // we don't have to parse the query again here. ast, err := sqlparser.Parse(sql) if err != nil { return nil, vterrors.Wrap(err, "splitQuerySQLExecuter: parsing sql failed with") } parsedQuery := sqlparser.NewParsedQuery(ast) // We clone "bindVariables" since fullFetch() changes it. return se.queryExecutor.dbConnFetch( se.conn, parsedQuery, sqltypes.CopyBindVariables(bindVariables), "", /* buildStreamComment */ true, /* wantfields */ ) }
go
func (se *splitQuerySQLExecuter) SQLExecute( sql string, bindVariables map[string]*querypb.BindVariable, ) (*sqltypes.Result, error) { // We need to parse the query since we're dealing with bind-vars. // TODO(erez): Add an SQLExecute() to SQLExecuterInterface that gets a parsed query so that // we don't have to parse the query again here. ast, err := sqlparser.Parse(sql) if err != nil { return nil, vterrors.Wrap(err, "splitQuerySQLExecuter: parsing sql failed with") } parsedQuery := sqlparser.NewParsedQuery(ast) // We clone "bindVariables" since fullFetch() changes it. return se.queryExecutor.dbConnFetch( se.conn, parsedQuery, sqltypes.CopyBindVariables(bindVariables), "", /* buildStreamComment */ true, /* wantfields */ ) }
[ "func", "(", "se", "*", "splitQuerySQLExecuter", ")", "SQLExecute", "(", "sql", "string", ",", "bindVariables", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "// We need to parse the query since we're dealing with bind-vars.", "// TODO(erez): Add an SQLExecute() to SQLExecuterInterface that gets a parsed query so that", "// we don't have to parse the query again here.", "ast", ",", "err", ":=", "sqlparser", ".", "Parse", "(", "sql", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "vterrors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "parsedQuery", ":=", "sqlparser", ".", "NewParsedQuery", "(", "ast", ")", "\n\n", "// We clone \"bindVariables\" since fullFetch() changes it.", "return", "se", ".", "queryExecutor", ".", "dbConnFetch", "(", "se", ".", "conn", ",", "parsedQuery", ",", "sqltypes", ".", "CopyBindVariables", "(", "bindVariables", ")", ",", "\"", "\"", ",", "/* buildStreamComment */", "true", ",", "/* wantfields */", ")", "\n", "}" ]
// SQLExecute is part of the SQLExecuter interface.
[ "SQLExecute", "is", "part", "of", "the", "SQLExecuter", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L1830-L1850
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
StreamHealth
func (tsv *TabletServer) StreamHealth(ctx context.Context, callback func(*querypb.StreamHealthResponse) error) error { tsv.streamHealthMutex.Lock() shr := tsv.lastStreamHealthResponse shrExpiration := tsv.lastStreamHealthExpiration tsv.streamHealthMutex.Unlock() // Send current state immediately. if shr != nil && time.Now().Before(shrExpiration) { if err := callback(shr); err != nil { if err == io.EOF { return nil } return err } } // Broadcast periodic updates. id, ch := tsv.streamHealthRegister() defer tsv.streamHealthUnregister(id) for { select { case <-ctx.Done(): return nil case shr = <-ch: } if err := callback(shr); err != nil { if err == io.EOF { return nil } return err } } }
go
func (tsv *TabletServer) StreamHealth(ctx context.Context, callback func(*querypb.StreamHealthResponse) error) error { tsv.streamHealthMutex.Lock() shr := tsv.lastStreamHealthResponse shrExpiration := tsv.lastStreamHealthExpiration tsv.streamHealthMutex.Unlock() // Send current state immediately. if shr != nil && time.Now().Before(shrExpiration) { if err := callback(shr); err != nil { if err == io.EOF { return nil } return err } } // Broadcast periodic updates. id, ch := tsv.streamHealthRegister() defer tsv.streamHealthUnregister(id) for { select { case <-ctx.Done(): return nil case shr = <-ch: } if err := callback(shr); err != nil { if err == io.EOF { return nil } return err } } }
[ "func", "(", "tsv", "*", "TabletServer", ")", "StreamHealth", "(", "ctx", "context", ".", "Context", ",", "callback", "func", "(", "*", "querypb", ".", "StreamHealthResponse", ")", "error", ")", "error", "{", "tsv", ".", "streamHealthMutex", ".", "Lock", "(", ")", "\n", "shr", ":=", "tsv", ".", "lastStreamHealthResponse", "\n", "shrExpiration", ":=", "tsv", ".", "lastStreamHealthExpiration", "\n", "tsv", ".", "streamHealthMutex", ".", "Unlock", "(", ")", "\n", "// Send current state immediately.", "if", "shr", "!=", "nil", "&&", "time", ".", "Now", "(", ")", ".", "Before", "(", "shrExpiration", ")", "{", "if", "err", ":=", "callback", "(", "shr", ")", ";", "err", "!=", "nil", "{", "if", "err", "==", "io", ".", "EOF", "{", "return", "nil", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "}", "\n\n", "// Broadcast periodic updates.", "id", ",", "ch", ":=", "tsv", ".", "streamHealthRegister", "(", ")", "\n", "defer", "tsv", ".", "streamHealthUnregister", "(", "id", ")", "\n\n", "for", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "nil", "\n", "case", "shr", "=", "<-", "ch", ":", "}", "\n", "if", "err", ":=", "callback", "(", "shr", ")", ";", "err", "!=", "nil", "{", "if", "err", "==", "io", ".", "EOF", "{", "return", "nil", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "}", "\n", "}" ]
// StreamHealth streams the health status to callback. // At the beginning, if TabletServer has a valid health // state, that response is immediately sent.
[ "StreamHealth", "streams", "the", "health", "status", "to", "callback", ".", "At", "the", "beginning", "if", "TabletServer", "has", "a", "valid", "health", "state", "that", "response", "is", "immediately", "sent", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L1870-L1902
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
BroadcastHealth
func (tsv *TabletServer) BroadcastHealth(terTimestamp int64, stats *querypb.RealtimeStats, maxCache time.Duration) { tsv.mu.Lock() target := tsv.target tsv.mu.Unlock() shr := &querypb.StreamHealthResponse{ Target: &target, TabletAlias: &tsv.alias, Serving: tsv.IsServing(), TabletExternallyReparentedTimestamp: terTimestamp, RealtimeStats: stats, } tsv.streamHealthMutex.Lock() defer tsv.streamHealthMutex.Unlock() for _, c := range tsv.streamHealthMap { // Do not block on any write. select { case c <- shr: default: } } tsv.lastStreamHealthResponse = shr tsv.lastStreamHealthExpiration = time.Now().Add(maxCache) }
go
func (tsv *TabletServer) BroadcastHealth(terTimestamp int64, stats *querypb.RealtimeStats, maxCache time.Duration) { tsv.mu.Lock() target := tsv.target tsv.mu.Unlock() shr := &querypb.StreamHealthResponse{ Target: &target, TabletAlias: &tsv.alias, Serving: tsv.IsServing(), TabletExternallyReparentedTimestamp: terTimestamp, RealtimeStats: stats, } tsv.streamHealthMutex.Lock() defer tsv.streamHealthMutex.Unlock() for _, c := range tsv.streamHealthMap { // Do not block on any write. select { case c <- shr: default: } } tsv.lastStreamHealthResponse = shr tsv.lastStreamHealthExpiration = time.Now().Add(maxCache) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "BroadcastHealth", "(", "terTimestamp", "int64", ",", "stats", "*", "querypb", ".", "RealtimeStats", ",", "maxCache", "time", ".", "Duration", ")", "{", "tsv", ".", "mu", ".", "Lock", "(", ")", "\n", "target", ":=", "tsv", ".", "target", "\n", "tsv", ".", "mu", ".", "Unlock", "(", ")", "\n", "shr", ":=", "&", "querypb", ".", "StreamHealthResponse", "{", "Target", ":", "&", "target", ",", "TabletAlias", ":", "&", "tsv", ".", "alias", ",", "Serving", ":", "tsv", ".", "IsServing", "(", ")", ",", "TabletExternallyReparentedTimestamp", ":", "terTimestamp", ",", "RealtimeStats", ":", "stats", ",", "}", "\n\n", "tsv", ".", "streamHealthMutex", ".", "Lock", "(", ")", "\n", "defer", "tsv", ".", "streamHealthMutex", ".", "Unlock", "(", ")", "\n", "for", "_", ",", "c", ":=", "range", "tsv", ".", "streamHealthMap", "{", "// Do not block on any write.", "select", "{", "case", "c", "<-", "shr", ":", "default", ":", "}", "\n", "}", "\n", "tsv", ".", "lastStreamHealthResponse", "=", "shr", "\n", "tsv", ".", "lastStreamHealthExpiration", "=", "time", ".", "Now", "(", ")", ".", "Add", "(", "maxCache", ")", "\n", "}" ]
// BroadcastHealth will broadcast the current health to all listeners
[ "BroadcastHealth", "will", "broadcast", "the", "current", "health", "to", "all", "listeners" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L1922-L1945
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
HeartbeatLag
func (tsv *TabletServer) HeartbeatLag() (time.Duration, error) { // If the reader is closed and we are not serving, then the // query service is shutdown and this value is not being updated. // We return healthy from this as a signal to the healtcheck to attempt // to start the query service again. If the query service fails to start // with an error, then that error is be reported by the healthcheck. if !tsv.hr.IsOpen() && !tsv.IsServing() { return 0, nil } return tsv.hr.GetLatest() }
go
func (tsv *TabletServer) HeartbeatLag() (time.Duration, error) { // If the reader is closed and we are not serving, then the // query service is shutdown and this value is not being updated. // We return healthy from this as a signal to the healtcheck to attempt // to start the query service again. If the query service fails to start // with an error, then that error is be reported by the healthcheck. if !tsv.hr.IsOpen() && !tsv.IsServing() { return 0, nil } return tsv.hr.GetLatest() }
[ "func", "(", "tsv", "*", "TabletServer", ")", "HeartbeatLag", "(", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "// If the reader is closed and we are not serving, then the", "// query service is shutdown and this value is not being updated.", "// We return healthy from this as a signal to the healtcheck to attempt", "// to start the query service again. If the query service fails to start", "// with an error, then that error is be reported by the healthcheck.", "if", "!", "tsv", ".", "hr", ".", "IsOpen", "(", ")", "&&", "!", "tsv", ".", "IsServing", "(", ")", "{", "return", "0", ",", "nil", "\n", "}", "\n", "return", "tsv", ".", "hr", ".", "GetLatest", "(", ")", "\n", "}" ]
// HeartbeatLag returns the current lag as calculated by the heartbeat // package, if heartbeat is enabled. Otherwise returns 0.
[ "HeartbeatLag", "returns", "the", "current", "lag", "as", "calculated", "by", "the", "heartbeat", "package", "if", "heartbeat", "is", "enabled", ".", "Otherwise", "returns", "0", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L1949-L1959
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
UpdateStream
func (tsv *TabletServer) UpdateStream(ctx context.Context, target *querypb.Target, position string, timestamp int64, callback func(*querypb.StreamEvent) error) error { // Parse the position if needed. var p mysql.Position var err error if timestamp == 0 { if position != "" { p, err = mysql.DecodePosition(position) if err != nil { return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "cannot parse position: %v", err) } } } else if position != "" { return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "at most one of position and timestamp should be specified") } // Validate proper target is used. if err = tsv.startRequest(ctx, target, false /* isBegin */, false /* allowOnShutdown */); err != nil { return err } defer tsv.endRequest(false) s := binlog.NewEventStreamer(tsv.dbconfigs.DbaWithDB(), tsv.se, p, timestamp, callback) // Create a cancelable wrapping context. streamCtx, streamCancel := context.WithCancel(ctx) i := tsv.updateStreamList.Add(streamCancel) defer tsv.updateStreamList.Delete(i) // And stream with it. err = s.Stream(streamCtx) switch err { case binlog.ErrBinlogUnavailable: return vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "%v", err) case nil, io.EOF: return nil default: return vterrors.Errorf(vtrpcpb.Code_UNKNOWN, "%v", err) } }
go
func (tsv *TabletServer) UpdateStream(ctx context.Context, target *querypb.Target, position string, timestamp int64, callback func(*querypb.StreamEvent) error) error { // Parse the position if needed. var p mysql.Position var err error if timestamp == 0 { if position != "" { p, err = mysql.DecodePosition(position) if err != nil { return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "cannot parse position: %v", err) } } } else if position != "" { return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "at most one of position and timestamp should be specified") } // Validate proper target is used. if err = tsv.startRequest(ctx, target, false /* isBegin */, false /* allowOnShutdown */); err != nil { return err } defer tsv.endRequest(false) s := binlog.NewEventStreamer(tsv.dbconfigs.DbaWithDB(), tsv.se, p, timestamp, callback) // Create a cancelable wrapping context. streamCtx, streamCancel := context.WithCancel(ctx) i := tsv.updateStreamList.Add(streamCancel) defer tsv.updateStreamList.Delete(i) // And stream with it. err = s.Stream(streamCtx) switch err { case binlog.ErrBinlogUnavailable: return vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "%v", err) case nil, io.EOF: return nil default: return vterrors.Errorf(vtrpcpb.Code_UNKNOWN, "%v", err) } }
[ "func", "(", "tsv", "*", "TabletServer", ")", "UpdateStream", "(", "ctx", "context", ".", "Context", ",", "target", "*", "querypb", ".", "Target", ",", "position", "string", ",", "timestamp", "int64", ",", "callback", "func", "(", "*", "querypb", ".", "StreamEvent", ")", "error", ")", "error", "{", "// Parse the position if needed.", "var", "p", "mysql", ".", "Position", "\n", "var", "err", "error", "\n", "if", "timestamp", "==", "0", "{", "if", "position", "!=", "\"", "\"", "{", "p", ",", "err", "=", "mysql", ".", "DecodePosition", "(", "position", ")", "\n", "if", "err", "!=", "nil", "{", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "else", "if", "position", "!=", "\"", "\"", "{", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Validate proper target is used.", "if", "err", "=", "tsv", ".", "startRequest", "(", "ctx", ",", "target", ",", "false", "/* isBegin */", ",", "false", "/* allowOnShutdown */", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "tsv", ".", "endRequest", "(", "false", ")", "\n\n", "s", ":=", "binlog", ".", "NewEventStreamer", "(", "tsv", ".", "dbconfigs", ".", "DbaWithDB", "(", ")", ",", "tsv", ".", "se", ",", "p", ",", "timestamp", ",", "callback", ")", "\n\n", "// Create a cancelable wrapping context.", "streamCtx", ",", "streamCancel", ":=", "context", ".", "WithCancel", "(", "ctx", ")", "\n", "i", ":=", "tsv", ".", "updateStreamList", ".", "Add", "(", "streamCancel", ")", "\n", "defer", "tsv", ".", "updateStreamList", ".", "Delete", "(", "i", ")", "\n\n", "// And stream with it.", "err", "=", "s", ".", "Stream", "(", "streamCtx", ")", "\n", "switch", "err", "{", "case", "binlog", ".", "ErrBinlogUnavailable", ":", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_FAILED_PRECONDITION", ",", "\"", "\"", ",", "err", ")", "\n", "case", "nil", ",", "io", ".", "EOF", ":", "return", "nil", "\n", "default", ":", "return", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_UNKNOWN", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// UpdateStream streams binlog events.
[ "UpdateStream", "streams", "binlog", "events", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L1967-L2005
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
HandlePanic
func (tsv *TabletServer) HandlePanic(err *error) { if x := recover(); x != nil { *err = fmt.Errorf("uncaught panic: %v\n. Stack-trace:\n%s", x, tb.Stack(4)) } }
go
func (tsv *TabletServer) HandlePanic(err *error) { if x := recover(); x != nil { *err = fmt.Errorf("uncaught panic: %v\n. Stack-trace:\n%s", x, tb.Stack(4)) } }
[ "func", "(", "tsv", "*", "TabletServer", ")", "HandlePanic", "(", "err", "*", "error", ")", "{", "if", "x", ":=", "recover", "(", ")", ";", "x", "!=", "nil", "{", "*", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\\n", "\\n", "\"", ",", "x", ",", "tb", ".", "Stack", "(", "4", ")", ")", "\n", "}", "\n", "}" ]
// HandlePanic is part of the queryservice.QueryService interface
[ "HandlePanic", "is", "part", "of", "the", "queryservice", ".", "QueryService", "interface" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L2008-L2012
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
SetPoolSize
func (tsv *TabletServer) SetPoolSize(val int) { tsv.qe.conns.SetCapacity(val) }
go
func (tsv *TabletServer) SetPoolSize(val int) { tsv.qe.conns.SetCapacity(val) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "SetPoolSize", "(", "val", "int", ")", "{", "tsv", ".", "qe", ".", "conns", ".", "SetCapacity", "(", "val", ")", "\n", "}" ]
// SetPoolSize changes the pool size to the specified value. // This function should only be used for testing.
[ "SetPoolSize", "changes", "the", "pool", "size", "to", "the", "specified", "value", ".", "This", "function", "should", "only", "be", "used", "for", "testing", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L2113-L2115
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
SetStreamPoolSize
func (tsv *TabletServer) SetStreamPoolSize(val int) { tsv.qe.streamConns.SetCapacity(val) }
go
func (tsv *TabletServer) SetStreamPoolSize(val int) { tsv.qe.streamConns.SetCapacity(val) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "SetStreamPoolSize", "(", "val", "int", ")", "{", "tsv", ".", "qe", ".", "streamConns", ".", "SetCapacity", "(", "val", ")", "\n", "}" ]
// SetStreamPoolSize changes the pool size to the specified value. // This function should only be used for testing.
[ "SetStreamPoolSize", "changes", "the", "pool", "size", "to", "the", "specified", "value", ".", "This", "function", "should", "only", "be", "used", "for", "testing", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L2124-L2126
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
SetTxPoolSize
func (tsv *TabletServer) SetTxPoolSize(val int) { tsv.te.txPool.conns.SetCapacity(val) }
go
func (tsv *TabletServer) SetTxPoolSize(val int) { tsv.te.txPool.conns.SetCapacity(val) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "SetTxPoolSize", "(", "val", "int", ")", "{", "tsv", ".", "te", ".", "txPool", ".", "conns", ".", "SetCapacity", "(", "val", ")", "\n", "}" ]
// SetTxPoolSize changes the tx pool size to the specified value. // This function should only be used for testing.
[ "SetTxPoolSize", "changes", "the", "tx", "pool", "size", "to", "the", "specified", "value", ".", "This", "function", "should", "only", "be", "used", "for", "testing", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L2135-L2137
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
TxPoolSize
func (tsv *TabletServer) TxPoolSize() int { return int(tsv.te.txPool.conns.Capacity()) }
go
func (tsv *TabletServer) TxPoolSize() int { return int(tsv.te.txPool.conns.Capacity()) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "TxPoolSize", "(", ")", "int", "{", "return", "int", "(", "tsv", ".", "te", ".", "txPool", ".", "conns", ".", "Capacity", "(", ")", ")", "\n", "}" ]
// TxPoolSize returns the tx pool size.
[ "TxPoolSize", "returns", "the", "tx", "pool", "size", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L2140-L2142
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
SetTxTimeout
func (tsv *TabletServer) SetTxTimeout(val time.Duration) { tsv.te.txPool.SetTimeout(val) }
go
func (tsv *TabletServer) SetTxTimeout(val time.Duration) { tsv.te.txPool.SetTimeout(val) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "SetTxTimeout", "(", "val", "time", ".", "Duration", ")", "{", "tsv", ".", "te", ".", "txPool", ".", "SetTimeout", "(", "val", ")", "\n", "}" ]
// SetTxTimeout changes the transaction timeout to the specified value. // This function should only be used for testing.
[ "SetTxTimeout", "changes", "the", "transaction", "timeout", "to", "the", "specified", "value", ".", "This", "function", "should", "only", "be", "used", "for", "testing", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L2146-L2148
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
SetAutoCommit
func (tsv *TabletServer) SetAutoCommit(auto bool) { tsv.qe.autoCommit.Set(auto) }
go
func (tsv *TabletServer) SetAutoCommit(auto bool) { tsv.qe.autoCommit.Set(auto) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "SetAutoCommit", "(", "auto", "bool", ")", "{", "tsv", ".", "qe", ".", "autoCommit", ".", "Set", "(", "auto", ")", "\n", "}" ]
// SetAutoCommit sets autocommit on or off. // This function should only be used for testing.
[ "SetAutoCommit", "sets", "autocommit", "on", "or", "off", ".", "This", "function", "should", "only", "be", "used", "for", "testing", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L2168-L2170
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
SetMaxResultSize
func (tsv *TabletServer) SetMaxResultSize(val int) { tsv.qe.maxResultSize.Set(int64(val)) }
go
func (tsv *TabletServer) SetMaxResultSize(val int) { tsv.qe.maxResultSize.Set(int64(val)) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "SetMaxResultSize", "(", "val", "int", ")", "{", "tsv", ".", "qe", ".", "maxResultSize", ".", "Set", "(", "int64", "(", "val", ")", ")", "\n", "}" ]
// SetMaxResultSize changes the max result size to the specified value. // This function should only be used for testing.
[ "SetMaxResultSize", "changes", "the", "max", "result", "size", "to", "the", "specified", "value", ".", "This", "function", "should", "only", "be", "used", "for", "testing", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L2174-L2176
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
SetWarnResultSize
func (tsv *TabletServer) SetWarnResultSize(val int) { tsv.qe.warnResultSize.Set(int64(val)) }
go
func (tsv *TabletServer) SetWarnResultSize(val int) { tsv.qe.warnResultSize.Set(int64(val)) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "SetWarnResultSize", "(", "val", "int", ")", "{", "tsv", ".", "qe", ".", "warnResultSize", ".", "Set", "(", "int64", "(", "val", ")", ")", "\n", "}" ]
// SetWarnResultSize changes the warn result size to the specified value. // This function should only be used for testing.
[ "SetWarnResultSize", "changes", "the", "warn", "result", "size", "to", "the", "specified", "value", ".", "This", "function", "should", "only", "be", "used", "for", "testing", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L2185-L2187
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
SetMaxDMLRows
func (tsv *TabletServer) SetMaxDMLRows(val int) { tsv.qe.maxDMLRows.Set(int64(val)) }
go
func (tsv *TabletServer) SetMaxDMLRows(val int) { tsv.qe.maxDMLRows.Set(int64(val)) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "SetMaxDMLRows", "(", "val", "int", ")", "{", "tsv", ".", "qe", ".", "maxDMLRows", ".", "Set", "(", "int64", "(", "val", ")", ")", "\n", "}" ]
// SetMaxDMLRows changes the max result size to the specified value. // This function should only be used for testing.
[ "SetMaxDMLRows", "changes", "the", "max", "result", "size", "to", "the", "specified", "value", ".", "This", "function", "should", "only", "be", "used", "for", "testing", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L2196-L2198
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
SetPassthroughDMLs
func (tsv *TabletServer) SetPassthroughDMLs(val bool) { planbuilder.PassthroughDMLs = true tsv.qe.passthroughDMLs.Set(val) }
go
func (tsv *TabletServer) SetPassthroughDMLs(val bool) { planbuilder.PassthroughDMLs = true tsv.qe.passthroughDMLs.Set(val) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "SetPassthroughDMLs", "(", "val", "bool", ")", "{", "planbuilder", ".", "PassthroughDMLs", "=", "true", "\n", "tsv", ".", "qe", ".", "passthroughDMLs", ".", "Set", "(", "val", ")", "\n", "}" ]
// SetPassthroughDMLs changes the setting to pass through all DMLs // It should only be used for testing
[ "SetPassthroughDMLs", "changes", "the", "setting", "to", "pass", "through", "all", "DMLs", "It", "should", "only", "be", "used", "for", "testing" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L2207-L2210
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
SetQueryPoolTimeout
func (tsv *TabletServer) SetQueryPoolTimeout(val time.Duration) { tsv.qe.connTimeout.Set(val) }
go
func (tsv *TabletServer) SetQueryPoolTimeout(val time.Duration) { tsv.qe.connTimeout.Set(val) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "SetQueryPoolTimeout", "(", "val", "time", ".", "Duration", ")", "{", "tsv", ".", "qe", ".", "connTimeout", ".", "Set", "(", "val", ")", "\n", "}" ]
// SetQueryPoolTimeout changes the timeout to get a connection from the // query pool // This function should only be used for testing.
[ "SetQueryPoolTimeout", "changes", "the", "timeout", "to", "get", "a", "connection", "from", "the", "query", "pool", "This", "function", "should", "only", "be", "used", "for", "testing", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L2221-L2223
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
SetQueryPoolWaiterCap
func (tsv *TabletServer) SetQueryPoolWaiterCap(val int64) { tsv.qe.queryPoolWaiterCap.Set(val) }
go
func (tsv *TabletServer) SetQueryPoolWaiterCap(val int64) { tsv.qe.queryPoolWaiterCap.Set(val) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "SetQueryPoolWaiterCap", "(", "val", "int64", ")", "{", "tsv", ".", "qe", ".", "queryPoolWaiterCap", ".", "Set", "(", "val", ")", "\n", "}" ]
// SetQueryPoolWaiterCap changes the limit on the number of queries that can be // waiting for a connection from the pool // This function should only be used for testing.
[ "SetQueryPoolWaiterCap", "changes", "the", "limit", "on", "the", "number", "of", "queries", "that", "can", "be", "waiting", "for", "a", "connection", "from", "the", "pool", "This", "function", "should", "only", "be", "used", "for", "testing", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L2235-L2237
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
SetTxPoolWaiterCap
func (tsv *TabletServer) SetTxPoolWaiterCap(val int64) { tsv.te.txPool.waiterCap.Set(val) }
go
func (tsv *TabletServer) SetTxPoolWaiterCap(val int64) { tsv.te.txPool.waiterCap.Set(val) }
[ "func", "(", "tsv", "*", "TabletServer", ")", "SetTxPoolWaiterCap", "(", "val", "int64", ")", "{", "tsv", ".", "te", ".", "txPool", ".", "waiterCap", ".", "Set", "(", "val", ")", "\n", "}" ]
// SetTxPoolWaiterCap changes the limit on the number of queries that can be // waiting for a connection from the pool // This function should only be used for testing.
[ "SetTxPoolWaiterCap", "changes", "the", "limit", "on", "the", "number", "of", "queries", "that", "can", "be", "waiting", "for", "a", "connection", "from", "the", "pool", "This", "function", "should", "only", "be", "used", "for", "testing", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L2249-L2251
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
queryAsString
func queryAsString(sql string, bindVariables map[string]*querypb.BindVariable) string { buf := &bytes.Buffer{} fmt.Fprintf(buf, "Sql: %q", sql) fmt.Fprintf(buf, ", BindVars: {") var keys []string for key := range bindVariables { keys = append(keys, key) } sort.Strings(keys) var valString string for _, key := range keys { valString = fmt.Sprintf("%v", bindVariables[key]) fmt.Fprintf(buf, "%s: %q", key, valString) } fmt.Fprintf(buf, "}") return buf.String() }
go
func queryAsString(sql string, bindVariables map[string]*querypb.BindVariable) string { buf := &bytes.Buffer{} fmt.Fprintf(buf, "Sql: %q", sql) fmt.Fprintf(buf, ", BindVars: {") var keys []string for key := range bindVariables { keys = append(keys, key) } sort.Strings(keys) var valString string for _, key := range keys { valString = fmt.Sprintf("%v", bindVariables[key]) fmt.Fprintf(buf, "%s: %q", key, valString) } fmt.Fprintf(buf, "}") return buf.String() }
[ "func", "queryAsString", "(", "sql", "string", ",", "bindVariables", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "string", "{", "buf", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "fmt", ".", "Fprintf", "(", "buf", ",", "\"", "\"", ",", "sql", ")", "\n", "fmt", ".", "Fprintf", "(", "buf", ",", "\"", "\"", ")", "\n", "var", "keys", "[", "]", "string", "\n", "for", "key", ":=", "range", "bindVariables", "{", "keys", "=", "append", "(", "keys", ",", "key", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "keys", ")", "\n", "var", "valString", "string", "\n", "for", "_", ",", "key", ":=", "range", "keys", "{", "valString", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "bindVariables", "[", "key", "]", ")", "\n", "fmt", ".", "Fprintf", "(", "buf", ",", "\"", "\"", ",", "key", ",", "valString", ")", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "buf", ",", "\"", "\"", ")", "\n", "return", "buf", ".", "String", "(", ")", "\n", "}" ]
// queryAsString returns a readable version of query+bind variables.
[ "queryAsString", "returns", "a", "readable", "version", "of", "query", "+", "bind", "variables", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L2268-L2284
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
withTimeout
func withTimeout(ctx context.Context, timeout time.Duration, options *querypb.ExecuteOptions) (context.Context, context.CancelFunc) { if timeout == 0 || options.GetWorkload() == querypb.ExecuteOptions_DBA || tabletenv.IsLocalContext(ctx) { return ctx, func() {} } return context.WithTimeout(ctx, timeout) }
go
func withTimeout(ctx context.Context, timeout time.Duration, options *querypb.ExecuteOptions) (context.Context, context.CancelFunc) { if timeout == 0 || options.GetWorkload() == querypb.ExecuteOptions_DBA || tabletenv.IsLocalContext(ctx) { return ctx, func() {} } return context.WithTimeout(ctx, timeout) }
[ "func", "withTimeout", "(", "ctx", "context", ".", "Context", ",", "timeout", "time", ".", "Duration", ",", "options", "*", "querypb", ".", "ExecuteOptions", ")", "(", "context", ".", "Context", ",", "context", ".", "CancelFunc", ")", "{", "if", "timeout", "==", "0", "||", "options", ".", "GetWorkload", "(", ")", "==", "querypb", ".", "ExecuteOptions_DBA", "||", "tabletenv", ".", "IsLocalContext", "(", "ctx", ")", "{", "return", "ctx", ",", "func", "(", ")", "{", "}", "\n", "}", "\n", "return", "context", ".", "WithTimeout", "(", "ctx", ",", "timeout", ")", "\n", "}" ]
// withTimeout returns a context based on the specified timeout. // If the context is local or if timeout is 0, the // original context is returned as is.
[ "withTimeout", "returns", "a", "context", "based", "on", "the", "specified", "timeout", ".", "If", "the", "context", "is", "local", "or", "if", "timeout", "is", "0", "the", "original", "context", "is", "returned", "as", "is", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L2289-L2294
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletserver.go
skipQueryPlanCache
func skipQueryPlanCache(options *querypb.ExecuteOptions) bool { if options == nil { return false } return options.SkipQueryPlanCache }
go
func skipQueryPlanCache(options *querypb.ExecuteOptions) bool { if options == nil { return false } return options.SkipQueryPlanCache }
[ "func", "skipQueryPlanCache", "(", "options", "*", "querypb", ".", "ExecuteOptions", ")", "bool", "{", "if", "options", "==", "nil", "{", "return", "false", "\n", "}", "\n", "return", "options", ".", "SkipQueryPlanCache", "\n", "}" ]
// skipQueryPlanCache returns true if the query plan should be cached
[ "skipQueryPlanCache", "returns", "true", "if", "the", "query", "plan", "should", "be", "cached" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletserver.go#L2297-L2302
train
vitessio/vitess
go/vt/mysqlctl/cephbackupstorage/ceph.go
AbortBackup
func (bh *CephBackupHandle) AbortBackup(ctx context.Context) error { if bh.readOnly { return fmt.Errorf("AbortBackup cannot be called on read-only backup") } return bh.bs.RemoveBackup(ctx, bh.dir, bh.name) }
go
func (bh *CephBackupHandle) AbortBackup(ctx context.Context) error { if bh.readOnly { return fmt.Errorf("AbortBackup cannot be called on read-only backup") } return bh.bs.RemoveBackup(ctx, bh.dir, bh.name) }
[ "func", "(", "bh", "*", "CephBackupHandle", ")", "AbortBackup", "(", "ctx", "context", ".", "Context", ")", "error", "{", "if", "bh", ".", "readOnly", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "bh", ".", "bs", ".", "RemoveBackup", "(", "ctx", ",", "bh", ".", "dir", ",", "bh", ".", "name", ")", "\n", "}" ]
// AbortBackup implements BackupHandle.
[ "AbortBackup", "implements", "BackupHandle", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/cephbackupstorage/ceph.go#L114-L119
train
vitessio/vitess
go/vt/mysqlctl/cephbackupstorage/ceph.go
client
func (bs *CephBackupStorage) client() (*minio.Client, error) { bs.mu.Lock() defer bs.mu.Unlock() if bs._client == nil { configFile, err := os.Open(*configFilePath) if err != nil { return nil, fmt.Errorf("file not present : %v", err) } defer configFile.Close() jsonParser := json.NewDecoder(configFile) if err = jsonParser.Decode(&storageConfig); err != nil { return nil, fmt.Errorf("error parsing the json file : %v", err) } accessKey := storageConfig.AccessKey secretKey := storageConfig.SecretKey url := storageConfig.EndPoint useSSL := storageConfig.UseSSL client, err := minio.NewV2(url, accessKey, secretKey, useSSL) if err != nil { return nil, err } bs._client = client } return bs._client, nil }
go
func (bs *CephBackupStorage) client() (*minio.Client, error) { bs.mu.Lock() defer bs.mu.Unlock() if bs._client == nil { configFile, err := os.Open(*configFilePath) if err != nil { return nil, fmt.Errorf("file not present : %v", err) } defer configFile.Close() jsonParser := json.NewDecoder(configFile) if err = jsonParser.Decode(&storageConfig); err != nil { return nil, fmt.Errorf("error parsing the json file : %v", err) } accessKey := storageConfig.AccessKey secretKey := storageConfig.SecretKey url := storageConfig.EndPoint useSSL := storageConfig.UseSSL client, err := minio.NewV2(url, accessKey, secretKey, useSSL) if err != nil { return nil, err } bs._client = client } return bs._client, nil }
[ "func", "(", "bs", "*", "CephBackupStorage", ")", "client", "(", ")", "(", "*", "minio", ".", "Client", ",", "error", ")", "{", "bs", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "bs", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "bs", ".", "_client", "==", "nil", "{", "configFile", ",", "err", ":=", "os", ".", "Open", "(", "*", "configFilePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "configFile", ".", "Close", "(", ")", "\n", "jsonParser", ":=", "json", ".", "NewDecoder", "(", "configFile", ")", "\n", "if", "err", "=", "jsonParser", ".", "Decode", "(", "&", "storageConfig", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "accessKey", ":=", "storageConfig", ".", "AccessKey", "\n", "secretKey", ":=", "storageConfig", ".", "SecretKey", "\n", "url", ":=", "storageConfig", ".", "EndPoint", "\n", "useSSL", ":=", "storageConfig", ".", "UseSSL", "\n\n", "client", ",", "err", ":=", "minio", ".", "NewV2", "(", "url", ",", "accessKey", ",", "secretKey", ",", "useSSL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "bs", ".", "_client", "=", "client", "\n", "}", "\n", "return", "bs", ".", "_client", ",", "nil", "\n", "}" ]
// client returns the Ceph Storage client instance. // If there isn't one yet, it tries to create one.
[ "client", "returns", "the", "Ceph", "Storage", "client", "instance", ".", "If", "there", "isn", "t", "one", "yet", "it", "tries", "to", "create", "one", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/cephbackupstorage/ceph.go#L259-L286
train
vitessio/vitess
go/vt/mysqlctl/cephbackupstorage/ceph.go
alterBucketName
func alterBucketName(dir string) string { bucket := strings.ToLower(dir) bucket = strings.Split(bucket, "/")[0] bucket = strings.Replace(bucket, "_", "-", -1) return bucket }
go
func alterBucketName(dir string) string { bucket := strings.ToLower(dir) bucket = strings.Split(bucket, "/")[0] bucket = strings.Replace(bucket, "_", "-", -1) return bucket }
[ "func", "alterBucketName", "(", "dir", "string", ")", "string", "{", "bucket", ":=", "strings", ".", "ToLower", "(", "dir", ")", "\n", "bucket", "=", "strings", ".", "Split", "(", "bucket", ",", "\"", "\"", ")", "[", "0", "]", "\n", "bucket", "=", "strings", ".", "Replace", "(", "bucket", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "return", "bucket", "\n", "}" ]
// keeping in view the bucket naming conventions for ceph // only keyspace informations is extracted and used for bucket name
[ "keeping", "in", "view", "the", "bucket", "naming", "conventions", "for", "ceph", "only", "keyspace", "informations", "is", "extracted", "and", "used", "for", "bucket", "name" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/cephbackupstorage/ceph.go#L301-L306
train
vitessio/vitess
go/vt/binlog/keyspace_id_resolver.go
newKeyspaceIDResolverFactory
func newKeyspaceIDResolverFactory(ctx context.Context, ts *topo.Server, keyspace string, cell string) (keyspaceIDResolverFactory, error) { if *useV3ReshardingMode { return newKeyspaceIDResolverFactoryV3(ctx, ts, keyspace, cell) } return newKeyspaceIDResolverFactoryV2(ctx, ts, keyspace) }
go
func newKeyspaceIDResolverFactory(ctx context.Context, ts *topo.Server, keyspace string, cell string) (keyspaceIDResolverFactory, error) { if *useV3ReshardingMode { return newKeyspaceIDResolverFactoryV3(ctx, ts, keyspace, cell) } return newKeyspaceIDResolverFactoryV2(ctx, ts, keyspace) }
[ "func", "newKeyspaceIDResolverFactory", "(", "ctx", "context", ".", "Context", ",", "ts", "*", "topo", ".", "Server", ",", "keyspace", "string", ",", "cell", "string", ")", "(", "keyspaceIDResolverFactory", ",", "error", ")", "{", "if", "*", "useV3ReshardingMode", "{", "return", "newKeyspaceIDResolverFactoryV3", "(", "ctx", ",", "ts", ",", "keyspace", ",", "cell", ")", "\n", "}", "\n\n", "return", "newKeyspaceIDResolverFactoryV2", "(", "ctx", ",", "ts", ",", "keyspace", ")", "\n", "}" ]
// newKeyspaceIDResolverFactory creates a new // keyspaceIDResolverFactory for the provided keyspace and cell.
[ "newKeyspaceIDResolverFactory", "creates", "a", "new", "keyspaceIDResolverFactory", "for", "the", "provided", "keyspace", "and", "cell", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/binlog/keyspace_id_resolver.go#L54-L60
train
vitessio/vitess
go/vt/binlog/keyspace_id_resolver.go
newKeyspaceIDResolverFactoryV3
func newKeyspaceIDResolverFactoryV3(ctx context.Context, ts *topo.Server, keyspace string, cell string) (keyspaceIDResolverFactory, error) { srvVSchema, err := ts.GetSrvVSchema(ctx, cell) if err != nil { return nil, err } kschema, ok := srvVSchema.Keyspaces[keyspace] if !ok { return nil, fmt.Errorf("SrvVSchema has no entry for keyspace %v", keyspace) } keyspaceSchema, err := vindexes.BuildKeyspaceSchema(kschema, keyspace) if err != nil { return nil, fmt.Errorf("cannot build vschema for keyspace %v: %v", keyspace, err) } return func(table *schema.Table) (int, keyspaceIDResolver, error) { // Find the v3 schema. tableSchema, ok := keyspaceSchema.Tables[table.Name.String()] if !ok { return -1, nil, fmt.Errorf("no vschema definition for table %v", table.Name) } // use the lowest cost unique vindex as the sharding key colVindex, err := vindexes.FindVindexForSharding(table.Name.String(), tableSchema.ColumnVindexes) if err != nil { return -1, nil, err } // TODO @rafael - when rewriting the mapping function, this will need to change. // for now it's safe to assume the sharding key will be always on index 0. shardingColumnName := colVindex.Columns[0].String() for i, col := range table.Columns { if col.Name.EqualString(shardingColumnName) { // We found the column. return i, &keyspaceIDResolverFactoryV3{ vindex: colVindex.Vindex, }, nil } } // The column was not found. return -1, nil, fmt.Errorf("cannot find column %v in table %v", shardingColumnName, table.Name) }, nil }
go
func newKeyspaceIDResolverFactoryV3(ctx context.Context, ts *topo.Server, keyspace string, cell string) (keyspaceIDResolverFactory, error) { srvVSchema, err := ts.GetSrvVSchema(ctx, cell) if err != nil { return nil, err } kschema, ok := srvVSchema.Keyspaces[keyspace] if !ok { return nil, fmt.Errorf("SrvVSchema has no entry for keyspace %v", keyspace) } keyspaceSchema, err := vindexes.BuildKeyspaceSchema(kschema, keyspace) if err != nil { return nil, fmt.Errorf("cannot build vschema for keyspace %v: %v", keyspace, err) } return func(table *schema.Table) (int, keyspaceIDResolver, error) { // Find the v3 schema. tableSchema, ok := keyspaceSchema.Tables[table.Name.String()] if !ok { return -1, nil, fmt.Errorf("no vschema definition for table %v", table.Name) } // use the lowest cost unique vindex as the sharding key colVindex, err := vindexes.FindVindexForSharding(table.Name.String(), tableSchema.ColumnVindexes) if err != nil { return -1, nil, err } // TODO @rafael - when rewriting the mapping function, this will need to change. // for now it's safe to assume the sharding key will be always on index 0. shardingColumnName := colVindex.Columns[0].String() for i, col := range table.Columns { if col.Name.EqualString(shardingColumnName) { // We found the column. return i, &keyspaceIDResolverFactoryV3{ vindex: colVindex.Vindex, }, nil } } // The column was not found. return -1, nil, fmt.Errorf("cannot find column %v in table %v", shardingColumnName, table.Name) }, nil }
[ "func", "newKeyspaceIDResolverFactoryV3", "(", "ctx", "context", ".", "Context", ",", "ts", "*", "topo", ".", "Server", ",", "keyspace", "string", ",", "cell", "string", ")", "(", "keyspaceIDResolverFactory", ",", "error", ")", "{", "srvVSchema", ",", "err", ":=", "ts", ".", "GetSrvVSchema", "(", "ctx", ",", "cell", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "kschema", ",", "ok", ":=", "srvVSchema", ".", "Keyspaces", "[", "keyspace", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "keyspace", ")", "\n", "}", "\n", "keyspaceSchema", ",", "err", ":=", "vindexes", ".", "BuildKeyspaceSchema", "(", "kschema", ",", "keyspace", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "keyspace", ",", "err", ")", "\n", "}", "\n", "return", "func", "(", "table", "*", "schema", ".", "Table", ")", "(", "int", ",", "keyspaceIDResolver", ",", "error", ")", "{", "// Find the v3 schema.", "tableSchema", ",", "ok", ":=", "keyspaceSchema", ".", "Tables", "[", "table", ".", "Name", ".", "String", "(", ")", "]", "\n", "if", "!", "ok", "{", "return", "-", "1", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "table", ".", "Name", ")", "\n", "}", "\n\n", "// use the lowest cost unique vindex as the sharding key", "colVindex", ",", "err", ":=", "vindexes", ".", "FindVindexForSharding", "(", "table", ".", "Name", ".", "String", "(", ")", ",", "tableSchema", ".", "ColumnVindexes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "nil", ",", "err", "\n", "}", "\n\n", "// TODO @rafael - when rewriting the mapping function, this will need to change.", "// for now it's safe to assume the sharding key will be always on index 0.", "shardingColumnName", ":=", "colVindex", ".", "Columns", "[", "0", "]", ".", "String", "(", ")", "\n", "for", "i", ",", "col", ":=", "range", "table", ".", "Columns", "{", "if", "col", ".", "Name", ".", "EqualString", "(", "shardingColumnName", ")", "{", "// We found the column.", "return", "i", ",", "&", "keyspaceIDResolverFactoryV3", "{", "vindex", ":", "colVindex", ".", "Vindex", ",", "}", ",", "nil", "\n", "}", "\n", "}", "\n", "// The column was not found.", "return", "-", "1", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "shardingColumnName", ",", "table", ".", "Name", ")", "\n", "}", ",", "nil", "\n", "}" ]
// newKeyspaceIDResolverFactoryV3 finds the SrvVSchema in the cell, // gets the keyspace part, and uses it to find the column name.
[ "newKeyspaceIDResolverFactoryV3", "finds", "the", "SrvVSchema", "in", "the", "cell", "gets", "the", "keyspace", "part", "and", "uses", "it", "to", "find", "the", "column", "name", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/binlog/keyspace_id_resolver.go#L117-L157
train
vitessio/vitess
go/pools/resource_pool.go
closeIdleResources
func (rp *ResourcePool) closeIdleResources() { available := int(rp.Available()) idleTimeout := rp.IdleTimeout() for i := 0; i < available; i++ { var wrapper resourceWrapper select { case wrapper = <-rp.resources: default: // stop early if we don't get anything new from the pool return } if wrapper.resource != nil && idleTimeout > 0 && time.Until(wrapper.timeUsed.Add(idleTimeout)) < 0 { wrapper.resource.Close() wrapper.resource = nil rp.idleClosed.Add(1) rp.active.Add(-1) } rp.resources <- wrapper } }
go
func (rp *ResourcePool) closeIdleResources() { available := int(rp.Available()) idleTimeout := rp.IdleTimeout() for i := 0; i < available; i++ { var wrapper resourceWrapper select { case wrapper = <-rp.resources: default: // stop early if we don't get anything new from the pool return } if wrapper.resource != nil && idleTimeout > 0 && time.Until(wrapper.timeUsed.Add(idleTimeout)) < 0 { wrapper.resource.Close() wrapper.resource = nil rp.idleClosed.Add(1) rp.active.Add(-1) } rp.resources <- wrapper } }
[ "func", "(", "rp", "*", "ResourcePool", ")", "closeIdleResources", "(", ")", "{", "available", ":=", "int", "(", "rp", ".", "Available", "(", ")", ")", "\n", "idleTimeout", ":=", "rp", ".", "IdleTimeout", "(", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "available", ";", "i", "++", "{", "var", "wrapper", "resourceWrapper", "\n", "select", "{", "case", "wrapper", "=", "<-", "rp", ".", "resources", ":", "default", ":", "// stop early if we don't get anything new from the pool", "return", "\n", "}", "\n\n", "if", "wrapper", ".", "resource", "!=", "nil", "&&", "idleTimeout", ">", "0", "&&", "time", ".", "Until", "(", "wrapper", ".", "timeUsed", ".", "Add", "(", "idleTimeout", ")", ")", "<", "0", "{", "wrapper", ".", "resource", ".", "Close", "(", ")", "\n", "wrapper", ".", "resource", "=", "nil", "\n", "rp", ".", "idleClosed", ".", "Add", "(", "1", ")", "\n", "rp", ".", "active", ".", "Add", "(", "-", "1", ")", "\n", "}", "\n\n", "rp", ".", "resources", "<-", "wrapper", "\n", "}", "\n", "}" ]
// closeIdleResources scans the pool for idle resources
[ "closeIdleResources", "scans", "the", "pool", "for", "idle", "resources" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/pools/resource_pool.go#L121-L143
train
vitessio/vitess
go/pools/resource_pool.go
Get
func (rp *ResourcePool) Get(ctx context.Context) (resource Resource, err error) { span, ctx := trace.NewSpan(ctx, "ResourcePool.Get") span.Annotate("capacity", rp.capacity.Get()) span.Annotate("in_use", rp.inUse.Get()) span.Annotate("available", rp.available.Get()) span.Annotate("active", rp.active.Get()) defer span.Finish() return rp.get(ctx, true) }
go
func (rp *ResourcePool) Get(ctx context.Context) (resource Resource, err error) { span, ctx := trace.NewSpan(ctx, "ResourcePool.Get") span.Annotate("capacity", rp.capacity.Get()) span.Annotate("in_use", rp.inUse.Get()) span.Annotate("available", rp.available.Get()) span.Annotate("active", rp.active.Get()) defer span.Finish() return rp.get(ctx, true) }
[ "func", "(", "rp", "*", "ResourcePool", ")", "Get", "(", "ctx", "context", ".", "Context", ")", "(", "resource", "Resource", ",", "err", "error", ")", "{", "span", ",", "ctx", ":=", "trace", ".", "NewSpan", "(", "ctx", ",", "\"", "\"", ")", "\n", "span", ".", "Annotate", "(", "\"", "\"", ",", "rp", ".", "capacity", ".", "Get", "(", ")", ")", "\n", "span", ".", "Annotate", "(", "\"", "\"", ",", "rp", ".", "inUse", ".", "Get", "(", ")", ")", "\n", "span", ".", "Annotate", "(", "\"", "\"", ",", "rp", ".", "available", ".", "Get", "(", ")", ")", "\n", "span", ".", "Annotate", "(", "\"", "\"", ",", "rp", ".", "active", ".", "Get", "(", ")", ")", "\n", "defer", "span", ".", "Finish", "(", ")", "\n", "return", "rp", ".", "get", "(", "ctx", ",", "true", ")", "\n", "}" ]
// Get will return the next available resource. If capacity // has not been reached, it will create a new one using the factory. Otherwise, // it will wait till the next resource becomes available or a timeout. // A timeout of 0 is an indefinite wait.
[ "Get", "will", "return", "the", "next", "available", "resource", ".", "If", "capacity", "has", "not", "been", "reached", "it", "will", "create", "a", "new", "one", "using", "the", "factory", ".", "Otherwise", "it", "will", "wait", "till", "the", "next", "resource", "becomes", "available", "or", "a", "timeout", ".", "A", "timeout", "of", "0", "is", "an", "indefinite", "wait", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/pools/resource_pool.go#L149-L157
train
vitessio/vitess
go/pools/resource_pool.go
SetIdleTimeout
func (rp *ResourcePool) SetIdleTimeout(idleTimeout time.Duration) { if rp.idleTimer == nil { panic("SetIdleTimeout called when timer not initialized") } rp.idleTimeout.Set(idleTimeout) rp.idleTimer.SetInterval(idleTimeout / 10) }
go
func (rp *ResourcePool) SetIdleTimeout(idleTimeout time.Duration) { if rp.idleTimer == nil { panic("SetIdleTimeout called when timer not initialized") } rp.idleTimeout.Set(idleTimeout) rp.idleTimer.SetInterval(idleTimeout / 10) }
[ "func", "(", "rp", "*", "ResourcePool", ")", "SetIdleTimeout", "(", "idleTimeout", "time", ".", "Duration", ")", "{", "if", "rp", ".", "idleTimer", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "rp", ".", "idleTimeout", ".", "Set", "(", "idleTimeout", ")", "\n", "rp", ".", "idleTimer", ".", "SetInterval", "(", "idleTimeout", "/", "10", ")", "\n", "}" ]
// SetIdleTimeout sets the idle timeout. It can only be used if there was an // idle timeout set when the pool was created.
[ "SetIdleTimeout", "sets", "the", "idle", "timeout", ".", "It", "can", "only", "be", "used", "if", "there", "was", "an", "idle", "timeout", "set", "when", "the", "pool", "was", "created", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/pools/resource_pool.go#L279-L286
train
vitessio/vitess
go/pools/resource_pool.go
StatsJSON
func (rp *ResourcePool) StatsJSON() string { return fmt.Sprintf(`{"Capacity": %v, "Available": %v, "Active": %v, "InUse": %v, "MaxCapacity": %v, "WaitCount": %v, "WaitTime": %v, "IdleTimeout": %v, "IdleClosed": %v}`, rp.Capacity(), rp.Available(), rp.Active(), rp.InUse(), rp.MaxCap(), rp.WaitCount(), rp.WaitTime().Nanoseconds(), rp.IdleTimeout().Nanoseconds(), rp.IdleClosed(), ) }
go
func (rp *ResourcePool) StatsJSON() string { return fmt.Sprintf(`{"Capacity": %v, "Available": %v, "Active": %v, "InUse": %v, "MaxCapacity": %v, "WaitCount": %v, "WaitTime": %v, "IdleTimeout": %v, "IdleClosed": %v}`, rp.Capacity(), rp.Available(), rp.Active(), rp.InUse(), rp.MaxCap(), rp.WaitCount(), rp.WaitTime().Nanoseconds(), rp.IdleTimeout().Nanoseconds(), rp.IdleClosed(), ) }
[ "func", "(", "rp", "*", "ResourcePool", ")", "StatsJSON", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "`{\"Capacity\": %v, \"Available\": %v, \"Active\": %v, \"InUse\": %v, \"MaxCapacity\": %v, \"WaitCount\": %v, \"WaitTime\": %v, \"IdleTimeout\": %v, \"IdleClosed\": %v}`", ",", "rp", ".", "Capacity", "(", ")", ",", "rp", ".", "Available", "(", ")", ",", "rp", ".", "Active", "(", ")", ",", "rp", ".", "InUse", "(", ")", ",", "rp", ".", "MaxCap", "(", ")", ",", "rp", ".", "WaitCount", "(", ")", ",", "rp", ".", "WaitTime", "(", ")", ".", "Nanoseconds", "(", ")", ",", "rp", ".", "IdleTimeout", "(", ")", ".", "Nanoseconds", "(", ")", ",", "rp", ".", "IdleClosed", "(", ")", ",", ")", "\n", "}" ]
// StatsJSON returns the stats in JSON format.
[ "StatsJSON", "returns", "the", "stats", "in", "JSON", "format", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/pools/resource_pool.go#L289-L301
train
vitessio/vitess
go/vt/topo/cells_aliases.go
GetCellsAliases
func (ts *Server) GetCellsAliases(ctx context.Context, strongRead bool) (ret map[string]*topodatapb.CellsAlias, err error) { conn := ts.globalCell if !strongRead { conn = ts.globalReadOnlyCell } entries, err := ts.globalCell.ListDir(ctx, CellsAliasesPath, false /*full*/) switch { case IsErrType(err, NoNode): return nil, nil case err == nil: aliases := DirEntriesToStringArray(entries) ret = make(map[string]*topodatapb.CellsAlias, len(aliases)) for _, alias := range aliases { aliasPath := pathForCellsAlias(alias) contents, _, err := conn.Get(ctx, aliasPath) if err != nil { return nil, err } // Unpack the contents. cellsAlias := &topodatapb.CellsAlias{} if err := proto.Unmarshal(contents, cellsAlias); err != nil { return nil, err } ret[alias] = cellsAlias } return ret, nil default: return nil, err } }
go
func (ts *Server) GetCellsAliases(ctx context.Context, strongRead bool) (ret map[string]*topodatapb.CellsAlias, err error) { conn := ts.globalCell if !strongRead { conn = ts.globalReadOnlyCell } entries, err := ts.globalCell.ListDir(ctx, CellsAliasesPath, false /*full*/) switch { case IsErrType(err, NoNode): return nil, nil case err == nil: aliases := DirEntriesToStringArray(entries) ret = make(map[string]*topodatapb.CellsAlias, len(aliases)) for _, alias := range aliases { aliasPath := pathForCellsAlias(alias) contents, _, err := conn.Get(ctx, aliasPath) if err != nil { return nil, err } // Unpack the contents. cellsAlias := &topodatapb.CellsAlias{} if err := proto.Unmarshal(contents, cellsAlias); err != nil { return nil, err } ret[alias] = cellsAlias } return ret, nil default: return nil, err } }
[ "func", "(", "ts", "*", "Server", ")", "GetCellsAliases", "(", "ctx", "context", ".", "Context", ",", "strongRead", "bool", ")", "(", "ret", "map", "[", "string", "]", "*", "topodatapb", ".", "CellsAlias", ",", "err", "error", ")", "{", "conn", ":=", "ts", ".", "globalCell", "\n", "if", "!", "strongRead", "{", "conn", "=", "ts", ".", "globalReadOnlyCell", "\n", "}", "\n\n", "entries", ",", "err", ":=", "ts", ".", "globalCell", ".", "ListDir", "(", "ctx", ",", "CellsAliasesPath", ",", "false", "/*full*/", ")", "\n", "switch", "{", "case", "IsErrType", "(", "err", ",", "NoNode", ")", ":", "return", "nil", ",", "nil", "\n", "case", "err", "==", "nil", ":", "aliases", ":=", "DirEntriesToStringArray", "(", "entries", ")", "\n", "ret", "=", "make", "(", "map", "[", "string", "]", "*", "topodatapb", ".", "CellsAlias", ",", "len", "(", "aliases", ")", ")", "\n", "for", "_", ",", "alias", ":=", "range", "aliases", "{", "aliasPath", ":=", "pathForCellsAlias", "(", "alias", ")", "\n", "contents", ",", "_", ",", "err", ":=", "conn", ".", "Get", "(", "ctx", ",", "aliasPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Unpack the contents.", "cellsAlias", ":=", "&", "topodatapb", ".", "CellsAlias", "{", "}", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "contents", ",", "cellsAlias", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "ret", "[", "alias", "]", "=", "cellsAlias", "\n", "}", "\n", "return", "ret", ",", "nil", "\n", "default", ":", "return", "nil", ",", "err", "\n", "}", "\n", "}" ]
// GetCellsAliases returns the names of the existing cells. They are // sorted by name.
[ "GetCellsAliases", "returns", "the", "names", "of", "the", "existing", "cells", ".", "They", "are", "sorted", "by", "name", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/cells_aliases.go#L43-L75
train
vitessio/vitess
go/vt/topo/cells_aliases.go
DeleteCellsAlias
func (ts *Server) DeleteCellsAlias(ctx context.Context, alias string) error { ts.clearCellAliasesCache() filePath := pathForCellsAlias(alias) return ts.globalCell.Delete(ctx, filePath, nil) }
go
func (ts *Server) DeleteCellsAlias(ctx context.Context, alias string) error { ts.clearCellAliasesCache() filePath := pathForCellsAlias(alias) return ts.globalCell.Delete(ctx, filePath, nil) }
[ "func", "(", "ts", "*", "Server", ")", "DeleteCellsAlias", "(", "ctx", "context", ".", "Context", ",", "alias", "string", ")", "error", "{", "ts", ".", "clearCellAliasesCache", "(", ")", "\n\n", "filePath", ":=", "pathForCellsAlias", "(", "alias", ")", "\n", "return", "ts", ".", "globalCell", ".", "Delete", "(", "ctx", ",", "filePath", ",", "nil", ")", "\n", "}" ]
// DeleteCellsAlias deletes the specified CellsAlias
[ "DeleteCellsAlias", "deletes", "the", "specified", "CellsAlias" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/cells_aliases.go#L78-L83
train
vitessio/vitess
go/vt/topo/cells_aliases.go
CreateCellsAlias
func (ts *Server) CreateCellsAlias(ctx context.Context, alias string, cellsAlias *topodatapb.CellsAlias) error { currentAliases, err := ts.GetCellsAliases(ctx, true) if err != nil { return err } if overlappingAliases(currentAliases, cellsAlias) { return fmt.Errorf("unsupported: you can't over overlapping aliases. Cells alias: %v, has an overlap with existent aliases", cellsAlias) } ts.clearCellAliasesCache() // Pack the content. contents, err := proto.Marshal(cellsAlias) if err != nil { return err } // Save it. filePath := pathForCellsAlias(alias) _, err = ts.globalCell.Create(ctx, filePath, contents) return err }
go
func (ts *Server) CreateCellsAlias(ctx context.Context, alias string, cellsAlias *topodatapb.CellsAlias) error { currentAliases, err := ts.GetCellsAliases(ctx, true) if err != nil { return err } if overlappingAliases(currentAliases, cellsAlias) { return fmt.Errorf("unsupported: you can't over overlapping aliases. Cells alias: %v, has an overlap with existent aliases", cellsAlias) } ts.clearCellAliasesCache() // Pack the content. contents, err := proto.Marshal(cellsAlias) if err != nil { return err } // Save it. filePath := pathForCellsAlias(alias) _, err = ts.globalCell.Create(ctx, filePath, contents) return err }
[ "func", "(", "ts", "*", "Server", ")", "CreateCellsAlias", "(", "ctx", "context", ".", "Context", ",", "alias", "string", ",", "cellsAlias", "*", "topodatapb", ".", "CellsAlias", ")", "error", "{", "currentAliases", ",", "err", ":=", "ts", ".", "GetCellsAliases", "(", "ctx", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "overlappingAliases", "(", "currentAliases", ",", "cellsAlias", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "cellsAlias", ")", "\n\n", "}", "\n\n", "ts", ".", "clearCellAliasesCache", "(", ")", "\n\n", "// Pack the content.", "contents", ",", "err", ":=", "proto", ".", "Marshal", "(", "cellsAlias", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Save it.", "filePath", ":=", "pathForCellsAlias", "(", "alias", ")", "\n", "_", ",", "err", "=", "ts", ".", "globalCell", ".", "Create", "(", "ctx", ",", "filePath", ",", "contents", ")", "\n", "return", "err", "\n", "}" ]
// CreateCellsAlias creates a new CellInfo with the provided content.
[ "CreateCellsAlias", "creates", "a", "new", "CellInfo", "with", "the", "provided", "content", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/cells_aliases.go#L86-L109
train
vitessio/vitess
go/vt/topo/cells_aliases.go
UpdateCellsAlias
func (ts *Server) UpdateCellsAlias(ctx context.Context, alias string, update func(*topodatapb.CellsAlias) error) error { ts.clearCellAliasesCache() filePath := pathForCellsAlias(alias) for { ca := &topodatapb.CellsAlias{} // Read the file, unpack the contents. contents, version, err := ts.globalCell.Get(ctx, filePath) switch { case err == nil: if err := proto.Unmarshal(contents, ca); err != nil { return err } case IsErrType(err, NoNode): // Nothing to do. default: return err } // Call update method. if err = update(ca); err != nil { if IsErrType(err, NoUpdateNeeded) { return nil } return err } currentAliases, err := ts.GetCellsAliases(ctx, true) if err != nil { return err } if overlappingAliases(currentAliases, ca) { return fmt.Errorf("unsupported: you can't over overlapping aliases. Cells alias: %v, has an overlap with existent aliases", ca) } // Pack and save. contents, err = proto.Marshal(ca) if err != nil { return err } if _, err = ts.globalCell.Update(ctx, filePath, contents, version); !IsErrType(err, BadVersion) { // This includes the 'err=nil' case. return err } } }
go
func (ts *Server) UpdateCellsAlias(ctx context.Context, alias string, update func(*topodatapb.CellsAlias) error) error { ts.clearCellAliasesCache() filePath := pathForCellsAlias(alias) for { ca := &topodatapb.CellsAlias{} // Read the file, unpack the contents. contents, version, err := ts.globalCell.Get(ctx, filePath) switch { case err == nil: if err := proto.Unmarshal(contents, ca); err != nil { return err } case IsErrType(err, NoNode): // Nothing to do. default: return err } // Call update method. if err = update(ca); err != nil { if IsErrType(err, NoUpdateNeeded) { return nil } return err } currentAliases, err := ts.GetCellsAliases(ctx, true) if err != nil { return err } if overlappingAliases(currentAliases, ca) { return fmt.Errorf("unsupported: you can't over overlapping aliases. Cells alias: %v, has an overlap with existent aliases", ca) } // Pack and save. contents, err = proto.Marshal(ca) if err != nil { return err } if _, err = ts.globalCell.Update(ctx, filePath, contents, version); !IsErrType(err, BadVersion) { // This includes the 'err=nil' case. return err } } }
[ "func", "(", "ts", "*", "Server", ")", "UpdateCellsAlias", "(", "ctx", "context", ".", "Context", ",", "alias", "string", ",", "update", "func", "(", "*", "topodatapb", ".", "CellsAlias", ")", "error", ")", "error", "{", "ts", ".", "clearCellAliasesCache", "(", ")", "\n\n", "filePath", ":=", "pathForCellsAlias", "(", "alias", ")", "\n", "for", "{", "ca", ":=", "&", "topodatapb", ".", "CellsAlias", "{", "}", "\n\n", "// Read the file, unpack the contents.", "contents", ",", "version", ",", "err", ":=", "ts", ".", "globalCell", ".", "Get", "(", "ctx", ",", "filePath", ")", "\n", "switch", "{", "case", "err", "==", "nil", ":", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "contents", ",", "ca", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "IsErrType", "(", "err", ",", "NoNode", ")", ":", "// Nothing to do.", "default", ":", "return", "err", "\n", "}", "\n\n", "// Call update method.", "if", "err", "=", "update", "(", "ca", ")", ";", "err", "!=", "nil", "{", "if", "IsErrType", "(", "err", ",", "NoUpdateNeeded", ")", "{", "return", "nil", "\n", "}", "\n", "return", "err", "\n", "}", "\n\n", "currentAliases", ",", "err", ":=", "ts", ".", "GetCellsAliases", "(", "ctx", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "overlappingAliases", "(", "currentAliases", ",", "ca", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ca", ")", "\n\n", "}", "\n\n", "// Pack and save.", "contents", ",", "err", "=", "proto", ".", "Marshal", "(", "ca", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "_", ",", "err", "=", "ts", ".", "globalCell", ".", "Update", "(", "ctx", ",", "filePath", ",", "contents", ",", "version", ")", ";", "!", "IsErrType", "(", "err", ",", "BadVersion", ")", "{", "// This includes the 'err=nil' case.", "return", "err", "\n", "}", "\n", "}", "\n", "}" ]
// UpdateCellsAlias updates cells for a given alias
[ "UpdateCellsAlias", "updates", "cells", "for", "a", "given", "alias" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/cells_aliases.go#L112-L160
train
vitessio/vitess
go/vt/mysqlctl/permissions.go
GetPermissions
func GetPermissions(mysqld MysqlDaemon) (*tabletmanagerdatapb.Permissions, error) { ctx := context.TODO() permissions := &tabletmanagerdatapb.Permissions{} // get Users qr, err := mysqld.FetchSuperQuery(ctx, "SELECT * FROM mysql.user ORDER BY host, user") if err != nil { return nil, err } for _, row := range qr.Rows { permissions.UserPermissions = append(permissions.UserPermissions, tmutils.NewUserPermission(qr.Fields, row)) } // get Dbs qr, err = mysqld.FetchSuperQuery(ctx, "SELECT * FROM mysql.db ORDER BY host, db, user") if err != nil { return nil, err } for _, row := range qr.Rows { permissions.DbPermissions = append(permissions.DbPermissions, tmutils.NewDbPermission(qr.Fields, row)) } return permissions, nil }
go
func GetPermissions(mysqld MysqlDaemon) (*tabletmanagerdatapb.Permissions, error) { ctx := context.TODO() permissions := &tabletmanagerdatapb.Permissions{} // get Users qr, err := mysqld.FetchSuperQuery(ctx, "SELECT * FROM mysql.user ORDER BY host, user") if err != nil { return nil, err } for _, row := range qr.Rows { permissions.UserPermissions = append(permissions.UserPermissions, tmutils.NewUserPermission(qr.Fields, row)) } // get Dbs qr, err = mysqld.FetchSuperQuery(ctx, "SELECT * FROM mysql.db ORDER BY host, db, user") if err != nil { return nil, err } for _, row := range qr.Rows { permissions.DbPermissions = append(permissions.DbPermissions, tmutils.NewDbPermission(qr.Fields, row)) } return permissions, nil }
[ "func", "GetPermissions", "(", "mysqld", "MysqlDaemon", ")", "(", "*", "tabletmanagerdatapb", ".", "Permissions", ",", "error", ")", "{", "ctx", ":=", "context", ".", "TODO", "(", ")", "\n", "permissions", ":=", "&", "tabletmanagerdatapb", ".", "Permissions", "{", "}", "\n\n", "// get Users", "qr", ",", "err", ":=", "mysqld", ".", "FetchSuperQuery", "(", "ctx", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "row", ":=", "range", "qr", ".", "Rows", "{", "permissions", ".", "UserPermissions", "=", "append", "(", "permissions", ".", "UserPermissions", ",", "tmutils", ".", "NewUserPermission", "(", "qr", ".", "Fields", ",", "row", ")", ")", "\n", "}", "\n\n", "// get Dbs", "qr", ",", "err", "=", "mysqld", ".", "FetchSuperQuery", "(", "ctx", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "row", ":=", "range", "qr", ".", "Rows", "{", "permissions", ".", "DbPermissions", "=", "append", "(", "permissions", ".", "DbPermissions", ",", "tmutils", ".", "NewDbPermission", "(", "qr", ".", "Fields", ",", "row", ")", ")", "\n", "}", "\n\n", "return", "permissions", ",", "nil", "\n", "}" ]
// GetPermissions lists the permissions on the mysqld. // The rows are sorted in primary key order to help with comparing // permissions between tablets.
[ "GetPermissions", "lists", "the", "permissions", "on", "the", "mysqld", ".", "The", "rows", "are", "sorted", "in", "primary", "key", "order", "to", "help", "with", "comparing", "permissions", "between", "tablets", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/permissions.go#L28-L51
train
vitessio/vitess
go/json2/marshal.go
MarshalPB
func MarshalPB(pb proto.Message) ([]byte, error) { buf := new(bytes.Buffer) m := jsonpb.Marshaler{} if err := m.Marshal(buf, pb); err != nil { return nil, err } return buf.Bytes(), nil }
go
func MarshalPB(pb proto.Message) ([]byte, error) { buf := new(bytes.Buffer) m := jsonpb.Marshaler{} if err := m.Marshal(buf, pb); err != nil { return nil, err } return buf.Bytes(), nil }
[ "func", "MarshalPB", "(", "pb", "proto", ".", "Message", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "m", ":=", "jsonpb", ".", "Marshaler", "{", "}", "\n", "if", "err", ":=", "m", ".", "Marshal", "(", "buf", ",", "pb", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "buf", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// MarshalPB marshals a proto.
[ "MarshalPB", "marshals", "a", "proto", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/json2/marshal.go#L27-L34
train
vitessio/vitess
go/json2/marshal.go
MarshalIndentPB
func MarshalIndentPB(pb proto.Message, indent string) ([]byte, error) { buf := new(bytes.Buffer) m := jsonpb.Marshaler{ Indent: indent, } if err := m.Marshal(buf, pb); err != nil { return nil, err } return buf.Bytes(), nil }
go
func MarshalIndentPB(pb proto.Message, indent string) ([]byte, error) { buf := new(bytes.Buffer) m := jsonpb.Marshaler{ Indent: indent, } if err := m.Marshal(buf, pb); err != nil { return nil, err } return buf.Bytes(), nil }
[ "func", "MarshalIndentPB", "(", "pb", "proto", ".", "Message", ",", "indent", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "m", ":=", "jsonpb", ".", "Marshaler", "{", "Indent", ":", "indent", ",", "}", "\n", "if", "err", ":=", "m", ".", "Marshal", "(", "buf", ",", "pb", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "buf", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// MarshalIndentPB MarshalIndents a proto.
[ "MarshalIndentPB", "MarshalIndents", "a", "proto", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/json2/marshal.go#L37-L46
train
vitessio/vitess
go/stats/prometheusbackend/prometheusbackend.go
Init
func Init(namespace string) { http.Handle("/metrics", promhttp.Handler()) be.namespace = namespace stats.Register(be.publishPrometheusMetric) }
go
func Init(namespace string) { http.Handle("/metrics", promhttp.Handler()) be.namespace = namespace stats.Register(be.publishPrometheusMetric) }
[ "func", "Init", "(", "namespace", "string", ")", "{", "http", ".", "Handle", "(", "\"", "\"", ",", "promhttp", ".", "Handler", "(", ")", ")", "\n", "be", ".", "namespace", "=", "namespace", "\n", "stats", ".", "Register", "(", "be", ".", "publishPrometheusMetric", ")", "\n", "}" ]
// Init initializes the Prometheus be with the given namespace.
[ "Init", "initializes", "the", "Prometheus", "be", "with", "the", "given", "namespace", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/stats/prometheusbackend/prometheusbackend.go#L24-L28
train
vitessio/vitess
go/stats/prometheusbackend/prometheusbackend.go
buildPromName
func (be PromBackend) buildPromName(name string) string { s := strings.TrimPrefix(normalizeMetric(name), be.namespace+"_") return prometheus.BuildFQName("", be.namespace, s) }
go
func (be PromBackend) buildPromName(name string) string { s := strings.TrimPrefix(normalizeMetric(name), be.namespace+"_") return prometheus.BuildFQName("", be.namespace, s) }
[ "func", "(", "be", "PromBackend", ")", "buildPromName", "(", "name", "string", ")", "string", "{", "s", ":=", "strings", ".", "TrimPrefix", "(", "normalizeMetric", "(", "name", ")", ",", "be", ".", "namespace", "+", "\"", "\"", ")", "\n", "return", "prometheus", ".", "BuildFQName", "(", "\"", "\"", ",", "be", ".", "namespace", ",", "s", ")", "\n", "}" ]
// buildPromName specifies the namespace as a prefix to the metric name
[ "buildPromName", "specifies", "the", "namespace", "as", "a", "prefix", "to", "the", "metric", "name" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/stats/prometheusbackend/prometheusbackend.go#L78-L81
train
vitessio/vitess
go/stats/prometheusbackend/prometheusbackend.go
normalizeMetric
func normalizeMetric(name string) string { // Special cases r := strings.NewReplacer("VSchema", "vschema", "VtGate", "vtgate") name = r.Replace(name) return stats.GetSnakeName(name) }
go
func normalizeMetric(name string) string { // Special cases r := strings.NewReplacer("VSchema", "vschema", "VtGate", "vtgate") name = r.Replace(name) return stats.GetSnakeName(name) }
[ "func", "normalizeMetric", "(", "name", "string", ")", "string", "{", "// Special cases", "r", ":=", "strings", ".", "NewReplacer", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "name", "=", "r", ".", "Replace", "(", "name", ")", "\n\n", "return", "stats", ".", "GetSnakeName", "(", "name", ")", "\n", "}" ]
// normalizeMetricForPrometheus produces a compliant name by applying // special case conversions and then applying a camel case to snake case converter.
[ "normalizeMetricForPrometheus", "produces", "a", "compliant", "name", "by", "applying", "special", "case", "conversions", "and", "then", "applying", "a", "camel", "case", "to", "snake", "case", "converter", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/stats/prometheusbackend/prometheusbackend.go#L93-L99
train
vitessio/vitess
go/vt/vtgate/executor.go
NewExecutor
func NewExecutor(ctx context.Context, serv srvtopo.Server, cell, statsName string, resolver *Resolver, normalize bool, streamSize int, queryPlanCacheSize int64, legacyAutocommit bool) *Executor { e := &Executor{ serv: serv, cell: cell, resolver: resolver, scatterConn: resolver.scatterConn, txConn: resolver.scatterConn.txConn, plans: cache.NewLRUCache(queryPlanCacheSize), normalize: normalize, streamSize: streamSize, legacyAutocommit: legacyAutocommit, } vschemaacl.Init() e.vm = VSchemaManager{e: e} e.vm.watchSrvVSchema(ctx, cell) executorOnce.Do(func() { stats.NewGaugeFunc("QueryPlanCacheLength", "Query plan cache length", e.plans.Length) stats.NewGaugeFunc("QueryPlanCacheSize", "Query plan cache size", e.plans.Size) stats.NewGaugeFunc("QueryPlanCacheCapacity", "Query plan cache capacity", e.plans.Capacity) stats.NewCounterFunc("QueryPlanCacheEvictions", "Query plan cache evictions", e.plans.Evictions) stats.Publish("QueryPlanCacheOldest", stats.StringFunc(func() string { return fmt.Sprintf("%v", e.plans.Oldest()) })) http.Handle("/debug/query_plans", e) http.Handle("/debug/vschema", e) }) return e }
go
func NewExecutor(ctx context.Context, serv srvtopo.Server, cell, statsName string, resolver *Resolver, normalize bool, streamSize int, queryPlanCacheSize int64, legacyAutocommit bool) *Executor { e := &Executor{ serv: serv, cell: cell, resolver: resolver, scatterConn: resolver.scatterConn, txConn: resolver.scatterConn.txConn, plans: cache.NewLRUCache(queryPlanCacheSize), normalize: normalize, streamSize: streamSize, legacyAutocommit: legacyAutocommit, } vschemaacl.Init() e.vm = VSchemaManager{e: e} e.vm.watchSrvVSchema(ctx, cell) executorOnce.Do(func() { stats.NewGaugeFunc("QueryPlanCacheLength", "Query plan cache length", e.plans.Length) stats.NewGaugeFunc("QueryPlanCacheSize", "Query plan cache size", e.plans.Size) stats.NewGaugeFunc("QueryPlanCacheCapacity", "Query plan cache capacity", e.plans.Capacity) stats.NewCounterFunc("QueryPlanCacheEvictions", "Query plan cache evictions", e.plans.Evictions) stats.Publish("QueryPlanCacheOldest", stats.StringFunc(func() string { return fmt.Sprintf("%v", e.plans.Oldest()) })) http.Handle("/debug/query_plans", e) http.Handle("/debug/vschema", e) }) return e }
[ "func", "NewExecutor", "(", "ctx", "context", ".", "Context", ",", "serv", "srvtopo", ".", "Server", ",", "cell", ",", "statsName", "string", ",", "resolver", "*", "Resolver", ",", "normalize", "bool", ",", "streamSize", "int", ",", "queryPlanCacheSize", "int64", ",", "legacyAutocommit", "bool", ")", "*", "Executor", "{", "e", ":=", "&", "Executor", "{", "serv", ":", "serv", ",", "cell", ":", "cell", ",", "resolver", ":", "resolver", ",", "scatterConn", ":", "resolver", ".", "scatterConn", ",", "txConn", ":", "resolver", ".", "scatterConn", ".", "txConn", ",", "plans", ":", "cache", ".", "NewLRUCache", "(", "queryPlanCacheSize", ")", ",", "normalize", ":", "normalize", ",", "streamSize", ":", "streamSize", ",", "legacyAutocommit", ":", "legacyAutocommit", ",", "}", "\n\n", "vschemaacl", ".", "Init", "(", ")", "\n", "e", ".", "vm", "=", "VSchemaManager", "{", "e", ":", "e", "}", "\n", "e", ".", "vm", ".", "watchSrvVSchema", "(", "ctx", ",", "cell", ")", "\n\n", "executorOnce", ".", "Do", "(", "func", "(", ")", "{", "stats", ".", "NewGaugeFunc", "(", "\"", "\"", ",", "\"", "\"", ",", "e", ".", "plans", ".", "Length", ")", "\n", "stats", ".", "NewGaugeFunc", "(", "\"", "\"", ",", "\"", "\"", ",", "e", ".", "plans", ".", "Size", ")", "\n", "stats", ".", "NewGaugeFunc", "(", "\"", "\"", ",", "\"", "\"", ",", "e", ".", "plans", ".", "Capacity", ")", "\n", "stats", ".", "NewCounterFunc", "(", "\"", "\"", ",", "\"", "\"", ",", "e", ".", "plans", ".", "Evictions", ")", "\n", "stats", ".", "Publish", "(", "\"", "\"", ",", "stats", ".", "StringFunc", "(", "func", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "e", ".", "plans", ".", "Oldest", "(", ")", ")", "\n", "}", ")", ")", "\n", "http", ".", "Handle", "(", "\"", "\"", ",", "e", ")", "\n", "http", ".", "Handle", "(", "\"", "\"", ",", "e", ")", "\n", "}", ")", "\n", "return", "e", "\n", "}" ]
// NewExecutor creates a new Executor.
[ "NewExecutor", "creates", "a", "new", "Executor", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/executor.go#L93-L122
train
vitessio/vitess
go/vt/vtgate/executor.go
Execute
func (e *Executor) Execute(ctx context.Context, method string, safeSession *SafeSession, sql string, bindVars map[string]*querypb.BindVariable) (result *sqltypes.Result, err error) { span, ctx := trace.NewSpan(ctx, "executor.Execute") span.Annotate("method", method) trace.AnnotateSQL(span, sql) defer span.Finish() logStats := NewLogStats(ctx, method, sql, bindVars) result, err = e.execute(ctx, safeSession, sql, bindVars, logStats) logStats.Error = err // The mysql plugin runs an implicit rollback whenever a connection closes. // To avoid spamming the log with no-op rollback records, ignore it if // it was a no-op record (i.e. didn't issue any queries) if !(logStats.StmtType == "ROLLBACK" && logStats.ShardQueries == 0) { logStats.Send() } return result, err }
go
func (e *Executor) Execute(ctx context.Context, method string, safeSession *SafeSession, sql string, bindVars map[string]*querypb.BindVariable) (result *sqltypes.Result, err error) { span, ctx := trace.NewSpan(ctx, "executor.Execute") span.Annotate("method", method) trace.AnnotateSQL(span, sql) defer span.Finish() logStats := NewLogStats(ctx, method, sql, bindVars) result, err = e.execute(ctx, safeSession, sql, bindVars, logStats) logStats.Error = err // The mysql plugin runs an implicit rollback whenever a connection closes. // To avoid spamming the log with no-op rollback records, ignore it if // it was a no-op record (i.e. didn't issue any queries) if !(logStats.StmtType == "ROLLBACK" && logStats.ShardQueries == 0) { logStats.Send() } return result, err }
[ "func", "(", "e", "*", "Executor", ")", "Execute", "(", "ctx", "context", ".", "Context", ",", "method", "string", ",", "safeSession", "*", "SafeSession", ",", "sql", "string", ",", "bindVars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "(", "result", "*", "sqltypes", ".", "Result", ",", "err", "error", ")", "{", "span", ",", "ctx", ":=", "trace", ".", "NewSpan", "(", "ctx", ",", "\"", "\"", ")", "\n", "span", ".", "Annotate", "(", "\"", "\"", ",", "method", ")", "\n", "trace", ".", "AnnotateSQL", "(", "span", ",", "sql", ")", "\n", "defer", "span", ".", "Finish", "(", ")", "\n\n", "logStats", ":=", "NewLogStats", "(", "ctx", ",", "method", ",", "sql", ",", "bindVars", ")", "\n", "result", ",", "err", "=", "e", ".", "execute", "(", "ctx", ",", "safeSession", ",", "sql", ",", "bindVars", ",", "logStats", ")", "\n", "logStats", ".", "Error", "=", "err", "\n\n", "// The mysql plugin runs an implicit rollback whenever a connection closes.", "// To avoid spamming the log with no-op rollback records, ignore it if", "// it was a no-op record (i.e. didn't issue any queries)", "if", "!", "(", "logStats", ".", "StmtType", "==", "\"", "\"", "&&", "logStats", ".", "ShardQueries", "==", "0", ")", "{", "logStats", ".", "Send", "(", ")", "\n", "}", "\n", "return", "result", ",", "err", "\n", "}" ]
// Execute executes a non-streaming query.
[ "Execute", "executes", "a", "non", "-", "streaming", "query", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/executor.go#L125-L142
train
vitessio/vitess
go/vt/vtgate/executor.go
StreamExecute
func (e *Executor) StreamExecute(ctx context.Context, method string, safeSession *SafeSession, sql string, bindVars map[string]*querypb.BindVariable, target querypb.Target, callback func(*sqltypes.Result) error) (err error) { logStats := NewLogStats(ctx, method, sql, bindVars) logStats.StmtType = sqlparser.StmtType(sqlparser.Preview(sql)) defer logStats.Send() if bindVars == nil { bindVars = make(map[string]*querypb.BindVariable) } query, comments := sqlparser.SplitMarginComments(sql) vcursor := newVCursorImpl(ctx, safeSession, target.Keyspace, target.TabletType, comments, e, logStats) // check if this is a stream statement for messaging // TODO: support keyRange syntax if logStats.StmtType == sqlparser.StmtType(sqlparser.StmtStream) { return e.handleMessageStream(ctx, safeSession, sql, target, callback, vcursor, logStats) } plan, err := e.getPlan( vcursor, query, comments, bindVars, skipQueryPlanCache(safeSession), logStats, ) if err != nil { logStats.Error = err return err } execStart := time.Now() logStats.PlanTime = execStart.Sub(logStats.StartTime) // Some of the underlying primitives may send results one row at a time. // So, we need the ability to consolidate those into reasonable chunks. // The callback wrapper below accumulates rows and sends them as chunks // dictated by stream_buffer_size. result := &sqltypes.Result{} byteCount := 0 err = plan.Instructions.StreamExecute(vcursor, bindVars, true, func(qr *sqltypes.Result) error { // If the row has field info, send it separately. // TODO(sougou): this behavior is for handling tests because // the framework currently sends all results as one packet. if len(qr.Fields) > 0 { qrfield := &sqltypes.Result{Fields: qr.Fields} if err := callback(qrfield); err != nil { return err } } for _, row := range qr.Rows { result.Rows = append(result.Rows, row) for _, col := range row { byteCount += col.Len() } if byteCount >= e.streamSize { err := callback(result) result = &sqltypes.Result{} byteCount = 0 if err != nil { return err } } } return nil }) // Send left-over rows. if len(result.Rows) > 0 { if err := callback(result); err != nil { return err } } logStats.ExecuteTime = time.Since(execStart) return err }
go
func (e *Executor) StreamExecute(ctx context.Context, method string, safeSession *SafeSession, sql string, bindVars map[string]*querypb.BindVariable, target querypb.Target, callback func(*sqltypes.Result) error) (err error) { logStats := NewLogStats(ctx, method, sql, bindVars) logStats.StmtType = sqlparser.StmtType(sqlparser.Preview(sql)) defer logStats.Send() if bindVars == nil { bindVars = make(map[string]*querypb.BindVariable) } query, comments := sqlparser.SplitMarginComments(sql) vcursor := newVCursorImpl(ctx, safeSession, target.Keyspace, target.TabletType, comments, e, logStats) // check if this is a stream statement for messaging // TODO: support keyRange syntax if logStats.StmtType == sqlparser.StmtType(sqlparser.StmtStream) { return e.handleMessageStream(ctx, safeSession, sql, target, callback, vcursor, logStats) } plan, err := e.getPlan( vcursor, query, comments, bindVars, skipQueryPlanCache(safeSession), logStats, ) if err != nil { logStats.Error = err return err } execStart := time.Now() logStats.PlanTime = execStart.Sub(logStats.StartTime) // Some of the underlying primitives may send results one row at a time. // So, we need the ability to consolidate those into reasonable chunks. // The callback wrapper below accumulates rows and sends them as chunks // dictated by stream_buffer_size. result := &sqltypes.Result{} byteCount := 0 err = plan.Instructions.StreamExecute(vcursor, bindVars, true, func(qr *sqltypes.Result) error { // If the row has field info, send it separately. // TODO(sougou): this behavior is for handling tests because // the framework currently sends all results as one packet. if len(qr.Fields) > 0 { qrfield := &sqltypes.Result{Fields: qr.Fields} if err := callback(qrfield); err != nil { return err } } for _, row := range qr.Rows { result.Rows = append(result.Rows, row) for _, col := range row { byteCount += col.Len() } if byteCount >= e.streamSize { err := callback(result) result = &sqltypes.Result{} byteCount = 0 if err != nil { return err } } } return nil }) // Send left-over rows. if len(result.Rows) > 0 { if err := callback(result); err != nil { return err } } logStats.ExecuteTime = time.Since(execStart) return err }
[ "func", "(", "e", "*", "Executor", ")", "StreamExecute", "(", "ctx", "context", ".", "Context", ",", "method", "string", ",", "safeSession", "*", "SafeSession", ",", "sql", "string", ",", "bindVars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "target", "querypb", ".", "Target", ",", "callback", "func", "(", "*", "sqltypes", ".", "Result", ")", "error", ")", "(", "err", "error", ")", "{", "logStats", ":=", "NewLogStats", "(", "ctx", ",", "method", ",", "sql", ",", "bindVars", ")", "\n", "logStats", ".", "StmtType", "=", "sqlparser", ".", "StmtType", "(", "sqlparser", ".", "Preview", "(", "sql", ")", ")", "\n", "defer", "logStats", ".", "Send", "(", ")", "\n\n", "if", "bindVars", "==", "nil", "{", "bindVars", "=", "make", "(", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "\n", "}", "\n", "query", ",", "comments", ":=", "sqlparser", ".", "SplitMarginComments", "(", "sql", ")", "\n", "vcursor", ":=", "newVCursorImpl", "(", "ctx", ",", "safeSession", ",", "target", ".", "Keyspace", ",", "target", ".", "TabletType", ",", "comments", ",", "e", ",", "logStats", ")", "\n\n", "// check if this is a stream statement for messaging", "// TODO: support keyRange syntax", "if", "logStats", ".", "StmtType", "==", "sqlparser", ".", "StmtType", "(", "sqlparser", ".", "StmtStream", ")", "{", "return", "e", ".", "handleMessageStream", "(", "ctx", ",", "safeSession", ",", "sql", ",", "target", ",", "callback", ",", "vcursor", ",", "logStats", ")", "\n", "}", "\n\n", "plan", ",", "err", ":=", "e", ".", "getPlan", "(", "vcursor", ",", "query", ",", "comments", ",", "bindVars", ",", "skipQueryPlanCache", "(", "safeSession", ")", ",", "logStats", ",", ")", "\n", "if", "err", "!=", "nil", "{", "logStats", ".", "Error", "=", "err", "\n", "return", "err", "\n", "}", "\n\n", "execStart", ":=", "time", ".", "Now", "(", ")", "\n", "logStats", ".", "PlanTime", "=", "execStart", ".", "Sub", "(", "logStats", ".", "StartTime", ")", "\n\n", "// Some of the underlying primitives may send results one row at a time.", "// So, we need the ability to consolidate those into reasonable chunks.", "// The callback wrapper below accumulates rows and sends them as chunks", "// dictated by stream_buffer_size.", "result", ":=", "&", "sqltypes", ".", "Result", "{", "}", "\n", "byteCount", ":=", "0", "\n", "err", "=", "plan", ".", "Instructions", ".", "StreamExecute", "(", "vcursor", ",", "bindVars", ",", "true", ",", "func", "(", "qr", "*", "sqltypes", ".", "Result", ")", "error", "{", "// If the row has field info, send it separately.", "// TODO(sougou): this behavior is for handling tests because", "// the framework currently sends all results as one packet.", "if", "len", "(", "qr", ".", "Fields", ")", ">", "0", "{", "qrfield", ":=", "&", "sqltypes", ".", "Result", "{", "Fields", ":", "qr", ".", "Fields", "}", "\n", "if", "err", ":=", "callback", "(", "qrfield", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "row", ":=", "range", "qr", ".", "Rows", "{", "result", ".", "Rows", "=", "append", "(", "result", ".", "Rows", ",", "row", ")", "\n", "for", "_", ",", "col", ":=", "range", "row", "{", "byteCount", "+=", "col", ".", "Len", "(", ")", "\n", "}", "\n\n", "if", "byteCount", ">=", "e", ".", "streamSize", "{", "err", ":=", "callback", "(", "result", ")", "\n", "result", "=", "&", "sqltypes", ".", "Result", "{", "}", "\n", "byteCount", "=", "0", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n\n", "// Send left-over rows.", "if", "len", "(", "result", ".", "Rows", ")", ">", "0", "{", "if", "err", ":=", "callback", "(", "result", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "logStats", ".", "ExecuteTime", "=", "time", ".", "Since", "(", "execStart", ")", "\n\n", "return", "err", "\n", "}" ]
// StreamExecute executes a streaming query.
[ "StreamExecute", "executes", "a", "streaming", "query", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/executor.go#L1060-L1138
train
vitessio/vitess
go/vt/vtgate/executor.go
MessageStream
func (e *Executor) MessageStream(ctx context.Context, keyspace string, shard string, keyRange *topodatapb.KeyRange, name string, callback func(*sqltypes.Result) error) error { err := e.resolver.MessageStream( ctx, keyspace, shard, keyRange, name, callback, ) return formatError(err) }
go
func (e *Executor) MessageStream(ctx context.Context, keyspace string, shard string, keyRange *topodatapb.KeyRange, name string, callback func(*sqltypes.Result) error) error { err := e.resolver.MessageStream( ctx, keyspace, shard, keyRange, name, callback, ) return formatError(err) }
[ "func", "(", "e", "*", "Executor", ")", "MessageStream", "(", "ctx", "context", ".", "Context", ",", "keyspace", "string", ",", "shard", "string", ",", "keyRange", "*", "topodatapb", ".", "KeyRange", ",", "name", "string", ",", "callback", "func", "(", "*", "sqltypes", ".", "Result", ")", "error", ")", "error", "{", "err", ":=", "e", ".", "resolver", ".", "MessageStream", "(", "ctx", ",", "keyspace", ",", "shard", ",", "keyRange", ",", "name", ",", "callback", ",", ")", "\n", "return", "formatError", "(", "err", ")", "\n", "}" ]
// MessageStream is part of the vtgate service API. This is a V2 level API that's sent // to the Resolver.
[ "MessageStream", "is", "part", "of", "the", "vtgate", "service", "API", ".", "This", "is", "a", "V2", "level", "API", "that", "s", "sent", "to", "the", "Resolver", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/executor.go#L1172-L1182
train
vitessio/vitess
go/vt/vtgate/executor.go
IsKeyspaceRangeBasedSharded
func (e *Executor) IsKeyspaceRangeBasedSharded(keyspace string) bool { vschema := e.VSchema() ks, ok := vschema.Keyspaces[keyspace] if !ok { return false } if ks.Keyspace == nil { return false } return ks.Keyspace.Sharded }
go
func (e *Executor) IsKeyspaceRangeBasedSharded(keyspace string) bool { vschema := e.VSchema() ks, ok := vschema.Keyspaces[keyspace] if !ok { return false } if ks.Keyspace == nil { return false } return ks.Keyspace.Sharded }
[ "func", "(", "e", "*", "Executor", ")", "IsKeyspaceRangeBasedSharded", "(", "keyspace", "string", ")", "bool", "{", "vschema", ":=", "e", ".", "VSchema", "(", ")", "\n", "ks", ",", "ok", ":=", "vschema", ".", "Keyspaces", "[", "keyspace", "]", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "if", "ks", ".", "Keyspace", "==", "nil", "{", "return", "false", "\n", "}", "\n", "return", "ks", ".", "Keyspace", ".", "Sharded", "\n", "}" ]
// IsKeyspaceRangeBasedSharded returns true if the keyspace in the vschema is // marked as sharded.
[ "IsKeyspaceRangeBasedSharded", "returns", "true", "if", "the", "keyspace", "in", "the", "vschema", "is", "marked", "as", "sharded", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/executor.go#L1238-L1248
train
vitessio/vitess
go/vt/vtgate/executor.go
VSchema
func (e *Executor) VSchema() *vindexes.VSchema { e.mu.Lock() defer e.mu.Unlock() return e.vschema }
go
func (e *Executor) VSchema() *vindexes.VSchema { e.mu.Lock() defer e.mu.Unlock() return e.vschema }
[ "func", "(", "e", "*", "Executor", ")", "VSchema", "(", ")", "*", "vindexes", ".", "VSchema", "{", "e", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "e", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "e", ".", "vschema", "\n", "}" ]
// VSchema returns the VSchema.
[ "VSchema", "returns", "the", "VSchema", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/executor.go#L1251-L1255
train
vitessio/vitess
go/vt/vtgate/executor.go
SaveVSchema
func (e *Executor) SaveVSchema(vschema *vindexes.VSchema, stats *VSchemaStats) { e.mu.Lock() defer e.mu.Unlock() e.vschema = vschema e.vschemaStats = stats e.plans.Clear() if vschemaCounters != nil { vschemaCounters.Add("Reload", 1) } }
go
func (e *Executor) SaveVSchema(vschema *vindexes.VSchema, stats *VSchemaStats) { e.mu.Lock() defer e.mu.Unlock() e.vschema = vschema e.vschemaStats = stats e.plans.Clear() if vschemaCounters != nil { vschemaCounters.Add("Reload", 1) } }
[ "func", "(", "e", "*", "Executor", ")", "SaveVSchema", "(", "vschema", "*", "vindexes", ".", "VSchema", ",", "stats", "*", "VSchemaStats", ")", "{", "e", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "e", ".", "mu", ".", "Unlock", "(", ")", "\n", "e", ".", "vschema", "=", "vschema", "\n", "e", ".", "vschemaStats", "=", "stats", "\n", "e", ".", "plans", ".", "Clear", "(", ")", "\n\n", "if", "vschemaCounters", "!=", "nil", "{", "vschemaCounters", ".", "Add", "(", "\"", "\"", ",", "1", ")", "\n", "}", "\n\n", "}" ]
// SaveVSchema updates the vschema and stats
[ "SaveVSchema", "updates", "the", "vschema", "and", "stats" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/executor.go#L1258-L1269
train
vitessio/vitess
go/vt/vtgate/executor.go
ParseDestinationTarget
func (e *Executor) ParseDestinationTarget(targetString string) (string, topodatapb.TabletType, key.Destination, error) { destKeyspace, destTabletType, dest, err := topoproto.ParseDestination(targetString, defaultTabletType) // Set default keyspace if destKeyspace == "" && len(e.VSchema().Keyspaces) == 1 { for k := range e.VSchema().Keyspaces { destKeyspace = k } } return destKeyspace, destTabletType, dest, err }
go
func (e *Executor) ParseDestinationTarget(targetString string) (string, topodatapb.TabletType, key.Destination, error) { destKeyspace, destTabletType, dest, err := topoproto.ParseDestination(targetString, defaultTabletType) // Set default keyspace if destKeyspace == "" && len(e.VSchema().Keyspaces) == 1 { for k := range e.VSchema().Keyspaces { destKeyspace = k } } return destKeyspace, destTabletType, dest, err }
[ "func", "(", "e", "*", "Executor", ")", "ParseDestinationTarget", "(", "targetString", "string", ")", "(", "string", ",", "topodatapb", ".", "TabletType", ",", "key", ".", "Destination", ",", "error", ")", "{", "destKeyspace", ",", "destTabletType", ",", "dest", ",", "err", ":=", "topoproto", ".", "ParseDestination", "(", "targetString", ",", "defaultTabletType", ")", "\n", "// Set default keyspace", "if", "destKeyspace", "==", "\"", "\"", "&&", "len", "(", "e", ".", "VSchema", "(", ")", ".", "Keyspaces", ")", "==", "1", "{", "for", "k", ":=", "range", "e", ".", "VSchema", "(", ")", ".", "Keyspaces", "{", "destKeyspace", "=", "k", "\n", "}", "\n", "}", "\n", "return", "destKeyspace", ",", "destTabletType", ",", "dest", ",", "err", "\n", "}" ]
// ParseDestinationTarget parses destination target string and sets default keyspace if possible.
[ "ParseDestinationTarget", "parses", "destination", "target", "string", "and", "sets", "default", "keyspace", "if", "possible", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/executor.go#L1272-L1281
train
vitessio/vitess
go/vt/vtgate/executor.go
getPlan
func (e *Executor) getPlan(vcursor *vcursorImpl, sql string, comments sqlparser.MarginComments, bindVars map[string]*querypb.BindVariable, skipQueryPlanCache bool, logStats *LogStats) (*engine.Plan, error) { if logStats != nil { logStats.SQL = comments.Leading + sql + comments.Trailing logStats.BindVariables = bindVars } if e.VSchema() == nil { return nil, errors.New("vschema not initialized") } keyspace := vcursor.keyspace planKey := keyspace + vindexes.TabletTypeSuffix[vcursor.tabletType] + ":" + sql if result, ok := e.plans.Get(planKey); ok { return result.(*engine.Plan), nil } stmt, err := sqlparser.Parse(sql) if err != nil { return nil, err } if !e.normalize { plan, err := planbuilder.BuildFromStmt(sql, stmt, vcursor) if err != nil { return nil, err } if !skipQueryPlanCache && !sqlparser.SkipQueryPlanCacheDirective(stmt) { e.plans.Set(planKey, plan) } return plan, nil } // Normalize and retry. sqlparser.Normalize(stmt, bindVars, "vtg") normalized := sqlparser.String(stmt) if logStats != nil { logStats.SQL = comments.Leading + normalized + comments.Trailing logStats.BindVariables = bindVars } planKey = keyspace + vindexes.TabletTypeSuffix[vcursor.tabletType] + ":" + normalized if result, ok := e.plans.Get(planKey); ok { return result.(*engine.Plan), nil } plan, err := planbuilder.BuildFromStmt(normalized, stmt, vcursor) if err != nil { return nil, err } if !skipQueryPlanCache && !sqlparser.SkipQueryPlanCacheDirective(stmt) { e.plans.Set(planKey, plan) } return plan, nil }
go
func (e *Executor) getPlan(vcursor *vcursorImpl, sql string, comments sqlparser.MarginComments, bindVars map[string]*querypb.BindVariable, skipQueryPlanCache bool, logStats *LogStats) (*engine.Plan, error) { if logStats != nil { logStats.SQL = comments.Leading + sql + comments.Trailing logStats.BindVariables = bindVars } if e.VSchema() == nil { return nil, errors.New("vschema not initialized") } keyspace := vcursor.keyspace planKey := keyspace + vindexes.TabletTypeSuffix[vcursor.tabletType] + ":" + sql if result, ok := e.plans.Get(planKey); ok { return result.(*engine.Plan), nil } stmt, err := sqlparser.Parse(sql) if err != nil { return nil, err } if !e.normalize { plan, err := planbuilder.BuildFromStmt(sql, stmt, vcursor) if err != nil { return nil, err } if !skipQueryPlanCache && !sqlparser.SkipQueryPlanCacheDirective(stmt) { e.plans.Set(planKey, plan) } return plan, nil } // Normalize and retry. sqlparser.Normalize(stmt, bindVars, "vtg") normalized := sqlparser.String(stmt) if logStats != nil { logStats.SQL = comments.Leading + normalized + comments.Trailing logStats.BindVariables = bindVars } planKey = keyspace + vindexes.TabletTypeSuffix[vcursor.tabletType] + ":" + normalized if result, ok := e.plans.Get(planKey); ok { return result.(*engine.Plan), nil } plan, err := planbuilder.BuildFromStmt(normalized, stmt, vcursor) if err != nil { return nil, err } if !skipQueryPlanCache && !sqlparser.SkipQueryPlanCacheDirective(stmt) { e.plans.Set(planKey, plan) } return plan, nil }
[ "func", "(", "e", "*", "Executor", ")", "getPlan", "(", "vcursor", "*", "vcursorImpl", ",", "sql", "string", ",", "comments", "sqlparser", ".", "MarginComments", ",", "bindVars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "skipQueryPlanCache", "bool", ",", "logStats", "*", "LogStats", ")", "(", "*", "engine", ".", "Plan", ",", "error", ")", "{", "if", "logStats", "!=", "nil", "{", "logStats", ".", "SQL", "=", "comments", ".", "Leading", "+", "sql", "+", "comments", ".", "Trailing", "\n", "logStats", ".", "BindVariables", "=", "bindVars", "\n", "}", "\n\n", "if", "e", ".", "VSchema", "(", ")", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "keyspace", ":=", "vcursor", ".", "keyspace", "\n", "planKey", ":=", "keyspace", "+", "vindexes", ".", "TabletTypeSuffix", "[", "vcursor", ".", "tabletType", "]", "+", "\"", "\"", "+", "sql", "\n", "if", "result", ",", "ok", ":=", "e", ".", "plans", ".", "Get", "(", "planKey", ")", ";", "ok", "{", "return", "result", ".", "(", "*", "engine", ".", "Plan", ")", ",", "nil", "\n", "}", "\n", "stmt", ",", "err", ":=", "sqlparser", ".", "Parse", "(", "sql", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "!", "e", ".", "normalize", "{", "plan", ",", "err", ":=", "planbuilder", ".", "BuildFromStmt", "(", "sql", ",", "stmt", ",", "vcursor", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "!", "skipQueryPlanCache", "&&", "!", "sqlparser", ".", "SkipQueryPlanCacheDirective", "(", "stmt", ")", "{", "e", ".", "plans", ".", "Set", "(", "planKey", ",", "plan", ")", "\n", "}", "\n", "return", "plan", ",", "nil", "\n", "}", "\n\n", "// Normalize and retry.", "sqlparser", ".", "Normalize", "(", "stmt", ",", "bindVars", ",", "\"", "\"", ")", "\n", "normalized", ":=", "sqlparser", ".", "String", "(", "stmt", ")", "\n\n", "if", "logStats", "!=", "nil", "{", "logStats", ".", "SQL", "=", "comments", ".", "Leading", "+", "normalized", "+", "comments", ".", "Trailing", "\n", "logStats", ".", "BindVariables", "=", "bindVars", "\n", "}", "\n\n", "planKey", "=", "keyspace", "+", "vindexes", ".", "TabletTypeSuffix", "[", "vcursor", ".", "tabletType", "]", "+", "\"", "\"", "+", "normalized", "\n", "if", "result", ",", "ok", ":=", "e", ".", "plans", ".", "Get", "(", "planKey", ")", ";", "ok", "{", "return", "result", ".", "(", "*", "engine", ".", "Plan", ")", ",", "nil", "\n", "}", "\n", "plan", ",", "err", ":=", "planbuilder", ".", "BuildFromStmt", "(", "normalized", ",", "stmt", ",", "vcursor", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "!", "skipQueryPlanCache", "&&", "!", "sqlparser", ".", "SkipQueryPlanCacheDirective", "(", "stmt", ")", "{", "e", ".", "plans", ".", "Set", "(", "planKey", ",", "plan", ")", "\n", "}", "\n", "return", "plan", ",", "nil", "\n", "}" ]
// getPlan computes the plan for the given query. If one is in // the cache, it reuses it.
[ "getPlan", "computes", "the", "plan", "for", "the", "given", "query", ".", "If", "one", "is", "in", "the", "cache", "it", "reuses", "it", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/executor.go#L1285-L1335
train
vitessio/vitess
go/vt/vtgate/executor.go
skipQueryPlanCache
func skipQueryPlanCache(safeSession *SafeSession) bool { if safeSession == nil || safeSession.Options == nil { return false } return safeSession.Options.SkipQueryPlanCache }
go
func skipQueryPlanCache(safeSession *SafeSession) bool { if safeSession == nil || safeSession.Options == nil { return false } return safeSession.Options.SkipQueryPlanCache }
[ "func", "skipQueryPlanCache", "(", "safeSession", "*", "SafeSession", ")", "bool", "{", "if", "safeSession", "==", "nil", "||", "safeSession", ".", "Options", "==", "nil", "{", "return", "false", "\n", "}", "\n", "return", "safeSession", ".", "Options", ".", "SkipQueryPlanCache", "\n", "}" ]
// skipQueryPlanCache extracts SkipQueryPlanCache from session
[ "skipQueryPlanCache", "extracts", "SkipQueryPlanCache", "from", "session" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/executor.go#L1338-L1343
train
vitessio/vitess
go/vt/vtgate/executor.go
ServeHTTP
func (e *Executor) ServeHTTP(response http.ResponseWriter, request *http.Request) { if err := acl.CheckAccessHTTP(request, acl.DEBUGGING); err != nil { acl.SendError(response, err) return } if request.URL.Path == "/debug/query_plans" { keys := e.plans.Keys() response.Header().Set("Content-Type", "text/plain") response.Write([]byte(fmt.Sprintf("Length: %d\n", len(keys)))) for _, v := range keys { response.Write([]byte(fmt.Sprintf("%#v\n", sqlparser.TruncateForUI(v)))) if plan, ok := e.plans.Peek(v); ok { if b, err := json.MarshalIndent(plan, "", " "); err != nil { response.Write([]byte(err.Error())) } else { response.Write(b) } response.Write(([]byte)("\n\n")) } } } else if request.URL.Path == "/debug/vschema" { response.Header().Set("Content-Type", "application/json; charset=utf-8") b, err := json.MarshalIndent(e.VSchema().Keyspaces, "", " ") if err != nil { response.Write([]byte(err.Error())) return } buf := bytes.NewBuffer(nil) json.HTMLEscape(buf, b) response.Write(buf.Bytes()) } else { response.WriteHeader(http.StatusNotFound) } }
go
func (e *Executor) ServeHTTP(response http.ResponseWriter, request *http.Request) { if err := acl.CheckAccessHTTP(request, acl.DEBUGGING); err != nil { acl.SendError(response, err) return } if request.URL.Path == "/debug/query_plans" { keys := e.plans.Keys() response.Header().Set("Content-Type", "text/plain") response.Write([]byte(fmt.Sprintf("Length: %d\n", len(keys)))) for _, v := range keys { response.Write([]byte(fmt.Sprintf("%#v\n", sqlparser.TruncateForUI(v)))) if plan, ok := e.plans.Peek(v); ok { if b, err := json.MarshalIndent(plan, "", " "); err != nil { response.Write([]byte(err.Error())) } else { response.Write(b) } response.Write(([]byte)("\n\n")) } } } else if request.URL.Path == "/debug/vschema" { response.Header().Set("Content-Type", "application/json; charset=utf-8") b, err := json.MarshalIndent(e.VSchema().Keyspaces, "", " ") if err != nil { response.Write([]byte(err.Error())) return } buf := bytes.NewBuffer(nil) json.HTMLEscape(buf, b) response.Write(buf.Bytes()) } else { response.WriteHeader(http.StatusNotFound) } }
[ "func", "(", "e", "*", "Executor", ")", "ServeHTTP", "(", "response", "http", ".", "ResponseWriter", ",", "request", "*", "http", ".", "Request", ")", "{", "if", "err", ":=", "acl", ".", "CheckAccessHTTP", "(", "request", ",", "acl", ".", "DEBUGGING", ")", ";", "err", "!=", "nil", "{", "acl", ".", "SendError", "(", "response", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "request", ".", "URL", ".", "Path", "==", "\"", "\"", "{", "keys", ":=", "e", ".", "plans", ".", "Keys", "(", ")", "\n", "response", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "response", ".", "Write", "(", "[", "]", "byte", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "len", "(", "keys", ")", ")", ")", ")", "\n", "for", "_", ",", "v", ":=", "range", "keys", "{", "response", ".", "Write", "(", "[", "]", "byte", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "sqlparser", ".", "TruncateForUI", "(", "v", ")", ")", ")", ")", "\n", "if", "plan", ",", "ok", ":=", "e", ".", "plans", ".", "Peek", "(", "v", ")", ";", "ok", "{", "if", "b", ",", "err", ":=", "json", ".", "MarshalIndent", "(", "plan", ",", "\"", "\"", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "response", ".", "Write", "(", "[", "]", "byte", "(", "err", ".", "Error", "(", ")", ")", ")", "\n", "}", "else", "{", "response", ".", "Write", "(", "b", ")", "\n", "}", "\n", "response", ".", "Write", "(", "(", "[", "]", "byte", ")", "(", "\"", "\\n", "\\n", "\"", ")", ")", "\n", "}", "\n", "}", "\n", "}", "else", "if", "request", ".", "URL", ".", "Path", "==", "\"", "\"", "{", "response", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "b", ",", "err", ":=", "json", ".", "MarshalIndent", "(", "e", ".", "VSchema", "(", ")", ".", "Keyspaces", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "response", ".", "Write", "(", "[", "]", "byte", "(", "err", ".", "Error", "(", ")", ")", ")", "\n", "return", "\n", "}", "\n", "buf", ":=", "bytes", ".", "NewBuffer", "(", "nil", ")", "\n", "json", ".", "HTMLEscape", "(", "buf", ",", "b", ")", "\n", "response", ".", "Write", "(", "buf", ".", "Bytes", "(", ")", ")", "\n", "}", "else", "{", "response", ".", "WriteHeader", "(", "http", ".", "StatusNotFound", ")", "\n", "}", "\n", "}" ]
// ServeHTTP shows the current plans in the query cache.
[ "ServeHTTP", "shows", "the", "current", "plans", "in", "the", "query", "cache", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/executor.go#L1346-L1379
train
vitessio/vitess
go/vt/vtgate/executor.go
VSchemaStats
func (e *Executor) VSchemaStats() *VSchemaStats { e.mu.Lock() defer e.mu.Unlock() if e.vschemaStats == nil { return &VSchemaStats{ Error: "No VSchema loaded yet.", } } return e.vschemaStats }
go
func (e *Executor) VSchemaStats() *VSchemaStats { e.mu.Lock() defer e.mu.Unlock() if e.vschemaStats == nil { return &VSchemaStats{ Error: "No VSchema loaded yet.", } } return e.vschemaStats }
[ "func", "(", "e", "*", "Executor", ")", "VSchemaStats", "(", ")", "*", "VSchemaStats", "{", "e", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "e", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "e", ".", "vschemaStats", "==", "nil", "{", "return", "&", "VSchemaStats", "{", "Error", ":", "\"", "\"", ",", "}", "\n", "}", "\n", "return", "e", ".", "vschemaStats", "\n", "}" ]
// VSchemaStats returns the loaded vschema stats.
[ "VSchemaStats", "returns", "the", "loaded", "vschema", "stats", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/executor.go#L1387-L1396
train
vitessio/vitess
go/vt/workflow/reshardingworkflowgen/workflow.go
initCheckpoint
func initCheckpoint(keyspace string, vtworkers []string, shardsToSplit [][][]string, minHealthyRdonlyTablets, splitCmd, splitDiffDestTabletType, phaseEnableApprovals string, skipStartWorkflows bool) (*workflowpb.WorkflowCheckpoint, error) { sourceShards := 0 destShards := 0 for _, shardToSplit := range shardsToSplit { sourceShards = sourceShards + len(shardToSplit[0]) destShards = destShards + len(shardToSplit[1]) } if sourceShards == 0 || destShards == 0 { return nil, fmt.Errorf("invalid source or destination shards") } if len(vtworkers) != destShards { return nil, fmt.Errorf("there are %v vtworkers, %v destination shards: the number should be same", len(vtworkers), destShards) } splitRatio := destShards / sourceShards if minHealthyRdonlyTabletsVal, err := strconv.Atoi(minHealthyRdonlyTablets); err != nil || minHealthyRdonlyTabletsVal < splitRatio { return nil, fmt.Errorf("there are not enough rdonly tablets in source shards. You need at least %v, it got: %v", splitRatio, minHealthyRdonlyTablets) } tasks := make(map[string]*workflowpb.Task) usedVtworkersIdx := 0 for i, shardToSplit := range shardsToSplit { taskID := fmt.Sprintf("%s/%v", phaseName, i) tasks[taskID] = &workflowpb.Task{ Id: taskID, State: workflowpb.TaskState_TaskNotStarted, Attributes: map[string]string{ "source_shards": strings.Join(shardToSplit[0], ","), "destination_shards": strings.Join(shardToSplit[1], ","), "vtworkers": strings.Join(vtworkers[usedVtworkersIdx:usedVtworkersIdx+len(shardToSplit[1])], ","), }, } usedVtworkersIdx = usedVtworkersIdx + len(shardToSplit[1]) } return &workflowpb.WorkflowCheckpoint{ CodeVersion: codeVersion, Tasks: tasks, Settings: map[string]string{ "vtworkers": strings.Join(vtworkers, ","), "min_healthy_rdonly_tablets": minHealthyRdonlyTablets, "split_cmd": splitCmd, "split_diff_dest_tablet_type": splitDiffDestTabletType, "phase_enable_approvals": phaseEnableApprovals, "skip_start_workflows": fmt.Sprintf("%v", skipStartWorkflows), "workflows_count": fmt.Sprintf("%v", len(shardsToSplit)), "keyspace": keyspace, }, }, nil }
go
func initCheckpoint(keyspace string, vtworkers []string, shardsToSplit [][][]string, minHealthyRdonlyTablets, splitCmd, splitDiffDestTabletType, phaseEnableApprovals string, skipStartWorkflows bool) (*workflowpb.WorkflowCheckpoint, error) { sourceShards := 0 destShards := 0 for _, shardToSplit := range shardsToSplit { sourceShards = sourceShards + len(shardToSplit[0]) destShards = destShards + len(shardToSplit[1]) } if sourceShards == 0 || destShards == 0 { return nil, fmt.Errorf("invalid source or destination shards") } if len(vtworkers) != destShards { return nil, fmt.Errorf("there are %v vtworkers, %v destination shards: the number should be same", len(vtworkers), destShards) } splitRatio := destShards / sourceShards if minHealthyRdonlyTabletsVal, err := strconv.Atoi(minHealthyRdonlyTablets); err != nil || minHealthyRdonlyTabletsVal < splitRatio { return nil, fmt.Errorf("there are not enough rdonly tablets in source shards. You need at least %v, it got: %v", splitRatio, minHealthyRdonlyTablets) } tasks := make(map[string]*workflowpb.Task) usedVtworkersIdx := 0 for i, shardToSplit := range shardsToSplit { taskID := fmt.Sprintf("%s/%v", phaseName, i) tasks[taskID] = &workflowpb.Task{ Id: taskID, State: workflowpb.TaskState_TaskNotStarted, Attributes: map[string]string{ "source_shards": strings.Join(shardToSplit[0], ","), "destination_shards": strings.Join(shardToSplit[1], ","), "vtworkers": strings.Join(vtworkers[usedVtworkersIdx:usedVtworkersIdx+len(shardToSplit[1])], ","), }, } usedVtworkersIdx = usedVtworkersIdx + len(shardToSplit[1]) } return &workflowpb.WorkflowCheckpoint{ CodeVersion: codeVersion, Tasks: tasks, Settings: map[string]string{ "vtworkers": strings.Join(vtworkers, ","), "min_healthy_rdonly_tablets": minHealthyRdonlyTablets, "split_cmd": splitCmd, "split_diff_dest_tablet_type": splitDiffDestTabletType, "phase_enable_approvals": phaseEnableApprovals, "skip_start_workflows": fmt.Sprintf("%v", skipStartWorkflows), "workflows_count": fmt.Sprintf("%v", len(shardsToSplit)), "keyspace": keyspace, }, }, nil }
[ "func", "initCheckpoint", "(", "keyspace", "string", ",", "vtworkers", "[", "]", "string", ",", "shardsToSplit", "[", "]", "[", "]", "[", "]", "string", ",", "minHealthyRdonlyTablets", ",", "splitCmd", ",", "splitDiffDestTabletType", ",", "phaseEnableApprovals", "string", ",", "skipStartWorkflows", "bool", ")", "(", "*", "workflowpb", ".", "WorkflowCheckpoint", ",", "error", ")", "{", "sourceShards", ":=", "0", "\n", "destShards", ":=", "0", "\n", "for", "_", ",", "shardToSplit", ":=", "range", "shardsToSplit", "{", "sourceShards", "=", "sourceShards", "+", "len", "(", "shardToSplit", "[", "0", "]", ")", "\n", "destShards", "=", "destShards", "+", "len", "(", "shardToSplit", "[", "1", "]", ")", "\n", "}", "\n", "if", "sourceShards", "==", "0", "||", "destShards", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "vtworkers", ")", "!=", "destShards", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "vtworkers", ")", ",", "destShards", ")", "\n", "}", "\n\n", "splitRatio", ":=", "destShards", "/", "sourceShards", "\n", "if", "minHealthyRdonlyTabletsVal", ",", "err", ":=", "strconv", ".", "Atoi", "(", "minHealthyRdonlyTablets", ")", ";", "err", "!=", "nil", "||", "minHealthyRdonlyTabletsVal", "<", "splitRatio", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "splitRatio", ",", "minHealthyRdonlyTablets", ")", "\n", "}", "\n\n", "tasks", ":=", "make", "(", "map", "[", "string", "]", "*", "workflowpb", ".", "Task", ")", "\n", "usedVtworkersIdx", ":=", "0", "\n", "for", "i", ",", "shardToSplit", ":=", "range", "shardsToSplit", "{", "taskID", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "phaseName", ",", "i", ")", "\n", "tasks", "[", "taskID", "]", "=", "&", "workflowpb", ".", "Task", "{", "Id", ":", "taskID", ",", "State", ":", "workflowpb", ".", "TaskState_TaskNotStarted", ",", "Attributes", ":", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "strings", ".", "Join", "(", "shardToSplit", "[", "0", "]", ",", "\"", "\"", ")", ",", "\"", "\"", ":", "strings", ".", "Join", "(", "shardToSplit", "[", "1", "]", ",", "\"", "\"", ")", ",", "\"", "\"", ":", "strings", ".", "Join", "(", "vtworkers", "[", "usedVtworkersIdx", ":", "usedVtworkersIdx", "+", "len", "(", "shardToSplit", "[", "1", "]", ")", "]", ",", "\"", "\"", ")", ",", "}", ",", "}", "\n", "usedVtworkersIdx", "=", "usedVtworkersIdx", "+", "len", "(", "shardToSplit", "[", "1", "]", ")", "\n", "}", "\n", "return", "&", "workflowpb", ".", "WorkflowCheckpoint", "{", "CodeVersion", ":", "codeVersion", ",", "Tasks", ":", "tasks", ",", "Settings", ":", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "strings", ".", "Join", "(", "vtworkers", ",", "\"", "\"", ")", ",", "\"", "\"", ":", "minHealthyRdonlyTablets", ",", "\"", "\"", ":", "splitCmd", ",", "\"", "\"", ":", "splitDiffDestTabletType", ",", "\"", "\"", ":", "phaseEnableApprovals", ",", "\"", "\"", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "skipStartWorkflows", ")", ",", "\"", "\"", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "len", "(", "shardsToSplit", ")", ")", ",", "\"", "\"", ":", "keyspace", ",", "}", ",", "}", ",", "nil", "\n", "}" ]
// initCheckpoint initialize the checkpoint for keyspace reshard
[ "initCheckpoint", "initialize", "the", "checkpoint", "for", "keyspace", "reshard" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/reshardingworkflowgen/workflow.go#L191-L239
train
vitessio/vitess
go/vt/srvtopo/resolver.go
GetAllKeyspaces
func (r *Resolver) GetAllKeyspaces(ctx context.Context) ([]string, error) { keyspaces, err := r.topoServ.GetSrvKeyspaceNames(ctx, r.localCell) if err != nil { return nil, vterrors.Errorf(vtrpcpb.Code_UNKNOWN, "keyspace names fetch error: %v", err) } // FIXME(alainjobart) this should be unnecessary. The results // of ListDir are sorted, and that's the underlying topo code. // But the tests depend on this behavior now. sort.Strings(keyspaces) return keyspaces, nil }
go
func (r *Resolver) GetAllKeyspaces(ctx context.Context) ([]string, error) { keyspaces, err := r.topoServ.GetSrvKeyspaceNames(ctx, r.localCell) if err != nil { return nil, vterrors.Errorf(vtrpcpb.Code_UNKNOWN, "keyspace names fetch error: %v", err) } // FIXME(alainjobart) this should be unnecessary. The results // of ListDir are sorted, and that's the underlying topo code. // But the tests depend on this behavior now. sort.Strings(keyspaces) return keyspaces, nil }
[ "func", "(", "r", "*", "Resolver", ")", "GetAllKeyspaces", "(", "ctx", "context", ".", "Context", ")", "(", "[", "]", "string", ",", "error", ")", "{", "keyspaces", ",", "err", ":=", "r", ".", "topoServ", ".", "GetSrvKeyspaceNames", "(", "ctx", ",", "r", ".", "localCell", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_UNKNOWN", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "// FIXME(alainjobart) this should be unnecessary. The results", "// of ListDir are sorted, and that's the underlying topo code.", "// But the tests depend on this behavior now.", "sort", ".", "Strings", "(", "keyspaces", ")", "\n", "return", "keyspaces", ",", "nil", "\n", "}" ]
// GetAllKeyspaces returns all the known keyspaces in the local cell.
[ "GetAllKeyspaces", "returns", "all", "the", "known", "keyspaces", "in", "the", "local", "cell", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/srvtopo/resolver.go#L151-L161
train
vitessio/vitess
go/vt/srvtopo/resolver.go
ResolveDestination
func (r *Resolver) ResolveDestination(ctx context.Context, keyspace string, tabletType topodatapb.TabletType, destination key.Destination) ([]*ResolvedShard, error) { rss, _, err := r.ResolveDestinations(ctx, keyspace, tabletType, nil, []key.Destination{destination}) return rss, err }
go
func (r *Resolver) ResolveDestination(ctx context.Context, keyspace string, tabletType topodatapb.TabletType, destination key.Destination) ([]*ResolvedShard, error) { rss, _, err := r.ResolveDestinations(ctx, keyspace, tabletType, nil, []key.Destination{destination}) return rss, err }
[ "func", "(", "r", "*", "Resolver", ")", "ResolveDestination", "(", "ctx", "context", ".", "Context", ",", "keyspace", "string", ",", "tabletType", "topodatapb", ".", "TabletType", ",", "destination", "key", ".", "Destination", ")", "(", "[", "]", "*", "ResolvedShard", ",", "error", ")", "{", "rss", ",", "_", ",", "err", ":=", "r", ".", "ResolveDestinations", "(", "ctx", ",", "keyspace", ",", "tabletType", ",", "nil", ",", "[", "]", "key", ".", "Destination", "{", "destination", "}", ")", "\n", "return", "rss", ",", "err", "\n", "}" ]
// ResolveDestination is a shortcut to ResolveDestinations with only // one Destination, and no ids.
[ "ResolveDestination", "is", "a", "shortcut", "to", "ResolveDestinations", "with", "only", "one", "Destination", "and", "no", "ids", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/srvtopo/resolver.go#L228-L231
train
vitessio/vitess
go/vt/srvtopo/resolver.go
ValuesEqual
func ValuesEqual(vss1, vss2 [][]*querypb.Value) bool { if len(vss1) != len(vss2) { return false } for i, vs1 := range vss1 { if len(vs1) != len(vss2[i]) { return false } for j, v1 := range vs1 { if !proto.Equal(v1, vss2[i][j]) { return false } } } return true }
go
func ValuesEqual(vss1, vss2 [][]*querypb.Value) bool { if len(vss1) != len(vss2) { return false } for i, vs1 := range vss1 { if len(vs1) != len(vss2[i]) { return false } for j, v1 := range vs1 { if !proto.Equal(v1, vss2[i][j]) { return false } } } return true }
[ "func", "ValuesEqual", "(", "vss1", ",", "vss2", "[", "]", "[", "]", "*", "querypb", ".", "Value", ")", "bool", "{", "if", "len", "(", "vss1", ")", "!=", "len", "(", "vss2", ")", "{", "return", "false", "\n", "}", "\n", "for", "i", ",", "vs1", ":=", "range", "vss1", "{", "if", "len", "(", "vs1", ")", "!=", "len", "(", "vss2", "[", "i", "]", ")", "{", "return", "false", "\n", "}", "\n", "for", "j", ",", "v1", ":=", "range", "vs1", "{", "if", "!", "proto", ".", "Equal", "(", "v1", ",", "vss2", "[", "i", "]", "[", "j", "]", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// ValuesEqual is a helper method to compare arrays of values.
[ "ValuesEqual", "is", "a", "helper", "method", "to", "compare", "arrays", "of", "values", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/srvtopo/resolver.go#L234-L249
train
vitessio/vitess
go/vt/vttablet/endtoend/framework/server.go
StartServer
func StartServer(connParams, connAppDebugParams mysql.ConnParams, dbName string) error { // Setup a fake vtgate server. protocol := "resolveTest" *vtgateconn.VtgateProtocol = protocol vtgateconn.RegisterDialer(protocol, func(context.Context, string) (vtgateconn.Impl, error) { return &txResolver{ FakeVTGateConn: fakerpcvtgateconn.FakeVTGateConn{}, }, nil }) dbcfgs := dbconfigs.NewTestDBConfigs(connParams, connAppDebugParams, dbName) config := tabletenv.DefaultQsConfig config.EnableAutoCommit = true config.StrictTableACL = true config.TwoPCEnable = true config.TwoPCAbandonAge = 1 config.TwoPCCoordinatorAddress = "fake" config.EnableHotRowProtection = true Target = querypb.Target{ Keyspace: "vttest", Shard: "0", TabletType: topodatapb.TabletType_MASTER, } Server = tabletserver.NewTabletServerWithNilTopoServer(config) Server.Register() err := Server.StartService(Target, dbcfgs) if err != nil { return vterrors.Wrap(err, "could not start service") } // Start http service. ln, err := net.Listen("tcp", ":0") if err != nil { return vterrors.Wrap(err, "could not start listener") } ServerAddress = fmt.Sprintf("http://%s", ln.Addr().String()) go http.Serve(ln, nil) for { time.Sleep(10 * time.Millisecond) response, err := http.Get(fmt.Sprintf("%s/debug/vars", ServerAddress)) if err == nil { response.Body.Close() break } } return nil }
go
func StartServer(connParams, connAppDebugParams mysql.ConnParams, dbName string) error { // Setup a fake vtgate server. protocol := "resolveTest" *vtgateconn.VtgateProtocol = protocol vtgateconn.RegisterDialer(protocol, func(context.Context, string) (vtgateconn.Impl, error) { return &txResolver{ FakeVTGateConn: fakerpcvtgateconn.FakeVTGateConn{}, }, nil }) dbcfgs := dbconfigs.NewTestDBConfigs(connParams, connAppDebugParams, dbName) config := tabletenv.DefaultQsConfig config.EnableAutoCommit = true config.StrictTableACL = true config.TwoPCEnable = true config.TwoPCAbandonAge = 1 config.TwoPCCoordinatorAddress = "fake" config.EnableHotRowProtection = true Target = querypb.Target{ Keyspace: "vttest", Shard: "0", TabletType: topodatapb.TabletType_MASTER, } Server = tabletserver.NewTabletServerWithNilTopoServer(config) Server.Register() err := Server.StartService(Target, dbcfgs) if err != nil { return vterrors.Wrap(err, "could not start service") } // Start http service. ln, err := net.Listen("tcp", ":0") if err != nil { return vterrors.Wrap(err, "could not start listener") } ServerAddress = fmt.Sprintf("http://%s", ln.Addr().String()) go http.Serve(ln, nil) for { time.Sleep(10 * time.Millisecond) response, err := http.Get(fmt.Sprintf("%s/debug/vars", ServerAddress)) if err == nil { response.Body.Close() break } } return nil }
[ "func", "StartServer", "(", "connParams", ",", "connAppDebugParams", "mysql", ".", "ConnParams", ",", "dbName", "string", ")", "error", "{", "// Setup a fake vtgate server.", "protocol", ":=", "\"", "\"", "\n", "*", "vtgateconn", ".", "VtgateProtocol", "=", "protocol", "\n", "vtgateconn", ".", "RegisterDialer", "(", "protocol", ",", "func", "(", "context", ".", "Context", ",", "string", ")", "(", "vtgateconn", ".", "Impl", ",", "error", ")", "{", "return", "&", "txResolver", "{", "FakeVTGateConn", ":", "fakerpcvtgateconn", ".", "FakeVTGateConn", "{", "}", ",", "}", ",", "nil", "\n", "}", ")", "\n\n", "dbcfgs", ":=", "dbconfigs", ".", "NewTestDBConfigs", "(", "connParams", ",", "connAppDebugParams", ",", "dbName", ")", "\n\n", "config", ":=", "tabletenv", ".", "DefaultQsConfig", "\n", "config", ".", "EnableAutoCommit", "=", "true", "\n", "config", ".", "StrictTableACL", "=", "true", "\n", "config", ".", "TwoPCEnable", "=", "true", "\n", "config", ".", "TwoPCAbandonAge", "=", "1", "\n", "config", ".", "TwoPCCoordinatorAddress", "=", "\"", "\"", "\n", "config", ".", "EnableHotRowProtection", "=", "true", "\n\n", "Target", "=", "querypb", ".", "Target", "{", "Keyspace", ":", "\"", "\"", ",", "Shard", ":", "\"", "\"", ",", "TabletType", ":", "topodatapb", ".", "TabletType_MASTER", ",", "}", "\n\n", "Server", "=", "tabletserver", ".", "NewTabletServerWithNilTopoServer", "(", "config", ")", "\n", "Server", ".", "Register", "(", ")", "\n", "err", ":=", "Server", ".", "StartService", "(", "Target", ",", "dbcfgs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "vterrors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Start http service.", "ln", ",", "err", ":=", "net", ".", "Listen", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "vterrors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "ServerAddress", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ln", ".", "Addr", "(", ")", ".", "String", "(", ")", ")", "\n", "go", "http", ".", "Serve", "(", "ln", ",", "nil", ")", "\n", "for", "{", "time", ".", "Sleep", "(", "10", "*", "time", ".", "Millisecond", ")", "\n", "response", ",", "err", ":=", "http", ".", "Get", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ServerAddress", ")", ")", "\n", "if", "err", "==", "nil", "{", "response", ".", "Body", ".", "Close", "(", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// StartServer starts the server and initializes // all the global variables. This function should only be called // once at the beginning of the test.
[ "StartServer", "starts", "the", "server", "and", "initializes", "all", "the", "global", "variables", ".", "This", "function", "should", "only", "be", "called", "once", "at", "the", "beginning", "of", "the", "test", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/endtoend/framework/server.go#L54-L103
train
vitessio/vitess
go/vt/vtgate/engine/vindex_func.go
MarshalJSON
func (vf *VindexFunc) MarshalJSON() ([]byte, error) { v := struct { Opcode VindexOpcode Fields []*querypb.Field Cols []int Vindex string Value sqltypes.PlanValue }{ Opcode: vf.Opcode, Fields: vf.Fields, Cols: vf.Cols, Vindex: vf.Vindex.String(), Value: vf.Value, } return json.Marshal(v) }
go
func (vf *VindexFunc) MarshalJSON() ([]byte, error) { v := struct { Opcode VindexOpcode Fields []*querypb.Field Cols []int Vindex string Value sqltypes.PlanValue }{ Opcode: vf.Opcode, Fields: vf.Fields, Cols: vf.Cols, Vindex: vf.Vindex.String(), Value: vf.Value, } return json.Marshal(v) }
[ "func", "(", "vf", "*", "VindexFunc", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "v", ":=", "struct", "{", "Opcode", "VindexOpcode", "\n", "Fields", "[", "]", "*", "querypb", ".", "Field", "\n", "Cols", "[", "]", "int", "\n", "Vindex", "string", "\n", "Value", "sqltypes", ".", "PlanValue", "\n", "}", "{", "Opcode", ":", "vf", ".", "Opcode", ",", "Fields", ":", "vf", ".", "Fields", ",", "Cols", ":", "vf", ".", "Cols", ",", "Vindex", ":", "vf", ".", "Vindex", ".", "String", "(", ")", ",", "Value", ":", "vf", ".", "Value", ",", "}", "\n", "return", "json", ".", "Marshal", "(", "v", ")", "\n", "}" ]
// MarshalJSON serializes the VindexFunc into a JSON representation. // It's used for testing and diagnostics.
[ "MarshalJSON", "serializes", "the", "VindexFunc", "into", "a", "JSON", "representation", ".", "It", "s", "used", "for", "testing", "and", "diagnostics", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/engine/vindex_func.go#L45-L60
train
vitessio/vitess
go/trace/opentracing.go
Annotate
func (js openTracingSpan) Annotate(key string, value interface{}) { js.otSpan.SetTag(key, value) }
go
func (js openTracingSpan) Annotate(key string, value interface{}) { js.otSpan.SetTag(key, value) }
[ "func", "(", "js", "openTracingSpan", ")", "Annotate", "(", "key", "string", ",", "value", "interface", "{", "}", ")", "{", "js", ".", "otSpan", ".", "SetTag", "(", "key", ",", "value", ")", "\n", "}" ]
// Annotate will add information to an existing span
[ "Annotate", "will", "add", "information", "to", "an", "existing", "span" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/trace/opentracing.go#L37-L39
train
vitessio/vitess
go/trace/opentracing.go
AddGrpcServerOptions
func (jf openTracingService) AddGrpcServerOptions(addInterceptors func(s grpc.StreamServerInterceptor, u grpc.UnaryServerInterceptor)) { addInterceptors(otgrpc.OpenTracingStreamServerInterceptor(jf.Tracer), otgrpc.OpenTracingServerInterceptor(jf.Tracer)) }
go
func (jf openTracingService) AddGrpcServerOptions(addInterceptors func(s grpc.StreamServerInterceptor, u grpc.UnaryServerInterceptor)) { addInterceptors(otgrpc.OpenTracingStreamServerInterceptor(jf.Tracer), otgrpc.OpenTracingServerInterceptor(jf.Tracer)) }
[ "func", "(", "jf", "openTracingService", ")", "AddGrpcServerOptions", "(", "addInterceptors", "func", "(", "s", "grpc", ".", "StreamServerInterceptor", ",", "u", "grpc", ".", "UnaryServerInterceptor", ")", ")", "{", "addInterceptors", "(", "otgrpc", ".", "OpenTracingStreamServerInterceptor", "(", "jf", ".", "Tracer", ")", ",", "otgrpc", ".", "OpenTracingServerInterceptor", "(", "jf", ".", "Tracer", ")", ")", "\n", "}" ]
// AddGrpcServerOptions is part of an interface implementation
[ "AddGrpcServerOptions", "is", "part", "of", "an", "interface", "implementation" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/trace/opentracing.go#L48-L50
train
vitessio/vitess
go/trace/opentracing.go
AddGrpcClientOptions
func (jf openTracingService) AddGrpcClientOptions(addInterceptors func(s grpc.StreamClientInterceptor, u grpc.UnaryClientInterceptor)) { addInterceptors(otgrpc.OpenTracingStreamClientInterceptor(jf.Tracer), otgrpc.OpenTracingClientInterceptor(jf.Tracer)) }
go
func (jf openTracingService) AddGrpcClientOptions(addInterceptors func(s grpc.StreamClientInterceptor, u grpc.UnaryClientInterceptor)) { addInterceptors(otgrpc.OpenTracingStreamClientInterceptor(jf.Tracer), otgrpc.OpenTracingClientInterceptor(jf.Tracer)) }
[ "func", "(", "jf", "openTracingService", ")", "AddGrpcClientOptions", "(", "addInterceptors", "func", "(", "s", "grpc", ".", "StreamClientInterceptor", ",", "u", "grpc", ".", "UnaryClientInterceptor", ")", ")", "{", "addInterceptors", "(", "otgrpc", ".", "OpenTracingStreamClientInterceptor", "(", "jf", ".", "Tracer", ")", ",", "otgrpc", ".", "OpenTracingClientInterceptor", "(", "jf", ".", "Tracer", ")", ")", "\n", "}" ]
// AddGrpcClientOptions is part of an interface implementation
[ "AddGrpcClientOptions", "is", "part", "of", "an", "interface", "implementation" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/trace/opentracing.go#L53-L55
train
vitessio/vitess
go/trace/opentracing.go
NewClientSpan
func (jf openTracingService) NewClientSpan(parent Span, serviceName, label string) Span { span := jf.New(parent, label) span.Annotate("peer.service", serviceName) return span }
go
func (jf openTracingService) NewClientSpan(parent Span, serviceName, label string) Span { span := jf.New(parent, label) span.Annotate("peer.service", serviceName) return span }
[ "func", "(", "jf", "openTracingService", ")", "NewClientSpan", "(", "parent", "Span", ",", "serviceName", ",", "label", "string", ")", "Span", "{", "span", ":=", "jf", ".", "New", "(", "parent", ",", "label", ")", "\n", "span", ".", "Annotate", "(", "\"", "\"", ",", "serviceName", ")", "\n", "return", "span", "\n", "}" ]
// NewClientSpan is part of an interface implementation
[ "NewClientSpan", "is", "part", "of", "an", "interface", "implementation" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/trace/opentracing.go#L58-L62
train