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/binlog/binlogplayer/mock_dbclient.go
ExpectRequest
func (dc *MockDBClient) ExpectRequest(query string, result *sqltypes.Result, err error) { select { case <-dc.done: dc.done = make(chan struct{}) default: } dc.expect = append(dc.expect, &mockExpect{ query: query, result: result, err: err, }) }
go
func (dc *MockDBClient) ExpectRequest(query string, result *sqltypes.Result, err error) { select { case <-dc.done: dc.done = make(chan struct{}) default: } dc.expect = append(dc.expect, &mockExpect{ query: query, result: result, err: err, }) }
[ "func", "(", "dc", "*", "MockDBClient", ")", "ExpectRequest", "(", "query", "string", ",", "result", "*", "sqltypes", ".", "Result", ",", "err", "error", ")", "{", "select", "{", "case", "<-", "dc", ".", "done", ":", "dc", ".", "done", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "default", ":", "}", "\n", "dc", ".", "expect", "=", "append", "(", "dc", ".", "expect", ",", "&", "mockExpect", "{", "query", ":", "query", ",", "result", ":", "result", ",", "err", ":", "err", ",", "}", ")", "\n", "}" ]
// ExpectRequest adds an expected result to the mock. // This function should not be called conncurrently with other commands.
[ "ExpectRequest", "adds", "an", "expected", "result", "to", "the", "mock", ".", "This", "function", "should", "not", "be", "called", "conncurrently", "with", "other", "commands", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/binlog/binlogplayer/mock_dbclient.go#L53-L64
train
vitessio/vitess
go/vt/binlog/binlogplayer/mock_dbclient.go
ExpectRequestRE
func (dc *MockDBClient) ExpectRequestRE(queryRE string, result *sqltypes.Result, err error) { select { case <-dc.done: dc.done = make(chan struct{}) default: } dc.expect = append(dc.expect, &mockExpect{ query: queryRE, re: regexp.MustCompile(queryRE), result: result, err: err, }) }
go
func (dc *MockDBClient) ExpectRequestRE(queryRE string, result *sqltypes.Result, err error) { select { case <-dc.done: dc.done = make(chan struct{}) default: } dc.expect = append(dc.expect, &mockExpect{ query: queryRE, re: regexp.MustCompile(queryRE), result: result, err: err, }) }
[ "func", "(", "dc", "*", "MockDBClient", ")", "ExpectRequestRE", "(", "queryRE", "string", ",", "result", "*", "sqltypes", ".", "Result", ",", "err", "error", ")", "{", "select", "{", "case", "<-", "dc", ".", "done", ":", "dc", ".", "done", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "default", ":", "}", "\n", "dc", ".", "expect", "=", "append", "(", "dc", ".", "expect", ",", "&", "mockExpect", "{", "query", ":", "queryRE", ",", "re", ":", "regexp", ".", "MustCompile", "(", "queryRE", ")", ",", "result", ":", "result", ",", "err", ":", "err", ",", "}", ")", "\n", "}" ]
// ExpectRequestRE adds an expected result to the mock. // queryRE is a regular expression. // This function should not be called conncurrently with other commands.
[ "ExpectRequestRE", "adds", "an", "expected", "result", "to", "the", "mock", ".", "queryRE", "is", "a", "regular", "expression", ".", "This", "function", "should", "not", "be", "called", "conncurrently", "with", "other", "commands", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/binlog/binlogplayer/mock_dbclient.go#L69-L81
train
vitessio/vitess
go/vt/binlog/binlogplayer/mock_dbclient.go
Wait
func (dc *MockDBClient) Wait() { dc.t.Helper() select { case <-dc.done: return case <-time.After(5 * time.Second): dc.t.Fatalf("timeout waiting for requests, want: %v", dc.expect[dc.currentResult].query) } }
go
func (dc *MockDBClient) Wait() { dc.t.Helper() select { case <-dc.done: return case <-time.After(5 * time.Second): dc.t.Fatalf("timeout waiting for requests, want: %v", dc.expect[dc.currentResult].query) } }
[ "func", "(", "dc", "*", "MockDBClient", ")", "Wait", "(", ")", "{", "dc", ".", "t", ".", "Helper", "(", ")", "\n", "select", "{", "case", "<-", "dc", ".", "done", ":", "return", "\n", "case", "<-", "time", ".", "After", "(", "5", "*", "time", ".", "Second", ")", ":", "dc", ".", "t", ".", "Fatalf", "(", "\"", "\"", ",", "dc", ".", "expect", "[", "dc", ".", "currentResult", "]", ".", "query", ")", "\n", "}", "\n", "}" ]
// Wait waits for all expected requests to be executed. // dc.t.Fatalf is executed on 1 second timeout. Wait should // not be called concurrently with ExpectRequest.
[ "Wait", "waits", "for", "all", "expected", "requests", "to", "be", "executed", ".", "dc", ".", "t", ".", "Fatalf", "is", "executed", "on", "1", "second", "timeout", ".", "Wait", "should", "not", "be", "called", "concurrently", "with", "ExpectRequest", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/binlog/binlogplayer/mock_dbclient.go#L86-L94
train
vitessio/vitess
go/vt/binlog/binlogplayer/mock_dbclient.go
ExecuteFetch
func (dc *MockDBClient) ExecuteFetch(query string, maxrows int) (qr *sqltypes.Result, err error) { dc.t.Helper() dc.t.Logf("DBClient query: %v", query) if dc.currentResult >= len(dc.expect) { dc.t.Fatalf("DBClientMock: query: %s, no more requests are expected", query) } result := dc.expect[dc.currentResult] if result.re == nil { if query != result.query { dc.t.Fatalf("DBClientMock: query: %s, want %s", query, result.query) } } else { if !result.re.MatchString(query) { dc.t.Fatalf("DBClientMock: query: %s, must match %s", query, result.query) } } dc.currentResult++ if dc.currentResult >= len(dc.expect) { close(dc.done) } return result.result, result.err }
go
func (dc *MockDBClient) ExecuteFetch(query string, maxrows int) (qr *sqltypes.Result, err error) { dc.t.Helper() dc.t.Logf("DBClient query: %v", query) if dc.currentResult >= len(dc.expect) { dc.t.Fatalf("DBClientMock: query: %s, no more requests are expected", query) } result := dc.expect[dc.currentResult] if result.re == nil { if query != result.query { dc.t.Fatalf("DBClientMock: query: %s, want %s", query, result.query) } } else { if !result.re.MatchString(query) { dc.t.Fatalf("DBClientMock: query: %s, must match %s", query, result.query) } } dc.currentResult++ if dc.currentResult >= len(dc.expect) { close(dc.done) } return result.result, result.err }
[ "func", "(", "dc", "*", "MockDBClient", ")", "ExecuteFetch", "(", "query", "string", ",", "maxrows", "int", ")", "(", "qr", "*", "sqltypes", ".", "Result", ",", "err", "error", ")", "{", "dc", ".", "t", ".", "Helper", "(", ")", "\n", "dc", ".", "t", ".", "Logf", "(", "\"", "\"", ",", "query", ")", "\n", "if", "dc", ".", "currentResult", ">=", "len", "(", "dc", ".", "expect", ")", "{", "dc", ".", "t", ".", "Fatalf", "(", "\"", "\"", ",", "query", ")", "\n", "}", "\n", "result", ":=", "dc", ".", "expect", "[", "dc", ".", "currentResult", "]", "\n", "if", "result", ".", "re", "==", "nil", "{", "if", "query", "!=", "result", ".", "query", "{", "dc", ".", "t", ".", "Fatalf", "(", "\"", "\"", ",", "query", ",", "result", ".", "query", ")", "\n", "}", "\n", "}", "else", "{", "if", "!", "result", ".", "re", ".", "MatchString", "(", "query", ")", "{", "dc", ".", "t", ".", "Fatalf", "(", "\"", "\"", ",", "query", ",", "result", ".", "query", ")", "\n", "}", "\n", "}", "\n", "dc", ".", "currentResult", "++", "\n", "if", "dc", ".", "currentResult", ">=", "len", "(", "dc", ".", "expect", ")", "{", "close", "(", "dc", ".", "done", ")", "\n", "}", "\n", "return", "result", ".", "result", ",", "result", ".", "err", "\n", "}" ]
// ExecuteFetch is part of the DBClient interface
[ "ExecuteFetch", "is", "part", "of", "the", "DBClient", "interface" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/binlog/binlogplayer/mock_dbclient.go#L129-L150
train
vitessio/vitess
go/vt/vttablet/tabletserver/planbuilder/plan.go
PlanByName
func PlanByName(s string) (pt PlanType, ok bool) { for i, v := range planName { if v == s { return PlanType(i), true } } return NumPlans, false }
go
func PlanByName(s string) (pt PlanType, ok bool) { for i, v := range planName { if v == s { return PlanType(i), true } } return NumPlans, false }
[ "func", "PlanByName", "(", "s", "string", ")", "(", "pt", "PlanType", ",", "ok", "bool", ")", "{", "for", "i", ",", "v", ":=", "range", "planName", "{", "if", "v", "==", "s", "{", "return", "PlanType", "(", "i", ")", ",", "true", "\n", "}", "\n", "}", "\n", "return", "NumPlans", ",", "false", "\n", "}" ]
// PlanByName find a PlanType by its string name.
[ "PlanByName", "find", "a", "PlanType", "by", "its", "string", "name", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/planbuilder/plan.go#L121-L128
train
vitessio/vitess
go/vt/vttablet/tabletserver/planbuilder/plan.go
IsSelect
func (pt PlanType) IsSelect() bool { return pt == PlanPassSelect || pt == PlanSelectLock || pt == PlanSelectImpossible }
go
func (pt PlanType) IsSelect() bool { return pt == PlanPassSelect || pt == PlanSelectLock || pt == PlanSelectImpossible }
[ "func", "(", "pt", "PlanType", ")", "IsSelect", "(", ")", "bool", "{", "return", "pt", "==", "PlanPassSelect", "||", "pt", "==", "PlanSelectLock", "||", "pt", "==", "PlanSelectImpossible", "\n", "}" ]
// IsSelect returns true if PlanType is about a select query.
[ "IsSelect", "returns", "true", "if", "PlanType", "is", "about", "a", "select", "query", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/planbuilder/plan.go#L131-L133
train
vitessio/vitess
go/vt/vttablet/tabletserver/planbuilder/plan.go
MarshalJSON
func (rt ReasonType) MarshalJSON() ([]byte, error) { return ([]byte)(fmt.Sprintf("\"%s\"", rt.String())), nil }
go
func (rt ReasonType) MarshalJSON() ([]byte, error) { return ([]byte)(fmt.Sprintf("\"%s\"", rt.String())), nil }
[ "func", "(", "rt", "ReasonType", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "(", "[", "]", "byte", ")", "(", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\"", ",", "rt", ".", "String", "(", ")", ")", ")", ",", "nil", "\n", "}" ]
// MarshalJSON returns a json string for ReasonType.
[ "MarshalJSON", "returns", "a", "json", "string", "for", "ReasonType", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/planbuilder/plan.go#L178-L180
train
vitessio/vitess
go/vt/vttablet/tabletserver/planbuilder/plan.go
TableName
func (plan *Plan) TableName() sqlparser.TableIdent { var tableName sqlparser.TableIdent if plan.Table != nil { tableName = plan.Table.Name } return tableName }
go
func (plan *Plan) TableName() sqlparser.TableIdent { var tableName sqlparser.TableIdent if plan.Table != nil { tableName = plan.Table.Name } return tableName }
[ "func", "(", "plan", "*", "Plan", ")", "TableName", "(", ")", "sqlparser", ".", "TableIdent", "{", "var", "tableName", "sqlparser", ".", "TableIdent", "\n", "if", "plan", ".", "Table", "!=", "nil", "{", "tableName", "=", "plan", ".", "Table", ".", "Name", "\n", "}", "\n", "return", "tableName", "\n", "}" ]
// TableName returns the table name for the plan.
[ "TableName", "returns", "the", "table", "name", "for", "the", "plan", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/planbuilder/plan.go#L230-L236
train
vitessio/vitess
go/vt/vttablet/tabletserver/planbuilder/plan.go
Build
func Build(statement sqlparser.Statement, tables map[string]*schema.Table) (*Plan, error) { var plan *Plan err := checkForPoolingUnsafeConstructs(statement) if err != nil { return nil, err } switch stmt := statement.(type) { case *sqlparser.Union: plan, err = &Plan{ PlanID: PlanPassSelect, FieldQuery: GenerateFieldQuery(stmt), FullQuery: GenerateLimitQuery(stmt), }, nil case *sqlparser.Select: plan, err = analyzeSelect(stmt, tables) case *sqlparser.Insert: plan, err = analyzeInsert(stmt, tables) case *sqlparser.Update: plan, err = analyzeUpdate(stmt, tables) case *sqlparser.Delete: plan, err = analyzeDelete(stmt, tables) case *sqlparser.Set: plan, err = analyzeSet(stmt), nil case *sqlparser.DDL: plan, err = analyzeDDL(stmt, tables), nil case *sqlparser.Show: plan, err = &Plan{PlanID: PlanOtherRead}, nil case *sqlparser.OtherRead: plan, err = &Plan{PlanID: PlanOtherRead}, nil case *sqlparser.OtherAdmin: plan, err = &Plan{PlanID: PlanOtherAdmin}, nil default: return nil, vterrors.New(vtrpcpb.Code_INVALID_ARGUMENT, "invalid SQL") } if err != nil { return nil, err } plan.Permissions = BuildPermissions(statement) return plan, nil }
go
func Build(statement sqlparser.Statement, tables map[string]*schema.Table) (*Plan, error) { var plan *Plan err := checkForPoolingUnsafeConstructs(statement) if err != nil { return nil, err } switch stmt := statement.(type) { case *sqlparser.Union: plan, err = &Plan{ PlanID: PlanPassSelect, FieldQuery: GenerateFieldQuery(stmt), FullQuery: GenerateLimitQuery(stmt), }, nil case *sqlparser.Select: plan, err = analyzeSelect(stmt, tables) case *sqlparser.Insert: plan, err = analyzeInsert(stmt, tables) case *sqlparser.Update: plan, err = analyzeUpdate(stmt, tables) case *sqlparser.Delete: plan, err = analyzeDelete(stmt, tables) case *sqlparser.Set: plan, err = analyzeSet(stmt), nil case *sqlparser.DDL: plan, err = analyzeDDL(stmt, tables), nil case *sqlparser.Show: plan, err = &Plan{PlanID: PlanOtherRead}, nil case *sqlparser.OtherRead: plan, err = &Plan{PlanID: PlanOtherRead}, nil case *sqlparser.OtherAdmin: plan, err = &Plan{PlanID: PlanOtherAdmin}, nil default: return nil, vterrors.New(vtrpcpb.Code_INVALID_ARGUMENT, "invalid SQL") } if err != nil { return nil, err } plan.Permissions = BuildPermissions(statement) return plan, nil }
[ "func", "Build", "(", "statement", "sqlparser", ".", "Statement", ",", "tables", "map", "[", "string", "]", "*", "schema", ".", "Table", ")", "(", "*", "Plan", ",", "error", ")", "{", "var", "plan", "*", "Plan", "\n\n", "err", ":=", "checkForPoolingUnsafeConstructs", "(", "statement", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "switch", "stmt", ":=", "statement", ".", "(", "type", ")", "{", "case", "*", "sqlparser", ".", "Union", ":", "plan", ",", "err", "=", "&", "Plan", "{", "PlanID", ":", "PlanPassSelect", ",", "FieldQuery", ":", "GenerateFieldQuery", "(", "stmt", ")", ",", "FullQuery", ":", "GenerateLimitQuery", "(", "stmt", ")", ",", "}", ",", "nil", "\n", "case", "*", "sqlparser", ".", "Select", ":", "plan", ",", "err", "=", "analyzeSelect", "(", "stmt", ",", "tables", ")", "\n", "case", "*", "sqlparser", ".", "Insert", ":", "plan", ",", "err", "=", "analyzeInsert", "(", "stmt", ",", "tables", ")", "\n", "case", "*", "sqlparser", ".", "Update", ":", "plan", ",", "err", "=", "analyzeUpdate", "(", "stmt", ",", "tables", ")", "\n", "case", "*", "sqlparser", ".", "Delete", ":", "plan", ",", "err", "=", "analyzeDelete", "(", "stmt", ",", "tables", ")", "\n", "case", "*", "sqlparser", ".", "Set", ":", "plan", ",", "err", "=", "analyzeSet", "(", "stmt", ")", ",", "nil", "\n", "case", "*", "sqlparser", ".", "DDL", ":", "plan", ",", "err", "=", "analyzeDDL", "(", "stmt", ",", "tables", ")", ",", "nil", "\n", "case", "*", "sqlparser", ".", "Show", ":", "plan", ",", "err", "=", "&", "Plan", "{", "PlanID", ":", "PlanOtherRead", "}", ",", "nil", "\n", "case", "*", "sqlparser", ".", "OtherRead", ":", "plan", ",", "err", "=", "&", "Plan", "{", "PlanID", ":", "PlanOtherRead", "}", ",", "nil", "\n", "case", "*", "sqlparser", ".", "OtherAdmin", ":", "plan", ",", "err", "=", "&", "Plan", "{", "PlanID", ":", "PlanOtherAdmin", "}", ",", "nil", "\n", "default", ":", "return", "nil", ",", "vterrors", ".", "New", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "plan", ".", "Permissions", "=", "BuildPermissions", "(", "statement", ")", "\n", "return", "plan", ",", "nil", "\n", "}" ]
// Build builds a plan based on the schema.
[ "Build", "builds", "a", "plan", "based", "on", "the", "schema", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/planbuilder/plan.go#L246-L287
train
vitessio/vitess
go/vt/vttablet/tabletserver/planbuilder/plan.go
BuildStreaming
func BuildStreaming(sql string, tables map[string]*schema.Table) (*Plan, error) { statement, err := sqlparser.Parse(sql) if err != nil { return nil, err } err = checkForPoolingUnsafeConstructs(statement) if err != nil { return nil, err } plan := &Plan{ PlanID: PlanSelectStream, FullQuery: GenerateFullQuery(statement), Permissions: BuildPermissions(statement), } switch stmt := statement.(type) { case *sqlparser.Select: if stmt.Lock != "" { return nil, vterrors.New(vtrpcpb.Code_FAILED_PRECONDITION, "select with lock not allowed for streaming") } if tableName := analyzeFrom(stmt.From); !tableName.IsEmpty() { plan.setTable(tableName, tables) } case *sqlparser.OtherRead, *sqlparser.Show, *sqlparser.Union: // pass default: return nil, vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "'%v' not allowed for streaming", sqlparser.String(stmt)) } return plan, nil }
go
func BuildStreaming(sql string, tables map[string]*schema.Table) (*Plan, error) { statement, err := sqlparser.Parse(sql) if err != nil { return nil, err } err = checkForPoolingUnsafeConstructs(statement) if err != nil { return nil, err } plan := &Plan{ PlanID: PlanSelectStream, FullQuery: GenerateFullQuery(statement), Permissions: BuildPermissions(statement), } switch stmt := statement.(type) { case *sqlparser.Select: if stmt.Lock != "" { return nil, vterrors.New(vtrpcpb.Code_FAILED_PRECONDITION, "select with lock not allowed for streaming") } if tableName := analyzeFrom(stmt.From); !tableName.IsEmpty() { plan.setTable(tableName, tables) } case *sqlparser.OtherRead, *sqlparser.Show, *sqlparser.Union: // pass default: return nil, vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "'%v' not allowed for streaming", sqlparser.String(stmt)) } return plan, nil }
[ "func", "BuildStreaming", "(", "sql", "string", ",", "tables", "map", "[", "string", "]", "*", "schema", ".", "Table", ")", "(", "*", "Plan", ",", "error", ")", "{", "statement", ",", "err", ":=", "sqlparser", ".", "Parse", "(", "sql", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "err", "=", "checkForPoolingUnsafeConstructs", "(", "statement", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "plan", ":=", "&", "Plan", "{", "PlanID", ":", "PlanSelectStream", ",", "FullQuery", ":", "GenerateFullQuery", "(", "statement", ")", ",", "Permissions", ":", "BuildPermissions", "(", "statement", ")", ",", "}", "\n\n", "switch", "stmt", ":=", "statement", ".", "(", "type", ")", "{", "case", "*", "sqlparser", ".", "Select", ":", "if", "stmt", ".", "Lock", "!=", "\"", "\"", "{", "return", "nil", ",", "vterrors", ".", "New", "(", "vtrpcpb", ".", "Code_FAILED_PRECONDITION", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "tableName", ":=", "analyzeFrom", "(", "stmt", ".", "From", ")", ";", "!", "tableName", ".", "IsEmpty", "(", ")", "{", "plan", ".", "setTable", "(", "tableName", ",", "tables", ")", "\n", "}", "\n", "case", "*", "sqlparser", ".", "OtherRead", ",", "*", "sqlparser", ".", "Show", ",", "*", "sqlparser", ".", "Union", ":", "// pass", "default", ":", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_FAILED_PRECONDITION", ",", "\"", "\"", ",", "sqlparser", ".", "String", "(", "stmt", ")", ")", "\n", "}", "\n\n", "return", "plan", ",", "nil", "\n", "}" ]
// BuildStreaming builds a streaming plan based on the schema.
[ "BuildStreaming", "builds", "a", "streaming", "plan", "based", "on", "the", "schema", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/planbuilder/plan.go#L290-L322
train
vitessio/vitess
go/vt/vttablet/tabletserver/planbuilder/plan.go
BuildMessageStreaming
func BuildMessageStreaming(name string, tables map[string]*schema.Table) (*Plan, error) { plan := &Plan{ PlanID: PlanMessageStream, Table: tables[name], } if plan.Table == nil { return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "table %s not found in schema", name) } if plan.Table.Type != schema.Message { return nil, vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "'%s' is not a message table", name) } plan.Permissions = []Permission{{ TableName: plan.Table.Name.String(), Role: tableacl.WRITER, }} return plan, nil }
go
func BuildMessageStreaming(name string, tables map[string]*schema.Table) (*Plan, error) { plan := &Plan{ PlanID: PlanMessageStream, Table: tables[name], } if plan.Table == nil { return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "table %s not found in schema", name) } if plan.Table.Type != schema.Message { return nil, vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "'%s' is not a message table", name) } plan.Permissions = []Permission{{ TableName: plan.Table.Name.String(), Role: tableacl.WRITER, }} return plan, nil }
[ "func", "BuildMessageStreaming", "(", "name", "string", ",", "tables", "map", "[", "string", "]", "*", "schema", ".", "Table", ")", "(", "*", "Plan", ",", "error", ")", "{", "plan", ":=", "&", "Plan", "{", "PlanID", ":", "PlanMessageStream", ",", "Table", ":", "tables", "[", "name", "]", ",", "}", "\n", "if", "plan", ".", "Table", "==", "nil", "{", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "if", "plan", ".", "Table", ".", "Type", "!=", "schema", ".", "Message", "{", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_FAILED_PRECONDITION", ",", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "plan", ".", "Permissions", "=", "[", "]", "Permission", "{", "{", "TableName", ":", "plan", ".", "Table", ".", "Name", ".", "String", "(", ")", ",", "Role", ":", "tableacl", ".", "WRITER", ",", "}", "}", "\n", "return", "plan", ",", "nil", "\n", "}" ]
// BuildMessageStreaming builds a plan for message streaming.
[ "BuildMessageStreaming", "builds", "a", "plan", "for", "message", "streaming", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/planbuilder/plan.go#L325-L341
train
vitessio/vitess
go/vt/vtqueryserver/vtqueryserver.go
Init
func Init(dbcfgs *dbconfigs.DBConfigs) error { qs, err := initProxy(dbcfgs) if err != nil { return err } servenv.OnRun(func() { qs.Register() addStatusParts(qs) }) healthCheckTimer := timer.NewTimer(*healthCheckInterval) healthCheckTimer.Start(func() { if !qs.IsServing() { _ /* stateChanged */, healthErr := qs.SetServingType(topodatapb.TabletType_MASTER, true, nil) if healthErr != nil { log.Errorf("state %v: vtqueryserver SetServingType failed: %v", qs.GetState(), healthErr) } } }) healthCheckTimer.Trigger() servenv.OnClose(func() { healthCheckTimer.Stop() // We now leave the queryservice running during lameduck, // so stop it in OnClose(), after lameduck is over. qs.StopService() }) return nil }
go
func Init(dbcfgs *dbconfigs.DBConfigs) error { qs, err := initProxy(dbcfgs) if err != nil { return err } servenv.OnRun(func() { qs.Register() addStatusParts(qs) }) healthCheckTimer := timer.NewTimer(*healthCheckInterval) healthCheckTimer.Start(func() { if !qs.IsServing() { _ /* stateChanged */, healthErr := qs.SetServingType(topodatapb.TabletType_MASTER, true, nil) if healthErr != nil { log.Errorf("state %v: vtqueryserver SetServingType failed: %v", qs.GetState(), healthErr) } } }) healthCheckTimer.Trigger() servenv.OnClose(func() { healthCheckTimer.Stop() // We now leave the queryservice running during lameduck, // so stop it in OnClose(), after lameduck is over. qs.StopService() }) return nil }
[ "func", "Init", "(", "dbcfgs", "*", "dbconfigs", ".", "DBConfigs", ")", "error", "{", "qs", ",", "err", ":=", "initProxy", "(", "dbcfgs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "servenv", ".", "OnRun", "(", "func", "(", ")", "{", "qs", ".", "Register", "(", ")", "\n", "addStatusParts", "(", "qs", ")", "\n", "}", ")", "\n\n", "healthCheckTimer", ":=", "timer", ".", "NewTimer", "(", "*", "healthCheckInterval", ")", "\n", "healthCheckTimer", ".", "Start", "(", "func", "(", ")", "{", "if", "!", "qs", ".", "IsServing", "(", ")", "{", "_", "/* stateChanged */", ",", "healthErr", ":=", "qs", ".", "SetServingType", "(", "topodatapb", ".", "TabletType_MASTER", ",", "true", ",", "nil", ")", "\n", "if", "healthErr", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "qs", ".", "GetState", "(", ")", ",", "healthErr", ")", "\n", "}", "\n", "}", "\n", "}", ")", "\n", "healthCheckTimer", ".", "Trigger", "(", ")", "\n\n", "servenv", ".", "OnClose", "(", "func", "(", ")", "{", "healthCheckTimer", ".", "Stop", "(", ")", "\n", "// We now leave the queryservice running during lameduck,", "// so stop it in OnClose(), after lameduck is over.", "qs", ".", "StopService", "(", ")", "\n", "}", ")", "\n\n", "return", "nil", "\n", "}" ]
// Init initializes the proxy
[ "Init", "initializes", "the", "proxy" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtqueryserver/vtqueryserver.go#L70-L100
train
vitessio/vitess
go/pools/numbered.go
Unregister
func (nu *Numbered) Unregister(id int64, reason string) { success := nu.unregister(id, reason) if success { nu.recentlyUnregistered.Set( fmt.Sprintf("%v", id), &unregistered{reason: reason, timeUnregistered: time.Now()}) } }
go
func (nu *Numbered) Unregister(id int64, reason string) { success := nu.unregister(id, reason) if success { nu.recentlyUnregistered.Set( fmt.Sprintf("%v", id), &unregistered{reason: reason, timeUnregistered: time.Now()}) } }
[ "func", "(", "nu", "*", "Numbered", ")", "Unregister", "(", "id", "int64", ",", "reason", "string", ")", "{", "success", ":=", "nu", ".", "unregister", "(", "id", ",", "reason", ")", "\n", "if", "success", "{", "nu", ".", "recentlyUnregistered", ".", "Set", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "id", ")", ",", "&", "unregistered", "{", "reason", ":", "reason", ",", "timeUnregistered", ":", "time", ".", "Now", "(", ")", "}", ")", "\n", "}", "\n", "}" ]
// Unregister forgets the specified resource. If the resource is not present, it's ignored.
[ "Unregister", "forgets", "the", "specified", "resource", ".", "If", "the", "resource", "is", "not", "present", "it", "s", "ignored", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/pools/numbered.go#L88-L94
train
vitessio/vitess
go/pools/numbered.go
unregister
func (nu *Numbered) unregister(id int64, reason string) bool { nu.mu.Lock() defer nu.mu.Unlock() _, ok := nu.resources[id] delete(nu.resources, id) if len(nu.resources) == 0 { nu.empty.Broadcast() } return ok }
go
func (nu *Numbered) unregister(id int64, reason string) bool { nu.mu.Lock() defer nu.mu.Unlock() _, ok := nu.resources[id] delete(nu.resources, id) if len(nu.resources) == 0 { nu.empty.Broadcast() } return ok }
[ "func", "(", "nu", "*", "Numbered", ")", "unregister", "(", "id", "int64", ",", "reason", "string", ")", "bool", "{", "nu", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "nu", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "_", ",", "ok", ":=", "nu", ".", "resources", "[", "id", "]", "\n", "delete", "(", "nu", ".", "resources", ",", "id", ")", "\n", "if", "len", "(", "nu", ".", "resources", ")", "==", "0", "{", "nu", ".", "empty", ".", "Broadcast", "(", ")", "\n", "}", "\n", "return", "ok", "\n", "}" ]
// unregister forgets the resource, if it exists. Returns whether or not the resource existed at // time of Unregister.
[ "unregister", "forgets", "the", "resource", "if", "it", "exists", ".", "Returns", "whether", "or", "not", "the", "resource", "existed", "at", "time", "of", "Unregister", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/pools/numbered.go#L98-L108
train
vitessio/vitess
go/pools/numbered.go
Put
func (nu *Numbered) Put(id int64) { nu.mu.Lock() defer nu.mu.Unlock() if nw, ok := nu.resources[id]; ok { nw.inUse = false nw.purpose = "" nw.timeUsed = time.Now() } }
go
func (nu *Numbered) Put(id int64) { nu.mu.Lock() defer nu.mu.Unlock() if nw, ok := nu.resources[id]; ok { nw.inUse = false nw.purpose = "" nw.timeUsed = time.Now() } }
[ "func", "(", "nu", "*", "Numbered", ")", "Put", "(", "id", "int64", ")", "{", "nu", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "nu", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "nw", ",", "ok", ":=", "nu", ".", "resources", "[", "id", "]", ";", "ok", "{", "nw", ".", "inUse", "=", "false", "\n", "nw", ".", "purpose", "=", "\"", "\"", "\n", "nw", ".", "timeUsed", "=", "time", ".", "Now", "(", ")", "\n", "}", "\n", "}" ]
// Put unlocks a resource for someone else to use.
[ "Put", "unlocks", "a", "resource", "for", "someone", "else", "to", "use", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/pools/numbered.go#L133-L141
train
vitessio/vitess
go/pools/numbered.go
GetAll
func (nu *Numbered) GetAll() (vals []interface{}) { nu.mu.Lock() defer nu.mu.Unlock() vals = make([]interface{}, 0, len(nu.resources)) for _, nw := range nu.resources { vals = append(vals, nw.val) } return vals }
go
func (nu *Numbered) GetAll() (vals []interface{}) { nu.mu.Lock() defer nu.mu.Unlock() vals = make([]interface{}, 0, len(nu.resources)) for _, nw := range nu.resources { vals = append(vals, nw.val) } return vals }
[ "func", "(", "nu", "*", "Numbered", ")", "GetAll", "(", ")", "(", "vals", "[", "]", "interface", "{", "}", ")", "{", "nu", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "nu", ".", "mu", ".", "Unlock", "(", ")", "\n", "vals", "=", "make", "(", "[", "]", "interface", "{", "}", ",", "0", ",", "len", "(", "nu", ".", "resources", ")", ")", "\n", "for", "_", ",", "nw", ":=", "range", "nu", ".", "resources", "{", "vals", "=", "append", "(", "vals", ",", "nw", ".", "val", ")", "\n", "}", "\n", "return", "vals", "\n", "}" ]
// GetAll returns the list of all resources in the pool.
[ "GetAll", "returns", "the", "list", "of", "all", "resources", "in", "the", "pool", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/pools/numbered.go#L144-L152
train
vitessio/vitess
go/pools/numbered.go
GetOutdated
func (nu *Numbered) GetOutdated(age time.Duration, purpose string) (vals []interface{}) { nu.mu.Lock() defer nu.mu.Unlock() now := time.Now() for _, nw := range nu.resources { if nw.inUse || !nw.enforceTimeout { continue } if nw.timeCreated.Add(age).Sub(now) <= 0 { nw.inUse = true nw.purpose = purpose vals = append(vals, nw.val) } } return vals }
go
func (nu *Numbered) GetOutdated(age time.Duration, purpose string) (vals []interface{}) { nu.mu.Lock() defer nu.mu.Unlock() now := time.Now() for _, nw := range nu.resources { if nw.inUse || !nw.enforceTimeout { continue } if nw.timeCreated.Add(age).Sub(now) <= 0 { nw.inUse = true nw.purpose = purpose vals = append(vals, nw.val) } } return vals }
[ "func", "(", "nu", "*", "Numbered", ")", "GetOutdated", "(", "age", "time", ".", "Duration", ",", "purpose", "string", ")", "(", "vals", "[", "]", "interface", "{", "}", ")", "{", "nu", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "nu", ".", "mu", ".", "Unlock", "(", ")", "\n", "now", ":=", "time", ".", "Now", "(", ")", "\n", "for", "_", ",", "nw", ":=", "range", "nu", ".", "resources", "{", "if", "nw", ".", "inUse", "||", "!", "nw", ".", "enforceTimeout", "{", "continue", "\n", "}", "\n", "if", "nw", ".", "timeCreated", ".", "Add", "(", "age", ")", ".", "Sub", "(", "now", ")", "<=", "0", "{", "nw", ".", "inUse", "=", "true", "\n", "nw", ".", "purpose", "=", "purpose", "\n", "vals", "=", "append", "(", "vals", ",", "nw", ".", "val", ")", "\n", "}", "\n", "}", "\n", "return", "vals", "\n", "}" ]
// GetOutdated returns a list of resources that are older than age, and locks them. // It does not return any resources that are already locked.
[ "GetOutdated", "returns", "a", "list", "of", "resources", "that", "are", "older", "than", "age", "and", "locks", "them", ".", "It", "does", "not", "return", "any", "resources", "that", "are", "already", "locked", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/pools/numbered.go#L156-L171
train
vitessio/vitess
go/pools/numbered.go
GetIdle
func (nu *Numbered) GetIdle(timeout time.Duration, purpose string) (vals []interface{}) { nu.mu.Lock() defer nu.mu.Unlock() now := time.Now() for _, nw := range nu.resources { if nw.inUse { continue } if nw.timeUsed.Add(timeout).Sub(now) <= 0 { nw.inUse = true nw.purpose = purpose vals = append(vals, nw.val) } } return vals }
go
func (nu *Numbered) GetIdle(timeout time.Duration, purpose string) (vals []interface{}) { nu.mu.Lock() defer nu.mu.Unlock() now := time.Now() for _, nw := range nu.resources { if nw.inUse { continue } if nw.timeUsed.Add(timeout).Sub(now) <= 0 { nw.inUse = true nw.purpose = purpose vals = append(vals, nw.val) } } return vals }
[ "func", "(", "nu", "*", "Numbered", ")", "GetIdle", "(", "timeout", "time", ".", "Duration", ",", "purpose", "string", ")", "(", "vals", "[", "]", "interface", "{", "}", ")", "{", "nu", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "nu", ".", "mu", ".", "Unlock", "(", ")", "\n", "now", ":=", "time", ".", "Now", "(", ")", "\n", "for", "_", ",", "nw", ":=", "range", "nu", ".", "resources", "{", "if", "nw", ".", "inUse", "{", "continue", "\n", "}", "\n", "if", "nw", ".", "timeUsed", ".", "Add", "(", "timeout", ")", ".", "Sub", "(", "now", ")", "<=", "0", "{", "nw", ".", "inUse", "=", "true", "\n", "nw", ".", "purpose", "=", "purpose", "\n", "vals", "=", "append", "(", "vals", ",", "nw", ".", "val", ")", "\n", "}", "\n", "}", "\n", "return", "vals", "\n", "}" ]
// GetIdle returns a list of resurces that have been idle for longer // than timeout, and locks them. It does not return any resources that // are already locked.
[ "GetIdle", "returns", "a", "list", "of", "resurces", "that", "have", "been", "idle", "for", "longer", "than", "timeout", "and", "locks", "them", ".", "It", "does", "not", "return", "any", "resources", "that", "are", "already", "locked", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/pools/numbered.go#L176-L191
train
vitessio/vitess
go/pools/numbered.go
WaitForEmpty
func (nu *Numbered) WaitForEmpty() { nu.mu.Lock() defer nu.mu.Unlock() for len(nu.resources) != 0 { nu.empty.Wait() } }
go
func (nu *Numbered) WaitForEmpty() { nu.mu.Lock() defer nu.mu.Unlock() for len(nu.resources) != 0 { nu.empty.Wait() } }
[ "func", "(", "nu", "*", "Numbered", ")", "WaitForEmpty", "(", ")", "{", "nu", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "nu", ".", "mu", ".", "Unlock", "(", ")", "\n", "for", "len", "(", "nu", ".", "resources", ")", "!=", "0", "{", "nu", ".", "empty", ".", "Wait", "(", ")", "\n", "}", "\n", "}" ]
// WaitForEmpty returns as soon as the pool becomes empty
[ "WaitForEmpty", "returns", "as", "soon", "as", "the", "pool", "becomes", "empty" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/pools/numbered.go#L194-L200
train
vitessio/vitess
go/mysql/auth_server.go
RegisterAuthServerImpl
func RegisterAuthServerImpl(name string, authServer AuthServer) { if _, ok := authServers[name]; ok { log.Fatalf("AuthServer named %v already exists", name) } authServers[name] = authServer }
go
func RegisterAuthServerImpl(name string, authServer AuthServer) { if _, ok := authServers[name]; ok { log.Fatalf("AuthServer named %v already exists", name) } authServers[name] = authServer }
[ "func", "RegisterAuthServerImpl", "(", "name", "string", ",", "authServer", "AuthServer", ")", "{", "if", "_", ",", "ok", ":=", "authServers", "[", "name", "]", ";", "ok", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "authServers", "[", "name", "]", "=", "authServer", "\n", "}" ]
// RegisterAuthServerImpl registers an implementations of AuthServer.
[ "RegisterAuthServerImpl", "registers", "an", "implementations", "of", "AuthServer", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/auth_server.go#L86-L91
train
vitessio/vitess
go/mysql/auth_server.go
GetAuthServer
func GetAuthServer(name string) AuthServer { authServer, ok := authServers[name] if !ok { log.Exitf("no AuthServer name %v registered", name) } return authServer }
go
func GetAuthServer(name string) AuthServer { authServer, ok := authServers[name] if !ok { log.Exitf("no AuthServer name %v registered", name) } return authServer }
[ "func", "GetAuthServer", "(", "name", "string", ")", "AuthServer", "{", "authServer", ",", "ok", ":=", "authServers", "[", "name", "]", "\n", "if", "!", "ok", "{", "log", ".", "Exitf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "return", "authServer", "\n", "}" ]
// GetAuthServer returns an AuthServer by name, or log.Exitf.
[ "GetAuthServer", "returns", "an", "AuthServer", "by", "name", "or", "log", ".", "Exitf", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/auth_server.go#L94-L100
train
vitessio/vitess
go/mysql/auth_server.go
NewSalt
func NewSalt() ([]byte, error) { salt := make([]byte, 20) if _, err := rand.Read(salt); err != nil { return nil, err } // Salt must be a legal UTF8 string. for i := 0; i < len(salt); i++ { salt[i] &= 0x7f if salt[i] == '\x00' || salt[i] == '$' { salt[i]++ } } return salt, nil }
go
func NewSalt() ([]byte, error) { salt := make([]byte, 20) if _, err := rand.Read(salt); err != nil { return nil, err } // Salt must be a legal UTF8 string. for i := 0; i < len(salt); i++ { salt[i] &= 0x7f if salt[i] == '\x00' || salt[i] == '$' { salt[i]++ } } return salt, nil }
[ "func", "NewSalt", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "salt", ":=", "make", "(", "[", "]", "byte", ",", "20", ")", "\n", "if", "_", ",", "err", ":=", "rand", ".", "Read", "(", "salt", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Salt must be a legal UTF8 string.", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "salt", ")", ";", "i", "++", "{", "salt", "[", "i", "]", "&=", "0x7f", "\n", "if", "salt", "[", "i", "]", "==", "'\\x00'", "||", "salt", "[", "i", "]", "==", "'$'", "{", "salt", "[", "i", "]", "++", "\n", "}", "\n", "}", "\n\n", "return", "salt", ",", "nil", "\n", "}" ]
// NewSalt returns a 20 character salt.
[ "NewSalt", "returns", "a", "20", "character", "salt", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/auth_server.go#L103-L118
train
vitessio/vitess
go/mysql/auth_server.go
ScramblePassword
func ScramblePassword(salt, password []byte) []byte { if len(password) == 0 { return nil } // stage1Hash = SHA1(password) crypt := sha1.New() crypt.Write(password) stage1 := crypt.Sum(nil) // scrambleHash = SHA1(salt + SHA1(stage1Hash)) // inner Hash crypt.Reset() crypt.Write(stage1) hash := crypt.Sum(nil) // outer Hash crypt.Reset() crypt.Write(salt) crypt.Write(hash) scramble := crypt.Sum(nil) // token = scrambleHash XOR stage1Hash for i := range scramble { scramble[i] ^= stage1[i] } return scramble }
go
func ScramblePassword(salt, password []byte) []byte { if len(password) == 0 { return nil } // stage1Hash = SHA1(password) crypt := sha1.New() crypt.Write(password) stage1 := crypt.Sum(nil) // scrambleHash = SHA1(salt + SHA1(stage1Hash)) // inner Hash crypt.Reset() crypt.Write(stage1) hash := crypt.Sum(nil) // outer Hash crypt.Reset() crypt.Write(salt) crypt.Write(hash) scramble := crypt.Sum(nil) // token = scrambleHash XOR stage1Hash for i := range scramble { scramble[i] ^= stage1[i] } return scramble }
[ "func", "ScramblePassword", "(", "salt", ",", "password", "[", "]", "byte", ")", "[", "]", "byte", "{", "if", "len", "(", "password", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "// stage1Hash = SHA1(password)", "crypt", ":=", "sha1", ".", "New", "(", ")", "\n", "crypt", ".", "Write", "(", "password", ")", "\n", "stage1", ":=", "crypt", ".", "Sum", "(", "nil", ")", "\n\n", "// scrambleHash = SHA1(salt + SHA1(stage1Hash))", "// inner Hash", "crypt", ".", "Reset", "(", ")", "\n", "crypt", ".", "Write", "(", "stage1", ")", "\n", "hash", ":=", "crypt", ".", "Sum", "(", "nil", ")", "\n", "// outer Hash", "crypt", ".", "Reset", "(", ")", "\n", "crypt", ".", "Write", "(", "salt", ")", "\n", "crypt", ".", "Write", "(", "hash", ")", "\n", "scramble", ":=", "crypt", ".", "Sum", "(", "nil", ")", "\n\n", "// token = scrambleHash XOR stage1Hash", "for", "i", ":=", "range", "scramble", "{", "scramble", "[", "i", "]", "^=", "stage1", "[", "i", "]", "\n", "}", "\n", "return", "scramble", "\n", "}" ]
// ScramblePassword computes the hash of the password using 4.1+ method.
[ "ScramblePassword", "computes", "the", "hash", "of", "the", "password", "using", "4", ".", "1", "+", "method", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/auth_server.go#L121-L147
train
vitessio/vitess
go/mysql/auth_server.go
authServerDialogSwitchData
func authServerDialogSwitchData() []byte { result := make([]byte, len(mysqlDialogMessage)+2) result[0] = mysqlDialogAskPassword writeNullString(result, 1, mysqlDialogMessage) return result }
go
func authServerDialogSwitchData() []byte { result := make([]byte, len(mysqlDialogMessage)+2) result[0] = mysqlDialogAskPassword writeNullString(result, 1, mysqlDialogMessage) return result }
[ "func", "authServerDialogSwitchData", "(", ")", "[", "]", "byte", "{", "result", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "mysqlDialogMessage", ")", "+", "2", ")", "\n", "result", "[", "0", "]", "=", "mysqlDialogAskPassword", "\n", "writeNullString", "(", "result", ",", "1", ",", "mysqlDialogMessage", ")", "\n", "return", "result", "\n", "}" ]
// authServerDialogSwitchData is a helper method to return the data // needed in the AuthSwitchRequest packet for the dialog plugin // to ask for a password.
[ "authServerDialogSwitchData", "is", "a", "helper", "method", "to", "return", "the", "data", "needed", "in", "the", "AuthSwitchRequest", "packet", "for", "the", "dialog", "plugin", "to", "ask", "for", "a", "password", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/auth_server.go#L209-L214
train
vitessio/vitess
go/mysql/auth_server.go
AuthServerReadPacketString
func AuthServerReadPacketString(c *Conn) (string, error) { // Read a packet, the password is the payload, as a // zero terminated string. data, err := c.ReadPacket() if err != nil { return "", err } if len(data) == 0 || data[len(data)-1] != 0 { return "", vterrors.Errorf(vtrpc.Code_INTERNAL, "received invalid response packet, datalen=%v", len(data)) } return string(data[:len(data)-1]), nil }
go
func AuthServerReadPacketString(c *Conn) (string, error) { // Read a packet, the password is the payload, as a // zero terminated string. data, err := c.ReadPacket() if err != nil { return "", err } if len(data) == 0 || data[len(data)-1] != 0 { return "", vterrors.Errorf(vtrpc.Code_INTERNAL, "received invalid response packet, datalen=%v", len(data)) } return string(data[:len(data)-1]), nil }
[ "func", "AuthServerReadPacketString", "(", "c", "*", "Conn", ")", "(", "string", ",", "error", ")", "{", "// Read a packet, the password is the payload, as a", "// zero terminated string.", "data", ",", "err", ":=", "c", ".", "ReadPacket", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "len", "(", "data", ")", "==", "0", "||", "data", "[", "len", "(", "data", ")", "-", "1", "]", "!=", "0", "{", "return", "\"", "\"", ",", "vterrors", ".", "Errorf", "(", "vtrpc", ".", "Code_INTERNAL", ",", "\"", "\"", ",", "len", "(", "data", ")", ")", "\n", "}", "\n", "return", "string", "(", "data", "[", ":", "len", "(", "data", ")", "-", "1", "]", ")", ",", "nil", "\n", "}" ]
// AuthServerReadPacketString is a helper method to read a packet // as a null terminated string. It is used by the mysql_clear_password // and dialog plugins.
[ "AuthServerReadPacketString", "is", "a", "helper", "method", "to", "read", "a", "packet", "as", "a", "null", "terminated", "string", ".", "It", "is", "used", "by", "the", "mysql_clear_password", "and", "dialog", "plugins", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/auth_server.go#L219-L230
train
vitessio/vitess
go/mysql/auth_server.go
AuthServerNegotiateClearOrDialog
func AuthServerNegotiateClearOrDialog(c *Conn, method string) (string, error) { switch method { case MysqlClearPassword: // The password is the next packet in plain text. return AuthServerReadPacketString(c) case MysqlDialog: return AuthServerReadPacketString(c) default: return "", vterrors.Errorf(vtrpc.Code_INTERNAL, "unrecognized method: %v", method) } }
go
func AuthServerNegotiateClearOrDialog(c *Conn, method string) (string, error) { switch method { case MysqlClearPassword: // The password is the next packet in plain text. return AuthServerReadPacketString(c) case MysqlDialog: return AuthServerReadPacketString(c) default: return "", vterrors.Errorf(vtrpc.Code_INTERNAL, "unrecognized method: %v", method) } }
[ "func", "AuthServerNegotiateClearOrDialog", "(", "c", "*", "Conn", ",", "method", "string", ")", "(", "string", ",", "error", ")", "{", "switch", "method", "{", "case", "MysqlClearPassword", ":", "// The password is the next packet in plain text.", "return", "AuthServerReadPacketString", "(", "c", ")", "\n\n", "case", "MysqlDialog", ":", "return", "AuthServerReadPacketString", "(", "c", ")", "\n\n", "default", ":", "return", "\"", "\"", ",", "vterrors", ".", "Errorf", "(", "vtrpc", ".", "Code_INTERNAL", ",", "\"", "\"", ",", "method", ")", "\n", "}", "\n", "}" ]
// AuthServerNegotiateClearOrDialog will finish a negotiation based on // the method type for the connection. Only supports // MysqlClearPassword and MysqlDialog.
[ "AuthServerNegotiateClearOrDialog", "will", "finish", "a", "negotiation", "based", "on", "the", "method", "type", "for", "the", "connection", ".", "Only", "supports", "MysqlClearPassword", "and", "MysqlDialog", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/auth_server.go#L235-L247
train
vitessio/vitess
go/sqlescape/ids.go
EscapeID
func EscapeID(in string) string { var buf bytes.Buffer WriteEscapeID(&buf, in) return buf.String() }
go
func EscapeID(in string) string { var buf bytes.Buffer WriteEscapeID(&buf, in) return buf.String() }
[ "func", "EscapeID", "(", "in", "string", ")", "string", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "WriteEscapeID", "(", "&", "buf", ",", "in", ")", "\n", "return", "buf", ".", "String", "(", ")", "\n", "}" ]
// EscapeID returns a backticked identifier given an input string.
[ "EscapeID", "returns", "a", "backticked", "identifier", "given", "an", "input", "string", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqlescape/ids.go#L21-L25
train
vitessio/vitess
go/sqlescape/ids.go
WriteEscapeID
func WriteEscapeID(buf *bytes.Buffer, in string) { buf.WriteByte('`') for _, c := range in { buf.WriteRune(c) if c == '`' { buf.WriteByte('`') } } buf.WriteByte('`') }
go
func WriteEscapeID(buf *bytes.Buffer, in string) { buf.WriteByte('`') for _, c := range in { buf.WriteRune(c) if c == '`' { buf.WriteByte('`') } } buf.WriteByte('`') }
[ "func", "WriteEscapeID", "(", "buf", "*", "bytes", ".", "Buffer", ",", "in", "string", ")", "{", "buf", ".", "WriteByte", "(", "'`'", ")", "\n", "for", "_", ",", "c", ":=", "range", "in", "{", "buf", ".", "WriteRune", "(", "c", ")", "\n", "if", "c", "==", "'`'", "{", "buf", ".", "WriteByte", "(", "'`'", ")", "\n", "}", "\n", "}", "\n", "buf", ".", "WriteByte", "(", "'`'", ")", "\n", "}" ]
// WriteEscapeID writes a backticked identifier from an input string into buf.
[ "WriteEscapeID", "writes", "a", "backticked", "identifier", "from", "an", "input", "string", "into", "buf", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqlescape/ids.go#L28-L37
train
vitessio/vitess
go/vt/vttablet/tabletmanager/healthcheck.go
Class
func (r *HealthRecord) Class() string { switch { case r.Error != nil: return "unhealthy" case r.ReplicationDelay > *degradedThreshold: return "unhappy" default: return "healthy" } }
go
func (r *HealthRecord) Class() string { switch { case r.Error != nil: return "unhealthy" case r.ReplicationDelay > *degradedThreshold: return "unhappy" default: return "healthy" } }
[ "func", "(", "r", "*", "HealthRecord", ")", "Class", "(", ")", "string", "{", "switch", "{", "case", "r", ".", "Error", "!=", "nil", ":", "return", "\"", "\"", "\n", "case", "r", ".", "ReplicationDelay", ">", "*", "degradedThreshold", ":", "return", "\"", "\"", "\n", "default", ":", "return", "\"", "\"", "\n", "}", "\n", "}" ]
// Class returns a human-readable one word version of the health state.
[ "Class", "returns", "a", "human", "-", "readable", "one", "word", "version", "of", "the", "health", "state", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/healthcheck.go#L67-L76
train
vitessio/vitess
go/vt/vttablet/tabletmanager/healthcheck.go
HTML
func (r *HealthRecord) HTML() template.HTML { switch { case r.Error != nil: return template.HTML(fmt.Sprintf("unhealthy: %v", r.Error)) case r.ReplicationDelay > *degradedThreshold: return template.HTML(fmt.Sprintf("unhappy: %v behind on replication", r.ReplicationDelay)) default: html := "healthy" if r.ReplicationDelay > 0 { html += fmt.Sprintf(": only %v behind on replication", r.ReplicationDelay) } if r.IgnoredError != nil { html += fmt.Sprintf(" (ignored error: %v, matches expression: %v)", r.IgnoredError, r.IgnoreErrorExpr) } return template.HTML(html) } }
go
func (r *HealthRecord) HTML() template.HTML { switch { case r.Error != nil: return template.HTML(fmt.Sprintf("unhealthy: %v", r.Error)) case r.ReplicationDelay > *degradedThreshold: return template.HTML(fmt.Sprintf("unhappy: %v behind on replication", r.ReplicationDelay)) default: html := "healthy" if r.ReplicationDelay > 0 { html += fmt.Sprintf(": only %v behind on replication", r.ReplicationDelay) } if r.IgnoredError != nil { html += fmt.Sprintf(" (ignored error: %v, matches expression: %v)", r.IgnoredError, r.IgnoreErrorExpr) } return template.HTML(html) } }
[ "func", "(", "r", "*", "HealthRecord", ")", "HTML", "(", ")", "template", ".", "HTML", "{", "switch", "{", "case", "r", ".", "Error", "!=", "nil", ":", "return", "template", ".", "HTML", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "r", ".", "Error", ")", ")", "\n", "case", "r", ".", "ReplicationDelay", ">", "*", "degradedThreshold", ":", "return", "template", ".", "HTML", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "r", ".", "ReplicationDelay", ")", ")", "\n", "default", ":", "html", ":=", "\"", "\"", "\n", "if", "r", ".", "ReplicationDelay", ">", "0", "{", "html", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "r", ".", "ReplicationDelay", ")", "\n", "}", "\n", "if", "r", ".", "IgnoredError", "!=", "nil", "{", "html", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "r", ".", "IgnoredError", ",", "r", ".", "IgnoreErrorExpr", ")", "\n", "}", "\n", "return", "template", ".", "HTML", "(", "html", ")", "\n", "}", "\n", "}" ]
// HTML returns an HTML version to be displayed on UIs.
[ "HTML", "returns", "an", "HTML", "version", "to", "be", "displayed", "on", "UIs", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/healthcheck.go#L79-L95
train
vitessio/vitess
go/vt/vttablet/tabletmanager/healthcheck.go
ErrorString
func (r *HealthRecord) ErrorString() string { if r.Error == nil { return "" } return r.Error.Error() }
go
func (r *HealthRecord) ErrorString() string { if r.Error == nil { return "" } return r.Error.Error() }
[ "func", "(", "r", "*", "HealthRecord", ")", "ErrorString", "(", ")", "string", "{", "if", "r", ".", "Error", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "r", ".", "Error", ".", "Error", "(", ")", "\n", "}" ]
// ErrorString returns Error as a string.
[ "ErrorString", "returns", "Error", "as", "a", "string", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/healthcheck.go#L103-L108
train
vitessio/vitess
go/vt/vttablet/tabletmanager/healthcheck.go
IgnoredErrorString
func (r *HealthRecord) IgnoredErrorString() string { if r.IgnoredError == nil { return "" } return r.IgnoredError.Error() }
go
func (r *HealthRecord) IgnoredErrorString() string { if r.IgnoredError == nil { return "" } return r.IgnoredError.Error() }
[ "func", "(", "r", "*", "HealthRecord", ")", "IgnoredErrorString", "(", ")", "string", "{", "if", "r", ".", "IgnoredError", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "r", ".", "IgnoredError", ".", "Error", "(", ")", "\n", "}" ]
// IgnoredErrorString returns IgnoredError as a string.
[ "IgnoredErrorString", "returns", "IgnoredError", "as", "a", "string", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/healthcheck.go#L111-L116
train
vitessio/vitess
go/vt/vttablet/tabletmanager/healthcheck.go
ConfigHTML
func ConfigHTML() template.HTML { return template.HTML(fmt.Sprintf( "healthCheckInterval: %v; degradedThreshold: %v; unhealthyThreshold: %v", healthCheckInterval, degradedThreshold, unhealthyThreshold)) }
go
func ConfigHTML() template.HTML { return template.HTML(fmt.Sprintf( "healthCheckInterval: %v; degradedThreshold: %v; unhealthyThreshold: %v", healthCheckInterval, degradedThreshold, unhealthyThreshold)) }
[ "func", "ConfigHTML", "(", ")", "template", ".", "HTML", "{", "return", "template", ".", "HTML", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "healthCheckInterval", ",", "degradedThreshold", ",", "unhealthyThreshold", ")", ")", "\n", "}" ]
// ConfigHTML returns a formatted summary of health checking config values.
[ "ConfigHTML", "returns", "a", "formatted", "summary", "of", "health", "checking", "config", "values", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/healthcheck.go#L131-L135
train
vitessio/vitess
go/vt/vttablet/tabletmanager/healthcheck.go
terminateHealthChecks
func (agent *ActionAgent) terminateHealthChecks() { // No need to check for error, only a canceled batchCtx would fail this. agent.lock(agent.batchCtx) defer agent.unlock() log.Info("agent.terminateHealthChecks is starting") // read the current tablet record tablet := agent.Tablet() if !topo.IsSubjectToLameduck(tablet.Type) { // If we're MASTER, SPARE, WORKER, etc. then we // shouldn't enter lameduck. We do lameduck to not // trigger errors on clients. log.Infof("Tablet in state %v, not entering lameduck", tablet.Type) return } // Go lameduck for gracePeriod. // We've already checked above that we're not MASTER. // Enter new lameduck mode for gracePeriod, then shut down // queryservice. New lameduck mode means keep accepting // queries, but advertise unhealthy. After we return from // this synchronous OnTermSync hook, servenv may decide to // wait even longer, for the rest of the time specified by its // own "-lameduck-period" flag. During that extra period, // queryservice will be in old lameduck mode, meaning stay // alive but reject new queries. agent.lameduck("terminating healthchecks") // Note we only do this now if we entered lameduck. In the // master case for instance, we want to keep serving until // vttablet dies entirely (where else is the client going to // go?). After servenv lameduck, the queryservice is stopped // from a servenv.OnClose() hook anyway. log.Infof("Disabling query service after lameduck in terminating healthchecks") agent.QueryServiceControl.SetServingType(tablet.Type, false, nil) }
go
func (agent *ActionAgent) terminateHealthChecks() { // No need to check for error, only a canceled batchCtx would fail this. agent.lock(agent.batchCtx) defer agent.unlock() log.Info("agent.terminateHealthChecks is starting") // read the current tablet record tablet := agent.Tablet() if !topo.IsSubjectToLameduck(tablet.Type) { // If we're MASTER, SPARE, WORKER, etc. then we // shouldn't enter lameduck. We do lameduck to not // trigger errors on clients. log.Infof("Tablet in state %v, not entering lameduck", tablet.Type) return } // Go lameduck for gracePeriod. // We've already checked above that we're not MASTER. // Enter new lameduck mode for gracePeriod, then shut down // queryservice. New lameduck mode means keep accepting // queries, but advertise unhealthy. After we return from // this synchronous OnTermSync hook, servenv may decide to // wait even longer, for the rest of the time specified by its // own "-lameduck-period" flag. During that extra period, // queryservice will be in old lameduck mode, meaning stay // alive but reject new queries. agent.lameduck("terminating healthchecks") // Note we only do this now if we entered lameduck. In the // master case for instance, we want to keep serving until // vttablet dies entirely (where else is the client going to // go?). After servenv lameduck, the queryservice is stopped // from a servenv.OnClose() hook anyway. log.Infof("Disabling query service after lameduck in terminating healthchecks") agent.QueryServiceControl.SetServingType(tablet.Type, false, nil) }
[ "func", "(", "agent", "*", "ActionAgent", ")", "terminateHealthChecks", "(", ")", "{", "// No need to check for error, only a canceled batchCtx would fail this.", "agent", ".", "lock", "(", "agent", ".", "batchCtx", ")", "\n", "defer", "agent", ".", "unlock", "(", ")", "\n", "log", ".", "Info", "(", "\"", "\"", ")", "\n\n", "// read the current tablet record", "tablet", ":=", "agent", ".", "Tablet", "(", ")", "\n", "if", "!", "topo", ".", "IsSubjectToLameduck", "(", "tablet", ".", "Type", ")", "{", "// If we're MASTER, SPARE, WORKER, etc. then we", "// shouldn't enter lameduck. We do lameduck to not", "// trigger errors on clients.", "log", ".", "Infof", "(", "\"", "\"", ",", "tablet", ".", "Type", ")", "\n", "return", "\n", "}", "\n\n", "// Go lameduck for gracePeriod.", "// We've already checked above that we're not MASTER.", "// Enter new lameduck mode for gracePeriod, then shut down", "// queryservice. New lameduck mode means keep accepting", "// queries, but advertise unhealthy. After we return from", "// this synchronous OnTermSync hook, servenv may decide to", "// wait even longer, for the rest of the time specified by its", "// own \"-lameduck-period\" flag. During that extra period,", "// queryservice will be in old lameduck mode, meaning stay", "// alive but reject new queries.", "agent", ".", "lameduck", "(", "\"", "\"", ")", "\n\n", "// Note we only do this now if we entered lameduck. In the", "// master case for instance, we want to keep serving until", "// vttablet dies entirely (where else is the client going to", "// go?). After servenv lameduck, the queryservice is stopped", "// from a servenv.OnClose() hook anyway.", "log", ".", "Infof", "(", "\"", "\"", ")", "\n", "agent", ".", "QueryServiceControl", ".", "SetServingType", "(", "tablet", ".", "Type", ",", "false", ",", "nil", ")", "\n", "}" ]
// terminateHealthChecks is called when we enter lame duck mode. // We will clean up our state, and set query service to lame duck mode. // We only do something if we are in a serving state, and not a master.
[ "terminateHealthChecks", "is", "called", "when", "we", "enter", "lame", "duck", "mode", ".", "We", "will", "clean", "up", "our", "state", "and", "set", "query", "service", "to", "lame", "duck", "mode", ".", "We", "only", "do", "something", "if", "we", "are", "in", "a", "serving", "state", "and", "not", "a", "master", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/healthcheck.go#L324-L360
train
vitessio/vitess
go/vt/vtgate/vtgateconn/vtgateconn.go
Session
func (conn *VTGateConn) Session(targetString string, options *querypb.ExecuteOptions) *VTGateSession { return &VTGateSession{ session: &vtgatepb.Session{ TargetString: targetString, Options: options, Autocommit: true, }, impl: conn.impl, } }
go
func (conn *VTGateConn) Session(targetString string, options *querypb.ExecuteOptions) *VTGateSession { return &VTGateSession{ session: &vtgatepb.Session{ TargetString: targetString, Options: options, Autocommit: true, }, impl: conn.impl, } }
[ "func", "(", "conn", "*", "VTGateConn", ")", "Session", "(", "targetString", "string", ",", "options", "*", "querypb", ".", "ExecuteOptions", ")", "*", "VTGateSession", "{", "return", "&", "VTGateSession", "{", "session", ":", "&", "vtgatepb", ".", "Session", "{", "TargetString", ":", "targetString", ",", "Options", ":", "options", ",", "Autocommit", ":", "true", ",", "}", ",", "impl", ":", "conn", ".", "impl", ",", "}", "\n", "}" ]
// Session returns a VTGateSession that can be used to access V3 functions.
[ "Session", "returns", "a", "VTGateSession", "that", "can", "be", "used", "to", "access", "V3", "functions", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgateconn/vtgateconn.go#L47-L56
train
vitessio/vitess
go/vt/vtgate/vtgateconn/vtgateconn.go
ExecuteShards
func (conn *VTGateConn) ExecuteShards(ctx context.Context, query string, keyspace string, shards []string, bindVars map[string]*querypb.BindVariable, tabletType topodatapb.TabletType, options *querypb.ExecuteOptions) (*sqltypes.Result, error) { _, res, err := conn.impl.ExecuteShards(ctx, query, keyspace, shards, bindVars, tabletType, nil, options) return res, err }
go
func (conn *VTGateConn) ExecuteShards(ctx context.Context, query string, keyspace string, shards []string, bindVars map[string]*querypb.BindVariable, tabletType topodatapb.TabletType, options *querypb.ExecuteOptions) (*sqltypes.Result, error) { _, res, err := conn.impl.ExecuteShards(ctx, query, keyspace, shards, bindVars, tabletType, nil, options) return res, err }
[ "func", "(", "conn", "*", "VTGateConn", ")", "ExecuteShards", "(", "ctx", "context", ".", "Context", ",", "query", "string", ",", "keyspace", "string", ",", "shards", "[", "]", "string", ",", "bindVars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "tabletType", "topodatapb", ".", "TabletType", ",", "options", "*", "querypb", ".", "ExecuteOptions", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "_", ",", "res", ",", "err", ":=", "conn", ".", "impl", ".", "ExecuteShards", "(", "ctx", ",", "query", ",", "keyspace", ",", "shards", ",", "bindVars", ",", "tabletType", ",", "nil", ",", "options", ")", "\n", "return", "res", ",", "err", "\n", "}" ]
// ExecuteShards executes a non-streaming query for multiple shards on vtgate.
[ "ExecuteShards", "executes", "a", "non", "-", "streaming", "query", "for", "multiple", "shards", "on", "vtgate", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgateconn/vtgateconn.go#L59-L62
train
vitessio/vitess
go/vt/vtgate/vtgateconn/vtgateconn.go
StreamExecuteShards
func (conn *VTGateConn) StreamExecuteShards(ctx context.Context, query string, keyspace string, shards []string, bindVars map[string]*querypb.BindVariable, tabletType topodatapb.TabletType, options *querypb.ExecuteOptions) (sqltypes.ResultStream, error) { return conn.impl.StreamExecuteShards(ctx, query, keyspace, shards, bindVars, tabletType, options) }
go
func (conn *VTGateConn) StreamExecuteShards(ctx context.Context, query string, keyspace string, shards []string, bindVars map[string]*querypb.BindVariable, tabletType topodatapb.TabletType, options *querypb.ExecuteOptions) (sqltypes.ResultStream, error) { return conn.impl.StreamExecuteShards(ctx, query, keyspace, shards, bindVars, tabletType, options) }
[ "func", "(", "conn", "*", "VTGateConn", ")", "StreamExecuteShards", "(", "ctx", "context", ".", "Context", ",", "query", "string", ",", "keyspace", "string", ",", "shards", "[", "]", "string", ",", "bindVars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "tabletType", "topodatapb", ".", "TabletType", ",", "options", "*", "querypb", ".", "ExecuteOptions", ")", "(", "sqltypes", ".", "ResultStream", ",", "error", ")", "{", "return", "conn", ".", "impl", ".", "StreamExecuteShards", "(", "ctx", ",", "query", ",", "keyspace", ",", "shards", ",", "bindVars", ",", "tabletType", ",", "options", ")", "\n", "}" ]
// StreamExecuteShards executes a streaming query on vtgate, on a set // of shards. It returns a ResultStream and an error. First check the // error. Then you can pull values from the ResultStream until io.EOF, // or another error.
[ "StreamExecuteShards", "executes", "a", "streaming", "query", "on", "vtgate", "on", "a", "set", "of", "shards", ".", "It", "returns", "a", "ResultStream", "and", "an", "error", ".", "First", "check", "the", "error", ".", "Then", "you", "can", "pull", "values", "from", "the", "ResultStream", "until", "io", ".", "EOF", "or", "another", "error", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgateconn/vtgateconn.go#L102-L104
train
vitessio/vitess
go/vt/vtgate/vtgateconn/vtgateconn.go
ResolveTransaction
func (conn *VTGateConn) ResolveTransaction(ctx context.Context, dtid string) error { return conn.impl.ResolveTransaction(ctx, dtid) }
go
func (conn *VTGateConn) ResolveTransaction(ctx context.Context, dtid string) error { return conn.impl.ResolveTransaction(ctx, dtid) }
[ "func", "(", "conn", "*", "VTGateConn", ")", "ResolveTransaction", "(", "ctx", "context", ".", "Context", ",", "dtid", "string", ")", "error", "{", "return", "conn", ".", "impl", ".", "ResolveTransaction", "(", "ctx", ",", "dtid", ")", "\n", "}" ]
// ResolveTransaction resolves the 2pc transaction.
[ "ResolveTransaction", "resolves", "the", "2pc", "transaction", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgateconn/vtgateconn.go#L123-L125
train
vitessio/vitess
go/vt/vtgate/vtgateconn/vtgateconn.go
Begin
func (conn *VTGateConn) Begin(ctx context.Context) (*VTGateTx, error) { session, err := conn.impl.Begin(ctx, false /* singledb */) if err != nil { return nil, err } return &VTGateTx{ conn: conn, session: session, }, nil }
go
func (conn *VTGateConn) Begin(ctx context.Context) (*VTGateTx, error) { session, err := conn.impl.Begin(ctx, false /* singledb */) if err != nil { return nil, err } return &VTGateTx{ conn: conn, session: session, }, nil }
[ "func", "(", "conn", "*", "VTGateConn", ")", "Begin", "(", "ctx", "context", ".", "Context", ")", "(", "*", "VTGateTx", ",", "error", ")", "{", "session", ",", "err", ":=", "conn", ".", "impl", ".", "Begin", "(", "ctx", ",", "false", "/* singledb */", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "VTGateTx", "{", "conn", ":", "conn", ",", "session", ":", "session", ",", "}", ",", "nil", "\n", "}" ]
// Begin starts a transaction and returns a VTGateTX.
[ "Begin", "starts", "a", "transaction", "and", "returns", "a", "VTGateTX", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgateconn/vtgateconn.go#L144-L154
train
vitessio/vitess
go/vt/vtgate/vtgateconn/vtgateconn.go
GetSrvKeyspace
func (conn *VTGateConn) GetSrvKeyspace(ctx context.Context, keyspace string) (*topodatapb.SrvKeyspace, error) { return conn.impl.GetSrvKeyspace(ctx, keyspace) }
go
func (conn *VTGateConn) GetSrvKeyspace(ctx context.Context, keyspace string) (*topodatapb.SrvKeyspace, error) { return conn.impl.GetSrvKeyspace(ctx, keyspace) }
[ "func", "(", "conn", "*", "VTGateConn", ")", "GetSrvKeyspace", "(", "ctx", "context", ".", "Context", ",", "keyspace", "string", ")", "(", "*", "topodatapb", ".", "SrvKeyspace", ",", "error", ")", "{", "return", "conn", ".", "impl", ".", "GetSrvKeyspace", "(", "ctx", ",", "keyspace", ")", "\n", "}" ]
// GetSrvKeyspace returns a topo.SrvKeyspace object.
[ "GetSrvKeyspace", "returns", "a", "topo", ".", "SrvKeyspace", "object", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgateconn/vtgateconn.go#L170-L172
train
vitessio/vitess
go/vt/vtgate/vtgateconn/vtgateconn.go
UpdateStream
func (conn *VTGateConn) UpdateStream(ctx context.Context, keyspace, shard string, keyRange *topodatapb.KeyRange, tabletType topodatapb.TabletType, timestamp int64, event *querypb.EventToken) (UpdateStreamReader, error) { return conn.impl.UpdateStream(ctx, keyspace, shard, keyRange, tabletType, timestamp, event) }
go
func (conn *VTGateConn) UpdateStream(ctx context.Context, keyspace, shard string, keyRange *topodatapb.KeyRange, tabletType topodatapb.TabletType, timestamp int64, event *querypb.EventToken) (UpdateStreamReader, error) { return conn.impl.UpdateStream(ctx, keyspace, shard, keyRange, tabletType, timestamp, event) }
[ "func", "(", "conn", "*", "VTGateConn", ")", "UpdateStream", "(", "ctx", "context", ".", "Context", ",", "keyspace", ",", "shard", "string", ",", "keyRange", "*", "topodatapb", ".", "KeyRange", ",", "tabletType", "topodatapb", ".", "TabletType", ",", "timestamp", "int64", ",", "event", "*", "querypb", ".", "EventToken", ")", "(", "UpdateStreamReader", ",", "error", ")", "{", "return", "conn", ".", "impl", ".", "UpdateStream", "(", "ctx", ",", "keyspace", ",", "shard", ",", "keyRange", ",", "tabletType", ",", "timestamp", ",", "event", ")", "\n", "}" ]
// UpdateStream executes a streaming query on vtgate. It returns an // UpdateStreamReader and an error. First check the error. Then you // can pull values from the UpdateStreamReader until io.EOF, or // another error.
[ "UpdateStream", "executes", "a", "streaming", "query", "on", "vtgate", ".", "It", "returns", "an", "UpdateStreamReader", "and", "an", "error", ".", "First", "check", "the", "error", ".", "Then", "you", "can", "pull", "values", "from", "the", "UpdateStreamReader", "until", "io", ".", "EOF", "or", "another", "error", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgateconn/vtgateconn.go#L185-L187
train
vitessio/vitess
go/vt/vtgate/vtgateconn/vtgateconn.go
Execute
func (sn *VTGateSession) Execute(ctx context.Context, query string, bindVars map[string]*querypb.BindVariable) (*sqltypes.Result, error) { session, res, err := sn.impl.Execute(ctx, sn.session, query, bindVars) sn.session = session return res, err }
go
func (sn *VTGateSession) Execute(ctx context.Context, query string, bindVars map[string]*querypb.BindVariable) (*sqltypes.Result, error) { session, res, err := sn.impl.Execute(ctx, sn.session, query, bindVars) sn.session = session return res, err }
[ "func", "(", "sn", "*", "VTGateSession", ")", "Execute", "(", "ctx", "context", ".", "Context", ",", "query", "string", ",", "bindVars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "session", ",", "res", ",", "err", ":=", "sn", ".", "impl", ".", "Execute", "(", "ctx", ",", "sn", ".", "session", ",", "query", ",", "bindVars", ")", "\n", "sn", ".", "session", "=", "session", "\n", "return", "res", ",", "err", "\n", "}" ]
// Execute performs a VTGate Execute.
[ "Execute", "performs", "a", "VTGate", "Execute", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgateconn/vtgateconn.go#L201-L205
train
vitessio/vitess
go/vt/vtgate/vtgateconn/vtgateconn.go
ExecuteBatch
func (sn *VTGateSession) ExecuteBatch(ctx context.Context, query []string, bindVars []map[string]*querypb.BindVariable) ([]sqltypes.QueryResponse, error) { session, res, errs := sn.impl.ExecuteBatch(ctx, sn.session, query, bindVars) sn.session = session return res, errs }
go
func (sn *VTGateSession) ExecuteBatch(ctx context.Context, query []string, bindVars []map[string]*querypb.BindVariable) ([]sqltypes.QueryResponse, error) { session, res, errs := sn.impl.ExecuteBatch(ctx, sn.session, query, bindVars) sn.session = session return res, errs }
[ "func", "(", "sn", "*", "VTGateSession", ")", "ExecuteBatch", "(", "ctx", "context", ".", "Context", ",", "query", "[", "]", "string", ",", "bindVars", "[", "]", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "(", "[", "]", "sqltypes", ".", "QueryResponse", ",", "error", ")", "{", "session", ",", "res", ",", "errs", ":=", "sn", ".", "impl", ".", "ExecuteBatch", "(", "ctx", ",", "sn", ".", "session", ",", "query", ",", "bindVars", ")", "\n", "sn", ".", "session", "=", "session", "\n", "return", "res", ",", "errs", "\n", "}" ]
// ExecuteBatch executes a list of queries on vtgate within the current transaction.
[ "ExecuteBatch", "executes", "a", "list", "of", "queries", "on", "vtgate", "within", "the", "current", "transaction", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgateconn/vtgateconn.go#L208-L212
train
vitessio/vitess
go/vt/vtgate/vtgateconn/vtgateconn.go
StreamExecute
func (sn *VTGateSession) StreamExecute(ctx context.Context, query string, bindVars map[string]*querypb.BindVariable) (sqltypes.ResultStream, error) { // StreamExecute is only used for SELECT queries that don't change // the session. So, the protocol doesn't return an updated session. // This may change in the future. return sn.impl.StreamExecute(ctx, sn.session, query, bindVars) }
go
func (sn *VTGateSession) StreamExecute(ctx context.Context, query string, bindVars map[string]*querypb.BindVariable) (sqltypes.ResultStream, error) { // StreamExecute is only used for SELECT queries that don't change // the session. So, the protocol doesn't return an updated session. // This may change in the future. return sn.impl.StreamExecute(ctx, sn.session, query, bindVars) }
[ "func", "(", "sn", "*", "VTGateSession", ")", "StreamExecute", "(", "ctx", "context", ".", "Context", ",", "query", "string", ",", "bindVars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "(", "sqltypes", ".", "ResultStream", ",", "error", ")", "{", "// StreamExecute is only used for SELECT queries that don't change", "// the session. So, the protocol doesn't return an updated session.", "// This may change in the future.", "return", "sn", ".", "impl", ".", "StreamExecute", "(", "ctx", ",", "sn", ".", "session", ",", "query", ",", "bindVars", ")", "\n", "}" ]
// StreamExecute executes a streaming query on vtgate. // It returns a ResultStream and an error. First check the // error. Then you can pull values from the ResultStream until io.EOF, // or another error.
[ "StreamExecute", "executes", "a", "streaming", "query", "on", "vtgate", ".", "It", "returns", "a", "ResultStream", "and", "an", "error", ".", "First", "check", "the", "error", ".", "Then", "you", "can", "pull", "values", "from", "the", "ResultStream", "until", "io", ".", "EOF", "or", "another", "error", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgateconn/vtgateconn.go#L218-L223
train
vitessio/vitess
go/vt/vtgate/vtgateconn/vtgateconn.go
ExecuteKeyspaceIds
func (tx *VTGateTx) ExecuteKeyspaceIds(ctx context.Context, query string, keyspace string, keyspaceIds [][]byte, bindVars map[string]*querypb.BindVariable, tabletType topodatapb.TabletType, options *querypb.ExecuteOptions) (*sqltypes.Result, error) { if tx.session == nil { return nil, fmt.Errorf("executeKeyspaceIds: not in transaction") } session, res, err := tx.conn.impl.ExecuteKeyspaceIds(ctx, query, keyspace, keyspaceIds, bindVars, tabletType, tx.session, options) tx.session = session return res, err }
go
func (tx *VTGateTx) ExecuteKeyspaceIds(ctx context.Context, query string, keyspace string, keyspaceIds [][]byte, bindVars map[string]*querypb.BindVariable, tabletType topodatapb.TabletType, options *querypb.ExecuteOptions) (*sqltypes.Result, error) { if tx.session == nil { return nil, fmt.Errorf("executeKeyspaceIds: not in transaction") } session, res, err := tx.conn.impl.ExecuteKeyspaceIds(ctx, query, keyspace, keyspaceIds, bindVars, tabletType, tx.session, options) tx.session = session return res, err }
[ "func", "(", "tx", "*", "VTGateTx", ")", "ExecuteKeyspaceIds", "(", "ctx", "context", ".", "Context", ",", "query", "string", ",", "keyspace", "string", ",", "keyspaceIds", "[", "]", "[", "]", "byte", ",", "bindVars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "tabletType", "topodatapb", ".", "TabletType", ",", "options", "*", "querypb", ".", "ExecuteOptions", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "if", "tx", ".", "session", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "session", ",", "res", ",", "err", ":=", "tx", ".", "conn", ".", "impl", ".", "ExecuteKeyspaceIds", "(", "ctx", ",", "query", ",", "keyspace", ",", "keyspaceIds", ",", "bindVars", ",", "tabletType", ",", "tx", ".", "session", ",", "options", ")", "\n", "tx", ".", "session", "=", "session", "\n", "return", "res", ",", "err", "\n", "}" ]
// ExecuteKeyspaceIds executes a non-streaming query for multiple keyspace_ids.
[ "ExecuteKeyspaceIds", "executes", "a", "non", "-", "streaming", "query", "for", "multiple", "keyspace_ids", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgateconn/vtgateconn.go#L243-L250
train
vitessio/vitess
go/vt/vtgate/vtgateconn/vtgateconn.go
ExecuteBatchShards
func (tx *VTGateTx) ExecuteBatchShards(ctx context.Context, queries []*vtgatepb.BoundShardQuery, tabletType topodatapb.TabletType, options *querypb.ExecuteOptions) ([]sqltypes.Result, error) { if tx.session == nil { return nil, fmt.Errorf("executeBatchShards: not in transaction") } session, res, err := tx.conn.impl.ExecuteBatchShards(ctx, queries, tabletType, false /* asTransaction */, tx.session, options) tx.session = session return res, err }
go
func (tx *VTGateTx) ExecuteBatchShards(ctx context.Context, queries []*vtgatepb.BoundShardQuery, tabletType topodatapb.TabletType, options *querypb.ExecuteOptions) ([]sqltypes.Result, error) { if tx.session == nil { return nil, fmt.Errorf("executeBatchShards: not in transaction") } session, res, err := tx.conn.impl.ExecuteBatchShards(ctx, queries, tabletType, false /* asTransaction */, tx.session, options) tx.session = session return res, err }
[ "func", "(", "tx", "*", "VTGateTx", ")", "ExecuteBatchShards", "(", "ctx", "context", ".", "Context", ",", "queries", "[", "]", "*", "vtgatepb", ".", "BoundShardQuery", ",", "tabletType", "topodatapb", ".", "TabletType", ",", "options", "*", "querypb", ".", "ExecuteOptions", ")", "(", "[", "]", "sqltypes", ".", "Result", ",", "error", ")", "{", "if", "tx", ".", "session", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "session", ",", "res", ",", "err", ":=", "tx", ".", "conn", ".", "impl", ".", "ExecuteBatchShards", "(", "ctx", ",", "queries", ",", "tabletType", ",", "false", "/* asTransaction */", ",", "tx", ".", "session", ",", "options", ")", "\n", "tx", ".", "session", "=", "session", "\n", "return", "res", ",", "err", "\n", "}" ]
// ExecuteBatchShards executes a set of non-streaming queries for multiple shards.
[ "ExecuteBatchShards", "executes", "a", "set", "of", "non", "-", "streaming", "queries", "for", "multiple", "shards", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgateconn/vtgateconn.go#L273-L280
train
vitessio/vitess
go/vt/vtgate/vtgateconn/vtgateconn.go
RegisterDialer
func RegisterDialer(name string, dialer DialerFunc) { if _, ok := dialers[name]; ok { log.Warningf("Dialer %s already exists, overwriting it", name) } dialers[name] = dialer }
go
func RegisterDialer(name string, dialer DialerFunc) { if _, ok := dialers[name]; ok { log.Warningf("Dialer %s already exists, overwriting it", name) } dialers[name] = dialer }
[ "func", "RegisterDialer", "(", "name", "string", ",", "dialer", "DialerFunc", ")", "{", "if", "_", ",", "ok", ":=", "dialers", "[", "name", "]", ";", "ok", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "dialers", "[", "name", "]", "=", "dialer", "\n", "}" ]
// RegisterDialer is meant to be used by Dialer implementations // to self register.
[ "RegisterDialer", "is", "meant", "to", "be", "used", "by", "Dialer", "implementations", "to", "self", "register", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vtgateconn/vtgateconn.go#L393-L398
train
vitessio/vitess
go/vt/throttler/max_replication_lag_module_config.go
NewMaxReplicationLagModuleConfig
func NewMaxReplicationLagModuleConfig(maxReplicationLag int64) MaxReplicationLagModuleConfig { config := defaultMaxReplicationLagModuleConfig config.MaxReplicationLagSec = maxReplicationLag return config }
go
func NewMaxReplicationLagModuleConfig(maxReplicationLag int64) MaxReplicationLagModuleConfig { config := defaultMaxReplicationLagModuleConfig config.MaxReplicationLagSec = maxReplicationLag return config }
[ "func", "NewMaxReplicationLagModuleConfig", "(", "maxReplicationLag", "int64", ")", "MaxReplicationLagModuleConfig", "{", "config", ":=", "defaultMaxReplicationLagModuleConfig", "\n", "config", ".", "MaxReplicationLagSec", "=", "maxReplicationLag", "\n", "return", "config", "\n", "}" ]
// NewMaxReplicationLagModuleConfig returns a default configuration where // only "maxReplicationLag" is set.
[ "NewMaxReplicationLagModuleConfig", "returns", "a", "default", "configuration", "where", "only", "maxReplicationLag", "is", "set", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/max_replication_lag_module_config.go#L70-L74
train
vitessio/vitess
go/vt/throttler/max_replication_lag_module_config.go
MinDurationBetweenIncreases
func (c MaxReplicationLagModuleConfig) MinDurationBetweenIncreases() time.Duration { return time.Duration(c.MinDurationBetweenIncreasesSec) * time.Second }
go
func (c MaxReplicationLagModuleConfig) MinDurationBetweenIncreases() time.Duration { return time.Duration(c.MinDurationBetweenIncreasesSec) * time.Second }
[ "func", "(", "c", "MaxReplicationLagModuleConfig", ")", "MinDurationBetweenIncreases", "(", ")", "time", ".", "Duration", "{", "return", "time", ".", "Duration", "(", "c", ".", "MinDurationBetweenIncreasesSec", ")", "*", "time", ".", "Second", "\n", "}" ]
// MinDurationBetweenIncreases is a helper function which returns the respective // protobuf field as native Go type.
[ "MinDurationBetweenIncreases", "is", "a", "helper", "function", "which", "returns", "the", "respective", "protobuf", "field", "as", "native", "Go", "type", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/max_replication_lag_module_config.go#L132-L134
train
vitessio/vitess
go/vt/throttler/max_replication_lag_module_config.go
MaxDurationBetweenIncreases
func (c MaxReplicationLagModuleConfig) MaxDurationBetweenIncreases() time.Duration { return time.Duration(c.MaxDurationBetweenIncreasesSec) * time.Second }
go
func (c MaxReplicationLagModuleConfig) MaxDurationBetweenIncreases() time.Duration { return time.Duration(c.MaxDurationBetweenIncreasesSec) * time.Second }
[ "func", "(", "c", "MaxReplicationLagModuleConfig", ")", "MaxDurationBetweenIncreases", "(", ")", "time", ".", "Duration", "{", "return", "time", ".", "Duration", "(", "c", ".", "MaxDurationBetweenIncreasesSec", ")", "*", "time", ".", "Second", "\n", "}" ]
// MaxDurationBetweenIncreases is a helper function which returns the respective // protobuf field as native Go type.
[ "MaxDurationBetweenIncreases", "is", "a", "helper", "function", "which", "returns", "the", "respective", "protobuf", "field", "as", "native", "Go", "type", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/max_replication_lag_module_config.go#L138-L140
train
vitessio/vitess
go/vt/throttler/max_replication_lag_module_config.go
MinDurationBetweenDecreases
func (c MaxReplicationLagModuleConfig) MinDurationBetweenDecreases() time.Duration { return time.Duration(c.MinDurationBetweenDecreasesSec) * time.Second }
go
func (c MaxReplicationLagModuleConfig) MinDurationBetweenDecreases() time.Duration { return time.Duration(c.MinDurationBetweenDecreasesSec) * time.Second }
[ "func", "(", "c", "MaxReplicationLagModuleConfig", ")", "MinDurationBetweenDecreases", "(", ")", "time", ".", "Duration", "{", "return", "time", ".", "Duration", "(", "c", ".", "MinDurationBetweenDecreasesSec", ")", "*", "time", ".", "Second", "\n", "}" ]
// MinDurationBetweenDecreases is a helper function which returns the respective // protobuf field as native Go type.
[ "MinDurationBetweenDecreases", "is", "a", "helper", "function", "which", "returns", "the", "respective", "protobuf", "field", "as", "native", "Go", "type", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/max_replication_lag_module_config.go#L144-L146
train
vitessio/vitess
go/vt/throttler/max_replication_lag_module_config.go
SpreadBacklogAcross
func (c MaxReplicationLagModuleConfig) SpreadBacklogAcross() time.Duration { return time.Duration(c.SpreadBacklogAcrossSec) * time.Second }
go
func (c MaxReplicationLagModuleConfig) SpreadBacklogAcross() time.Duration { return time.Duration(c.SpreadBacklogAcrossSec) * time.Second }
[ "func", "(", "c", "MaxReplicationLagModuleConfig", ")", "SpreadBacklogAcross", "(", ")", "time", ".", "Duration", "{", "return", "time", ".", "Duration", "(", "c", ".", "SpreadBacklogAcrossSec", ")", "*", "time", ".", "Second", "\n", "}" ]
// SpreadBacklogAcross is a helper function which returns the respective // protobuf field as native Go type.
[ "SpreadBacklogAcross", "is", "a", "helper", "function", "which", "returns", "the", "respective", "protobuf", "field", "as", "native", "Go", "type", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/max_replication_lag_module_config.go#L150-L152
train
vitessio/vitess
go/vt/throttler/max_replication_lag_module_config.go
AgeBadRateAfter
func (c MaxReplicationLagModuleConfig) AgeBadRateAfter() time.Duration { return time.Duration(c.AgeBadRateAfterSec) * time.Second }
go
func (c MaxReplicationLagModuleConfig) AgeBadRateAfter() time.Duration { return time.Duration(c.AgeBadRateAfterSec) * time.Second }
[ "func", "(", "c", "MaxReplicationLagModuleConfig", ")", "AgeBadRateAfter", "(", ")", "time", ".", "Duration", "{", "return", "time", ".", "Duration", "(", "c", ".", "AgeBadRateAfterSec", ")", "*", "time", ".", "Second", "\n", "}" ]
// AgeBadRateAfter is a helper function which returns the respective // protobuf field as native Go type.
[ "AgeBadRateAfter", "is", "a", "helper", "function", "which", "returns", "the", "respective", "protobuf", "field", "as", "native", "Go", "type", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/max_replication_lag_module_config.go#L156-L158
train
vitessio/vitess
go/vt/worker/multi_split_diff.go
NewMultiSplitDiffWorker
func NewMultiSplitDiffWorker(wr *wrangler.Wrangler, cell, keyspace, shard string, excludeTables []string, minHealthyTablets, parallelDiffsCount int, waitForFixedTimeRatherThanGtidSet bool, useConsistentSnapshot bool, tabletType topodatapb.TabletType) Worker { return &MultiSplitDiffWorker{ StatusWorker: NewStatusWorker(), wr: wr, cell: cell, keyspace: keyspace, shard: shard, excludeTables: excludeTables, minHealthyTablets: minHealthyTablets, parallelDiffsCount: parallelDiffsCount, cleaner: &wrangler.Cleaner{}, useConsistentSnapshot: useConsistentSnapshot, waitForFixedTimeRatherThanGtidSet: waitForFixedTimeRatherThanGtidSet, tabletType: tabletType, } }
go
func NewMultiSplitDiffWorker(wr *wrangler.Wrangler, cell, keyspace, shard string, excludeTables []string, minHealthyTablets, parallelDiffsCount int, waitForFixedTimeRatherThanGtidSet bool, useConsistentSnapshot bool, tabletType topodatapb.TabletType) Worker { return &MultiSplitDiffWorker{ StatusWorker: NewStatusWorker(), wr: wr, cell: cell, keyspace: keyspace, shard: shard, excludeTables: excludeTables, minHealthyTablets: minHealthyTablets, parallelDiffsCount: parallelDiffsCount, cleaner: &wrangler.Cleaner{}, useConsistentSnapshot: useConsistentSnapshot, waitForFixedTimeRatherThanGtidSet: waitForFixedTimeRatherThanGtidSet, tabletType: tabletType, } }
[ "func", "NewMultiSplitDiffWorker", "(", "wr", "*", "wrangler", ".", "Wrangler", ",", "cell", ",", "keyspace", ",", "shard", "string", ",", "excludeTables", "[", "]", "string", ",", "minHealthyTablets", ",", "parallelDiffsCount", "int", ",", "waitForFixedTimeRatherThanGtidSet", "bool", ",", "useConsistentSnapshot", "bool", ",", "tabletType", "topodatapb", ".", "TabletType", ")", "Worker", "{", "return", "&", "MultiSplitDiffWorker", "{", "StatusWorker", ":", "NewStatusWorker", "(", ")", ",", "wr", ":", "wr", ",", "cell", ":", "cell", ",", "keyspace", ":", "keyspace", ",", "shard", ":", "shard", ",", "excludeTables", ":", "excludeTables", ",", "minHealthyTablets", ":", "minHealthyTablets", ",", "parallelDiffsCount", ":", "parallelDiffsCount", ",", "cleaner", ":", "&", "wrangler", ".", "Cleaner", "{", "}", ",", "useConsistentSnapshot", ":", "useConsistentSnapshot", ",", "waitForFixedTimeRatherThanGtidSet", ":", "waitForFixedTimeRatherThanGtidSet", ",", "tabletType", ":", "tabletType", ",", "}", "\n", "}" ]
// NewMultiSplitDiffWorker returns a new MultiSplitDiffWorker object.
[ "NewMultiSplitDiffWorker", "returns", "a", "new", "MultiSplitDiffWorker", "object", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/multi_split_diff.go#L83-L98
train
vitessio/vitess
go/vt/worker/multi_split_diff.go
findDestinationShards
func (msdw *MultiSplitDiffWorker) findDestinationShards(ctx context.Context) ([]*topo.ShardInfo, error) { shortCtx, cancel := context.WithTimeout(ctx, *remoteActionsTimeout) keyspaces, err := msdw.wr.TopoServer().GetKeyspaces(shortCtx) cancel() if err != nil { return nil, vterrors.Wrap(err, "failed to get list of keyspaces") } var resultArray []*topo.ShardInfo for _, keyspace := range keyspaces { shardInfo, err := msdw.findShardsInKeyspace(ctx, keyspace) if err != nil { return nil, err } resultArray = append(resultArray, shardInfo...) } if len(resultArray) == 0 { return nil, vterrors.Errorf(vtrpc.Code_UNAVAILABLE, "there are no destination shards") } return resultArray, nil }
go
func (msdw *MultiSplitDiffWorker) findDestinationShards(ctx context.Context) ([]*topo.ShardInfo, error) { shortCtx, cancel := context.WithTimeout(ctx, *remoteActionsTimeout) keyspaces, err := msdw.wr.TopoServer().GetKeyspaces(shortCtx) cancel() if err != nil { return nil, vterrors.Wrap(err, "failed to get list of keyspaces") } var resultArray []*topo.ShardInfo for _, keyspace := range keyspaces { shardInfo, err := msdw.findShardsInKeyspace(ctx, keyspace) if err != nil { return nil, err } resultArray = append(resultArray, shardInfo...) } if len(resultArray) == 0 { return nil, vterrors.Errorf(vtrpc.Code_UNAVAILABLE, "there are no destination shards") } return resultArray, nil }
[ "func", "(", "msdw", "*", "MultiSplitDiffWorker", ")", "findDestinationShards", "(", "ctx", "context", ".", "Context", ")", "(", "[", "]", "*", "topo", ".", "ShardInfo", ",", "error", ")", "{", "shortCtx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "ctx", ",", "*", "remoteActionsTimeout", ")", "\n", "keyspaces", ",", "err", ":=", "msdw", ".", "wr", ".", "TopoServer", "(", ")", ".", "GetKeyspaces", "(", "shortCtx", ")", "\n", "cancel", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "vterrors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "var", "resultArray", "[", "]", "*", "topo", ".", "ShardInfo", "\n\n", "for", "_", ",", "keyspace", ":=", "range", "keyspaces", "{", "shardInfo", ",", "err", ":=", "msdw", ".", "findShardsInKeyspace", "(", "ctx", ",", "keyspace", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "resultArray", "=", "append", "(", "resultArray", ",", "shardInfo", "...", ")", "\n", "}", "\n\n", "if", "len", "(", "resultArray", ")", "==", "0", "{", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpc", ".", "Code_UNAVAILABLE", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "resultArray", ",", "nil", "\n", "}" ]
// findDestinationShards finds all the shards that have filtered replication from the source shard
[ "findDestinationShards", "finds", "all", "the", "shards", "that", "have", "filtered", "replication", "from", "the", "source", "shard" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/multi_split_diff.go#L230-L252
train
vitessio/vitess
go/vt/worker/multi_split_diff.go
stopVreplicationAt
func (msdw *MultiSplitDiffWorker) stopVreplicationAt(ctx context.Context, shardInfo *topo.ShardInfo, sourcePosition string, masterInfo *topo.TabletInfo) (string, error) { msdw.wr.Logger().Infof("Restarting master %v until it catches up to %v", shardInfo.MasterAlias, sourcePosition) shortCtx, cancel := context.WithTimeout(ctx, *remoteActionsTimeout) _, err := msdw.wr.TabletManagerClient().VReplicationExec(shortCtx, masterInfo.Tablet, binlogplayer.StartVReplicationUntil(msdw.sourceUID, sourcePosition)) cancel() if err != nil { return "", vterrors.Wrapf(err, "VReplication(start until) for %v until %v failed", shardInfo.MasterAlias, sourcePosition) } shortCtx, cancel = context.WithTimeout(ctx, *remoteActionsTimeout) err = msdw.wr.TabletManagerClient().VReplicationWaitForPos(shortCtx, masterInfo.Tablet, int(msdw.sourceUID), sourcePosition) cancel() if err != nil { return "", vterrors.Wrapf(err, "VReplicationWaitForPos for %v until %v failed", shardInfo.MasterAlias, sourcePosition) } shortCtx, cancel = context.WithTimeout(ctx, *remoteActionsTimeout) masterPos, err := msdw.wr.TabletManagerClient().MasterPosition(shortCtx, masterInfo.Tablet) cancel() if err != nil { return "", vterrors.Wrapf(err, "MasterPosition for %v failed", msdw.shardInfo.MasterAlias) } return masterPos, nil }
go
func (msdw *MultiSplitDiffWorker) stopVreplicationAt(ctx context.Context, shardInfo *topo.ShardInfo, sourcePosition string, masterInfo *topo.TabletInfo) (string, error) { msdw.wr.Logger().Infof("Restarting master %v until it catches up to %v", shardInfo.MasterAlias, sourcePosition) shortCtx, cancel := context.WithTimeout(ctx, *remoteActionsTimeout) _, err := msdw.wr.TabletManagerClient().VReplicationExec(shortCtx, masterInfo.Tablet, binlogplayer.StartVReplicationUntil(msdw.sourceUID, sourcePosition)) cancel() if err != nil { return "", vterrors.Wrapf(err, "VReplication(start until) for %v until %v failed", shardInfo.MasterAlias, sourcePosition) } shortCtx, cancel = context.WithTimeout(ctx, *remoteActionsTimeout) err = msdw.wr.TabletManagerClient().VReplicationWaitForPos(shortCtx, masterInfo.Tablet, int(msdw.sourceUID), sourcePosition) cancel() if err != nil { return "", vterrors.Wrapf(err, "VReplicationWaitForPos for %v until %v failed", shardInfo.MasterAlias, sourcePosition) } shortCtx, cancel = context.WithTimeout(ctx, *remoteActionsTimeout) masterPos, err := msdw.wr.TabletManagerClient().MasterPosition(shortCtx, masterInfo.Tablet) cancel() if err != nil { return "", vterrors.Wrapf(err, "MasterPosition for %v failed", msdw.shardInfo.MasterAlias) } return masterPos, nil }
[ "func", "(", "msdw", "*", "MultiSplitDiffWorker", ")", "stopVreplicationAt", "(", "ctx", "context", ".", "Context", ",", "shardInfo", "*", "topo", ".", "ShardInfo", ",", "sourcePosition", "string", ",", "masterInfo", "*", "topo", ".", "TabletInfo", ")", "(", "string", ",", "error", ")", "{", "msdw", ".", "wr", ".", "Logger", "(", ")", ".", "Infof", "(", "\"", "\"", ",", "shardInfo", ".", "MasterAlias", ",", "sourcePosition", ")", "\n", "shortCtx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "ctx", ",", "*", "remoteActionsTimeout", ")", "\n", "_", ",", "err", ":=", "msdw", ".", "wr", ".", "TabletManagerClient", "(", ")", ".", "VReplicationExec", "(", "shortCtx", ",", "masterInfo", ".", "Tablet", ",", "binlogplayer", ".", "StartVReplicationUntil", "(", "msdw", ".", "sourceUID", ",", "sourcePosition", ")", ")", "\n", "cancel", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "shardInfo", ".", "MasterAlias", ",", "sourcePosition", ")", "\n", "}", "\n\n", "shortCtx", ",", "cancel", "=", "context", ".", "WithTimeout", "(", "ctx", ",", "*", "remoteActionsTimeout", ")", "\n", "err", "=", "msdw", ".", "wr", ".", "TabletManagerClient", "(", ")", ".", "VReplicationWaitForPos", "(", "shortCtx", ",", "masterInfo", ".", "Tablet", ",", "int", "(", "msdw", ".", "sourceUID", ")", ",", "sourcePosition", ")", "\n", "cancel", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "shardInfo", ".", "MasterAlias", ",", "sourcePosition", ")", "\n", "}", "\n\n", "shortCtx", ",", "cancel", "=", "context", ".", "WithTimeout", "(", "ctx", ",", "*", "remoteActionsTimeout", ")", "\n", "masterPos", ",", "err", ":=", "msdw", ".", "wr", ".", "TabletManagerClient", "(", ")", ".", "MasterPosition", "(", "shortCtx", ",", "masterInfo", ".", "Tablet", ")", "\n", "cancel", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "msdw", ".", "shardInfo", ".", "MasterAlias", ")", "\n", "}", "\n", "return", "masterPos", ",", "nil", "\n", "}" ]
// ask the master of the destination shard to resume filtered replication // up to the specified source position, and return the destination position.
[ "ask", "the", "master", "of", "the", "destination", "shard", "to", "resume", "filtered", "replication", "up", "to", "the", "specified", "source", "position", "and", "return", "the", "destination", "position", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/multi_split_diff.go#L432-L455
train
vitessio/vitess
go/vt/vttablet/tabletserver/vstreamer/engine.go
InitDBConfig
func (vse *Engine) InitDBConfig(dbcfgs *dbconfigs.DBConfigs) { vse.cp = dbcfgs.DbaWithDB() }
go
func (vse *Engine) InitDBConfig(dbcfgs *dbconfigs.DBConfigs) { vse.cp = dbcfgs.DbaWithDB() }
[ "func", "(", "vse", "*", "Engine", ")", "InitDBConfig", "(", "dbcfgs", "*", "dbconfigs", ".", "DBConfigs", ")", "{", "vse", ".", "cp", "=", "dbcfgs", ".", "DbaWithDB", "(", ")", "\n", "}" ]
// InitDBConfig performs saves the required info from dbconfigs for future use.
[ "InitDBConfig", "performs", "saves", "the", "required", "info", "from", "dbconfigs", "for", "future", "use", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/vstreamer/engine.go#L98-L100
train
vitessio/vitess
go/vt/vttablet/tabletserver/vstreamer/engine.go
Stream
func (vse *Engine) Stream(ctx context.Context, startPos string, filter *binlogdatapb.Filter, send func([]*binlogdatapb.VEvent) error) error { // Ensure kschema is initialized and the watcher is started. // Starting of the watcher has to be delayed till the first call to Stream // because this overhead should be incurred only if someone uses this feature. vse.watcherOnce.Do(vse.setWatch) // Create stream and add it to the map. streamer, idx, err := func() (*vstreamer, int, error) { vse.mu.Lock() defer vse.mu.Unlock() if !vse.isOpen { return nil, 0, errors.New("VStreamer is not open") } streamer := newVStreamer(ctx, vse.cp, vse.se, startPos, filter, vse.kschema, send) idx := vse.streamIdx vse.streamers[idx] = streamer vse.streamIdx++ // Now that we've added the stream, increment wg. // This must be done before releasing the lock. vse.wg.Add(1) return streamer, idx, nil }() if err != nil { return err } // Remove stream from map and decrement wg when it ends. defer func() { vse.mu.Lock() defer vse.mu.Unlock() delete(vse.streamers, idx) vse.wg.Done() }() // No lock is held while streaming, but wg is incremented. return streamer.Stream() }
go
func (vse *Engine) Stream(ctx context.Context, startPos string, filter *binlogdatapb.Filter, send func([]*binlogdatapb.VEvent) error) error { // Ensure kschema is initialized and the watcher is started. // Starting of the watcher has to be delayed till the first call to Stream // because this overhead should be incurred only if someone uses this feature. vse.watcherOnce.Do(vse.setWatch) // Create stream and add it to the map. streamer, idx, err := func() (*vstreamer, int, error) { vse.mu.Lock() defer vse.mu.Unlock() if !vse.isOpen { return nil, 0, errors.New("VStreamer is not open") } streamer := newVStreamer(ctx, vse.cp, vse.se, startPos, filter, vse.kschema, send) idx := vse.streamIdx vse.streamers[idx] = streamer vse.streamIdx++ // Now that we've added the stream, increment wg. // This must be done before releasing the lock. vse.wg.Add(1) return streamer, idx, nil }() if err != nil { return err } // Remove stream from map and decrement wg when it ends. defer func() { vse.mu.Lock() defer vse.mu.Unlock() delete(vse.streamers, idx) vse.wg.Done() }() // No lock is held while streaming, but wg is incremented. return streamer.Stream() }
[ "func", "(", "vse", "*", "Engine", ")", "Stream", "(", "ctx", "context", ".", "Context", ",", "startPos", "string", ",", "filter", "*", "binlogdatapb", ".", "Filter", ",", "send", "func", "(", "[", "]", "*", "binlogdatapb", ".", "VEvent", ")", "error", ")", "error", "{", "// Ensure kschema is initialized and the watcher is started.", "// Starting of the watcher has to be delayed till the first call to Stream", "// because this overhead should be incurred only if someone uses this feature.", "vse", ".", "watcherOnce", ".", "Do", "(", "vse", ".", "setWatch", ")", "\n\n", "// Create stream and add it to the map.", "streamer", ",", "idx", ",", "err", ":=", "func", "(", ")", "(", "*", "vstreamer", ",", "int", ",", "error", ")", "{", "vse", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "vse", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "!", "vse", ".", "isOpen", "{", "return", "nil", ",", "0", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "streamer", ":=", "newVStreamer", "(", "ctx", ",", "vse", ".", "cp", ",", "vse", ".", "se", ",", "startPos", ",", "filter", ",", "vse", ".", "kschema", ",", "send", ")", "\n", "idx", ":=", "vse", ".", "streamIdx", "\n", "vse", ".", "streamers", "[", "idx", "]", "=", "streamer", "\n", "vse", ".", "streamIdx", "++", "\n", "// Now that we've added the stream, increment wg.", "// This must be done before releasing the lock.", "vse", ".", "wg", ".", "Add", "(", "1", ")", "\n", "return", "streamer", ",", "idx", ",", "nil", "\n", "}", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Remove stream from map and decrement wg when it ends.", "defer", "func", "(", ")", "{", "vse", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "vse", ".", "mu", ".", "Unlock", "(", ")", "\n", "delete", "(", "vse", ".", "streamers", ",", "idx", ")", "\n", "vse", ".", "wg", ".", "Done", "(", ")", "\n", "}", "(", ")", "\n\n", "// No lock is held while streaming, but wg is incremented.", "return", "streamer", ".", "Stream", "(", ")", "\n", "}" ]
// Stream starts a new stream.
[ "Stream", "starts", "a", "new", "stream", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/vstreamer/engine.go#L146-L182
train
vitessio/vitess
go/vt/vttablet/tabletserver/vstreamer/engine.go
StreamRows
func (vse *Engine) StreamRows(ctx context.Context, query string, lastpk []sqltypes.Value, send func(*binlogdatapb.VStreamRowsResponse) error) error { // Ensure kschema is initialized and the watcher is started. // Starting of the watcher has to be delayed till the first call to Stream // because this overhead should be incurred only if someone uses this feature. vse.watcherOnce.Do(vse.setWatch) log.Infof("Streaming rows for query %s, lastpk: %s", query, lastpk) // Create stream and add it to the map. rowStreamer, idx, err := func() (*rowStreamer, int, error) { vse.mu.Lock() defer vse.mu.Unlock() if !vse.isOpen { return nil, 0, errors.New("VStreamer is not open") } rowStreamer := newRowStreamer(ctx, vse.cp, vse.se, query, lastpk, vse.kschema, send) idx := vse.streamIdx vse.rowStreamers[idx] = rowStreamer vse.streamIdx++ // Now that we've added the stream, increment wg. // This must be done before releasing the lock. vse.wg.Add(1) return rowStreamer, idx, nil }() if err != nil { return err } // Remove stream from map and decrement wg when it ends. defer func() { vse.mu.Lock() defer vse.mu.Unlock() delete(vse.rowStreamers, idx) vse.wg.Done() }() // No lock is held while streaming, but wg is incremented. return rowStreamer.Stream() }
go
func (vse *Engine) StreamRows(ctx context.Context, query string, lastpk []sqltypes.Value, send func(*binlogdatapb.VStreamRowsResponse) error) error { // Ensure kschema is initialized and the watcher is started. // Starting of the watcher has to be delayed till the first call to Stream // because this overhead should be incurred only if someone uses this feature. vse.watcherOnce.Do(vse.setWatch) log.Infof("Streaming rows for query %s, lastpk: %s", query, lastpk) // Create stream and add it to the map. rowStreamer, idx, err := func() (*rowStreamer, int, error) { vse.mu.Lock() defer vse.mu.Unlock() if !vse.isOpen { return nil, 0, errors.New("VStreamer is not open") } rowStreamer := newRowStreamer(ctx, vse.cp, vse.se, query, lastpk, vse.kschema, send) idx := vse.streamIdx vse.rowStreamers[idx] = rowStreamer vse.streamIdx++ // Now that we've added the stream, increment wg. // This must be done before releasing the lock. vse.wg.Add(1) return rowStreamer, idx, nil }() if err != nil { return err } // Remove stream from map and decrement wg when it ends. defer func() { vse.mu.Lock() defer vse.mu.Unlock() delete(vse.rowStreamers, idx) vse.wg.Done() }() // No lock is held while streaming, but wg is incremented. return rowStreamer.Stream() }
[ "func", "(", "vse", "*", "Engine", ")", "StreamRows", "(", "ctx", "context", ".", "Context", ",", "query", "string", ",", "lastpk", "[", "]", "sqltypes", ".", "Value", ",", "send", "func", "(", "*", "binlogdatapb", ".", "VStreamRowsResponse", ")", "error", ")", "error", "{", "// Ensure kschema is initialized and the watcher is started.", "// Starting of the watcher has to be delayed till the first call to Stream", "// because this overhead should be incurred only if someone uses this feature.", "vse", ".", "watcherOnce", ".", "Do", "(", "vse", ".", "setWatch", ")", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "query", ",", "lastpk", ")", "\n\n", "// Create stream and add it to the map.", "rowStreamer", ",", "idx", ",", "err", ":=", "func", "(", ")", "(", "*", "rowStreamer", ",", "int", ",", "error", ")", "{", "vse", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "vse", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "!", "vse", ".", "isOpen", "{", "return", "nil", ",", "0", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "rowStreamer", ":=", "newRowStreamer", "(", "ctx", ",", "vse", ".", "cp", ",", "vse", ".", "se", ",", "query", ",", "lastpk", ",", "vse", ".", "kschema", ",", "send", ")", "\n", "idx", ":=", "vse", ".", "streamIdx", "\n", "vse", ".", "rowStreamers", "[", "idx", "]", "=", "rowStreamer", "\n", "vse", ".", "streamIdx", "++", "\n", "// Now that we've added the stream, increment wg.", "// This must be done before releasing the lock.", "vse", ".", "wg", ".", "Add", "(", "1", ")", "\n", "return", "rowStreamer", ",", "idx", ",", "nil", "\n", "}", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Remove stream from map and decrement wg when it ends.", "defer", "func", "(", ")", "{", "vse", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "vse", ".", "mu", ".", "Unlock", "(", ")", "\n", "delete", "(", "vse", ".", "rowStreamers", ",", "idx", ")", "\n", "vse", ".", "wg", ".", "Done", "(", ")", "\n", "}", "(", ")", "\n\n", "// No lock is held while streaming, but wg is incremented.", "return", "rowStreamer", ".", "Stream", "(", ")", "\n", "}" ]
// StreamRows streams rows.
[ "StreamRows", "streams", "rows", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/vstreamer/engine.go#L185-L222
train
vitessio/vitess
go/vt/vttablet/tabletserver/vstreamer/engine.go
ServeHTTP
func (vse *Engine) ServeHTTP(response http.ResponseWriter, request *http.Request) { if err := acl.CheckAccessHTTP(request, acl.DEBUGGING); err != nil { acl.SendError(response, err) return } response.Header().Set("Content-Type", "application/json; charset=utf-8") vs := vse.vschema() if vs == nil || vs.Keyspace == nil { response.Write([]byte("{}")) } b, err := json.MarshalIndent(vs, "", " ") if err != nil { response.Write([]byte(err.Error())) return } buf := bytes.NewBuffer(nil) json.HTMLEscape(buf, b) response.Write(buf.Bytes()) }
go
func (vse *Engine) ServeHTTP(response http.ResponseWriter, request *http.Request) { if err := acl.CheckAccessHTTP(request, acl.DEBUGGING); err != nil { acl.SendError(response, err) return } response.Header().Set("Content-Type", "application/json; charset=utf-8") vs := vse.vschema() if vs == nil || vs.Keyspace == nil { response.Write([]byte("{}")) } b, err := json.MarshalIndent(vs, "", " ") if err != nil { response.Write([]byte(err.Error())) return } buf := bytes.NewBuffer(nil) json.HTMLEscape(buf, b) response.Write(buf.Bytes()) }
[ "func", "(", "vse", "*", "Engine", ")", "ServeHTTP", "(", "response", "http", ".", "ResponseWriter", ",", "request", "*", "http", ".", "Request", ")", "{", "if", "err", ":=", "acl", ".", "CheckAccessHTTP", "(", "request", ",", "acl", ".", "DEBUGGING", ")", ";", "err", "!=", "nil", "{", "acl", ".", "SendError", "(", "response", ",", "err", ")", "\n", "return", "\n", "}", "\n", "response", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "vs", ":=", "vse", ".", "vschema", "(", ")", "\n", "if", "vs", "==", "nil", "||", "vs", ".", "Keyspace", "==", "nil", "{", "response", ".", "Write", "(", "[", "]", "byte", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "b", ",", "err", ":=", "json", ".", "MarshalIndent", "(", "vs", ",", "\"", "\"", ",", "\"", "\"", ")", "\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", "}" ]
// ServeHTTP shows the current VSchema.
[ "ServeHTTP", "shows", "the", "current", "VSchema", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/vstreamer/engine.go#L225-L243
train
vitessio/vitess
go/acl/acl.go
RegisterPolicy
func RegisterPolicy(name string, policy Policy) { if _, ok := policies[name]; ok { log.Fatalf("policy %s is already registered", name) } policies[name] = policy }
go
func RegisterPolicy(name string, policy Policy) { if _, ok := policies[name]; ok { log.Fatalf("policy %s is already registered", name) } policies[name] = policy }
[ "func", "RegisterPolicy", "(", "name", "string", ",", "policy", "Policy", ")", "{", "if", "_", ",", "ok", ":=", "policies", "[", "name", "]", ";", "ok", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "policies", "[", "name", "]", "=", "policy", "\n", "}" ]
// RegisterPolicy registers a security policy. This function must be called // before the first call to CheckAccess happens, preferably through an init. // This will ensure that the requested policy can be found by other acl // functions when needed.
[ "RegisterPolicy", "registers", "a", "security", "policy", ".", "This", "function", "must", "be", "called", "before", "the", "first", "call", "to", "CheckAccess", "happens", "preferably", "through", "an", "init", ".", "This", "will", "ensure", "that", "the", "requested", "policy", "can", "be", "found", "by", "other", "acl", "functions", "when", "needed", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/acl/acl.go#L63-L68
train
vitessio/vitess
go/acl/acl.go
CheckAccessActor
func CheckAccessActor(actor, role string) error { once.Do(savePolicy) if currentPolicy != nil { return currentPolicy.CheckAccessActor(actor, role) } return nil }
go
func CheckAccessActor(actor, role string) error { once.Do(savePolicy) if currentPolicy != nil { return currentPolicy.CheckAccessActor(actor, role) } return nil }
[ "func", "CheckAccessActor", "(", "actor", ",", "role", "string", ")", "error", "{", "once", ".", "Do", "(", "savePolicy", ")", "\n", "if", "currentPolicy", "!=", "nil", "{", "return", "currentPolicy", ".", "CheckAccessActor", "(", "actor", ",", "role", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CheckAccessActor uses the current security policy to // verify if an actor has access to the role.
[ "CheckAccessActor", "uses", "the", "current", "security", "policy", "to", "verify", "if", "an", "actor", "has", "access", "to", "the", "role", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/acl/acl.go#L83-L89
train
vitessio/vitess
go/acl/acl.go
CheckAccessHTTP
func CheckAccessHTTP(req *http.Request, role string) error { once.Do(savePolicy) if currentPolicy != nil { return currentPolicy.CheckAccessHTTP(req, role) } return nil }
go
func CheckAccessHTTP(req *http.Request, role string) error { once.Do(savePolicy) if currentPolicy != nil { return currentPolicy.CheckAccessHTTP(req, role) } return nil }
[ "func", "CheckAccessHTTP", "(", "req", "*", "http", ".", "Request", ",", "role", "string", ")", "error", "{", "once", ".", "Do", "(", "savePolicy", ")", "\n", "if", "currentPolicy", "!=", "nil", "{", "return", "currentPolicy", ".", "CheckAccessHTTP", "(", "req", ",", "role", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CheckAccessHTTP uses the current security policy to // verify if an actor in an http request has access to // the role.
[ "CheckAccessHTTP", "uses", "the", "current", "security", "policy", "to", "verify", "if", "an", "actor", "in", "an", "http", "request", "has", "access", "to", "the", "role", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/acl/acl.go#L94-L100
train
vitessio/vitess
go/acl/acl.go
SendError
func SendError(w http.ResponseWriter, err error) { w.WriteHeader(http.StatusForbidden) fmt.Fprintf(w, "Access denied: %v\n", err) }
go
func SendError(w http.ResponseWriter, err error) { w.WriteHeader(http.StatusForbidden) fmt.Fprintf(w, "Access denied: %v\n", err) }
[ "func", "SendError", "(", "w", "http", ".", "ResponseWriter", ",", "err", "error", ")", "{", "w", ".", "WriteHeader", "(", "http", ".", "StatusForbidden", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "err", ")", "\n", "}" ]
// SendError is a convenience function that sends an ACL // error as an HTTP response.
[ "SendError", "is", "a", "convenience", "function", "that", "sends", "an", "ACL", "error", "as", "an", "HTTP", "response", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/acl/acl.go#L104-L107
train
vitessio/vitess
go/vt/vtctl/topo.go
DecodeContent
func DecodeContent(filename string, data []byte, json bool) (string, error) { name := path.Base(filename) var p proto.Message switch name { case topo.CellInfoFile: p = new(topodatapb.CellInfo) case topo.KeyspaceFile: p = new(topodatapb.Keyspace) case topo.ShardFile: p = new(topodatapb.Shard) case topo.VSchemaFile: p = new(vschemapb.Keyspace) case topo.ShardReplicationFile: p = new(topodatapb.ShardReplication) case topo.TabletFile: p = new(topodatapb.Tablet) case topo.SrvVSchemaFile: p = new(vschemapb.SrvVSchema) case topo.SrvKeyspaceFile: p = new(topodatapb.SrvKeyspace) case topo.RoutingRulesFile: p = new(vschemapb.RoutingRules) default: if json { return "", fmt.Errorf("unknown topo protobuf type for %v", name) } else { return string(data), nil } } if err := proto.Unmarshal(data, p); err != nil { return string(data), err } if json { return new(jsonpb.Marshaler).MarshalToString(p) } else { return proto.MarshalTextString(p), nil } }
go
func DecodeContent(filename string, data []byte, json bool) (string, error) { name := path.Base(filename) var p proto.Message switch name { case topo.CellInfoFile: p = new(topodatapb.CellInfo) case topo.KeyspaceFile: p = new(topodatapb.Keyspace) case topo.ShardFile: p = new(topodatapb.Shard) case topo.VSchemaFile: p = new(vschemapb.Keyspace) case topo.ShardReplicationFile: p = new(topodatapb.ShardReplication) case topo.TabletFile: p = new(topodatapb.Tablet) case topo.SrvVSchemaFile: p = new(vschemapb.SrvVSchema) case topo.SrvKeyspaceFile: p = new(topodatapb.SrvKeyspace) case topo.RoutingRulesFile: p = new(vschemapb.RoutingRules) default: if json { return "", fmt.Errorf("unknown topo protobuf type for %v", name) } else { return string(data), nil } } if err := proto.Unmarshal(data, p); err != nil { return string(data), err } if json { return new(jsonpb.Marshaler).MarshalToString(p) } else { return proto.MarshalTextString(p), nil } }
[ "func", "DecodeContent", "(", "filename", "string", ",", "data", "[", "]", "byte", ",", "json", "bool", ")", "(", "string", ",", "error", ")", "{", "name", ":=", "path", ".", "Base", "(", "filename", ")", "\n\n", "var", "p", "proto", ".", "Message", "\n", "switch", "name", "{", "case", "topo", ".", "CellInfoFile", ":", "p", "=", "new", "(", "topodatapb", ".", "CellInfo", ")", "\n", "case", "topo", ".", "KeyspaceFile", ":", "p", "=", "new", "(", "topodatapb", ".", "Keyspace", ")", "\n", "case", "topo", ".", "ShardFile", ":", "p", "=", "new", "(", "topodatapb", ".", "Shard", ")", "\n", "case", "topo", ".", "VSchemaFile", ":", "p", "=", "new", "(", "vschemapb", ".", "Keyspace", ")", "\n", "case", "topo", ".", "ShardReplicationFile", ":", "p", "=", "new", "(", "topodatapb", ".", "ShardReplication", ")", "\n", "case", "topo", ".", "TabletFile", ":", "p", "=", "new", "(", "topodatapb", ".", "Tablet", ")", "\n", "case", "topo", ".", "SrvVSchemaFile", ":", "p", "=", "new", "(", "vschemapb", ".", "SrvVSchema", ")", "\n", "case", "topo", ".", "SrvKeyspaceFile", ":", "p", "=", "new", "(", "topodatapb", ".", "SrvKeyspace", ")", "\n", "case", "topo", ".", "RoutingRulesFile", ":", "p", "=", "new", "(", "vschemapb", ".", "RoutingRules", ")", "\n", "default", ":", "if", "json", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "else", "{", "return", "string", "(", "data", ")", ",", "nil", "\n", "}", "\n", "}", "\n\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "data", ",", "p", ")", ";", "err", "!=", "nil", "{", "return", "string", "(", "data", ")", ",", "err", "\n", "}", "\n\n", "if", "json", "{", "return", "new", "(", "jsonpb", ".", "Marshaler", ")", ".", "MarshalToString", "(", "p", ")", "\n", "}", "else", "{", "return", "proto", ".", "MarshalTextString", "(", "p", ")", ",", "nil", "\n", "}", "\n", "}" ]
// DecodeContent uses the filename to imply a type, and proto-decodes // the right object, then echoes it as a string.
[ "DecodeContent", "uses", "the", "filename", "to", "imply", "a", "type", "and", "proto", "-", "decodes", "the", "right", "object", "then", "echoes", "it", "as", "a", "string", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtctl/topo.go#L60-L100
train
vitessio/vitess
go/vt/servenv/grpc_auth.go
RegisterAuthPlugin
func RegisterAuthPlugin(name string, authPlugin func() (Authenticator, error)) { if _, ok := authPlugins[name]; ok { log.Fatalf("AuthPlugin named %v already exists", name) } authPlugins[name] = authPlugin }
go
func RegisterAuthPlugin(name string, authPlugin func() (Authenticator, error)) { if _, ok := authPlugins[name]; ok { log.Fatalf("AuthPlugin named %v already exists", name) } authPlugins[name] = authPlugin }
[ "func", "RegisterAuthPlugin", "(", "name", "string", ",", "authPlugin", "func", "(", ")", "(", "Authenticator", ",", "error", ")", ")", "{", "if", "_", ",", "ok", ":=", "authPlugins", "[", "name", "]", ";", "ok", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "authPlugins", "[", "name", "]", "=", "authPlugin", "\n", "}" ]
// RegisterAuthPlugin registers an implementation of AuthServer.
[ "RegisterAuthPlugin", "registers", "an", "implementation", "of", "AuthServer", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/servenv/grpc_auth.go#L40-L45
train
vitessio/vitess
go/vt/servenv/grpc_auth.go
GetAuthenticator
func GetAuthenticator(name string) func() (Authenticator, error) { authPlugin, ok := authPlugins[name] if !ok { log.Fatalf("no AuthPlugin name %v registered", name) } return authPlugin }
go
func GetAuthenticator(name string) func() (Authenticator, error) { authPlugin, ok := authPlugins[name] if !ok { log.Fatalf("no AuthPlugin name %v registered", name) } return authPlugin }
[ "func", "GetAuthenticator", "(", "name", "string", ")", "func", "(", ")", "(", "Authenticator", ",", "error", ")", "{", "authPlugin", ",", "ok", ":=", "authPlugins", "[", "name", "]", "\n", "if", "!", "ok", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "return", "authPlugin", "\n", "}" ]
// GetAuthenticator returns an AuthPlugin by name, or log.Fatalf.
[ "GetAuthenticator", "returns", "an", "AuthPlugin", "by", "name", "or", "log", ".", "Fatalf", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/servenv/grpc_auth.go#L48-L54
train
vitessio/vitess
go/vt/servenv/grpc_auth.go
FakeAuthStreamInterceptor
func FakeAuthStreamInterceptor(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { if fakeDummyAuthenticate(stream.Context()) { return handler(srv, stream) } return status.Errorf(codes.Unauthenticated, "username and password must be provided") }
go
func FakeAuthStreamInterceptor(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { if fakeDummyAuthenticate(stream.Context()) { return handler(srv, stream) } return status.Errorf(codes.Unauthenticated, "username and password must be provided") }
[ "func", "FakeAuthStreamInterceptor", "(", "srv", "interface", "{", "}", ",", "stream", "grpc", ".", "ServerStream", ",", "info", "*", "grpc", ".", "StreamServerInfo", ",", "handler", "grpc", ".", "StreamHandler", ")", "error", "{", "if", "fakeDummyAuthenticate", "(", "stream", ".", "Context", "(", ")", ")", "{", "return", "handler", "(", "srv", ",", "stream", ")", "\n", "}", "\n", "return", "status", ".", "Errorf", "(", "codes", ".", "Unauthenticated", ",", "\"", "\"", ")", "\n", "}" ]
// FakeAuthStreamInterceptor fake interceptor to test plugin
[ "FakeAuthStreamInterceptor", "fake", "interceptor", "to", "test", "plugin" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/servenv/grpc_auth.go#L57-L62
train
vitessio/vitess
go/vt/servenv/grpc_auth.go
FakeAuthUnaryInterceptor
func FakeAuthUnaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { if fakeDummyAuthenticate(ctx) { return handler(ctx, req) } return nil, status.Errorf(codes.Unauthenticated, "username and password must be provided") }
go
func FakeAuthUnaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { if fakeDummyAuthenticate(ctx) { return handler(ctx, req) } return nil, status.Errorf(codes.Unauthenticated, "username and password must be provided") }
[ "func", "FakeAuthUnaryInterceptor", "(", "ctx", "context", ".", "Context", ",", "req", "interface", "{", "}", ",", "info", "*", "grpc", ".", "UnaryServerInfo", ",", "handler", "grpc", ".", "UnaryHandler", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "fakeDummyAuthenticate", "(", "ctx", ")", "{", "return", "handler", "(", "ctx", ",", "req", ")", "\n", "}", "\n", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "Unauthenticated", ",", "\"", "\"", ")", "\n", "}" ]
// FakeAuthUnaryInterceptor fake interceptor to test plugin
[ "FakeAuthUnaryInterceptor", "fake", "interceptor", "to", "test", "plugin" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/servenv/grpc_auth.go#L65-L70
train
vitessio/vitess
go/vt/throttler/demo/throttler_demo.go
execute
func (m *master) execute(msg time.Time) { m.replica.replicate(msg) }
go
func (m *master) execute(msg time.Time) { m.replica.replicate(msg) }
[ "func", "(", "m", "*", "master", ")", "execute", "(", "msg", "time", ".", "Time", ")", "{", "m", ".", "replica", ".", "replicate", "(", "msg", ")", "\n", "}" ]
// execute is the simulated RPC which is called by the client.
[ "execute", "is", "the", "simulated", "RPC", "which", "is", "called", "by", "the", "client", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/demo/throttler_demo.go#L77-L79
train
vitessio/vitess
go/vt/throttler/demo/throttler_demo.go
StatsUpdate
func (c *client) StatsUpdate(ts *discovery.TabletStats) { // Ignore unless REPLICA or RDONLY. if ts.Target.TabletType != topodatapb.TabletType_REPLICA && ts.Target.TabletType != topodatapb.TabletType_RDONLY { return } c.throttler.RecordReplicationLag(time.Now(), ts) }
go
func (c *client) StatsUpdate(ts *discovery.TabletStats) { // Ignore unless REPLICA or RDONLY. if ts.Target.TabletType != topodatapb.TabletType_REPLICA && ts.Target.TabletType != topodatapb.TabletType_RDONLY { return } c.throttler.RecordReplicationLag(time.Now(), ts) }
[ "func", "(", "c", "*", "client", ")", "StatsUpdate", "(", "ts", "*", "discovery", ".", "TabletStats", ")", "{", "// Ignore unless REPLICA or RDONLY.", "if", "ts", ".", "Target", ".", "TabletType", "!=", "topodatapb", ".", "TabletType_REPLICA", "&&", "ts", ".", "Target", ".", "TabletType", "!=", "topodatapb", ".", "TabletType_RDONLY", "{", "return", "\n", "}", "\n\n", "c", ".", "throttler", ".", "RecordReplicationLag", "(", "time", ".", "Now", "(", ")", ",", "ts", ")", "\n", "}" ]
// StatsUpdate implements discovery.HealthCheckStatsListener. // It gets called by the healthCheck instance every time a tablet broadcasts // a health update.
[ "StatsUpdate", "implements", "discovery", ".", "HealthCheckStatsListener", ".", "It", "gets", "called", "by", "the", "healthCheck", "instance", "every", "time", "a", "tablet", "broadcasts", "a", "health", "update", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/demo/throttler_demo.go#L279-L286
train
vitessio/vitess
go/vt/worker/vertical_split_diff.go
NewVerticalSplitDiffWorker
func NewVerticalSplitDiffWorker(wr *wrangler.Wrangler, cell, keyspace, shard string, minHealthyRdonlyTablets, parallelDiffsCount int, destintationTabletType topodatapb.TabletType) Worker { return &VerticalSplitDiffWorker{ StatusWorker: NewStatusWorker(), wr: wr, cell: cell, keyspace: keyspace, shard: shard, minHealthyRdonlyTablets: minHealthyRdonlyTablets, destinationTabletType: destintationTabletType, parallelDiffsCount: parallelDiffsCount, cleaner: &wrangler.Cleaner{}, } }
go
func NewVerticalSplitDiffWorker(wr *wrangler.Wrangler, cell, keyspace, shard string, minHealthyRdonlyTablets, parallelDiffsCount int, destintationTabletType topodatapb.TabletType) Worker { return &VerticalSplitDiffWorker{ StatusWorker: NewStatusWorker(), wr: wr, cell: cell, keyspace: keyspace, shard: shard, minHealthyRdonlyTablets: minHealthyRdonlyTablets, destinationTabletType: destintationTabletType, parallelDiffsCount: parallelDiffsCount, cleaner: &wrangler.Cleaner{}, } }
[ "func", "NewVerticalSplitDiffWorker", "(", "wr", "*", "wrangler", ".", "Wrangler", ",", "cell", ",", "keyspace", ",", "shard", "string", ",", "minHealthyRdonlyTablets", ",", "parallelDiffsCount", "int", ",", "destintationTabletType", "topodatapb", ".", "TabletType", ")", "Worker", "{", "return", "&", "VerticalSplitDiffWorker", "{", "StatusWorker", ":", "NewStatusWorker", "(", ")", ",", "wr", ":", "wr", ",", "cell", ":", "cell", ",", "keyspace", ":", "keyspace", ",", "shard", ":", "shard", ",", "minHealthyRdonlyTablets", ":", "minHealthyRdonlyTablets", ",", "destinationTabletType", ":", "destintationTabletType", ",", "parallelDiffsCount", ":", "parallelDiffsCount", ",", "cleaner", ":", "&", "wrangler", ".", "Cleaner", "{", "}", ",", "}", "\n", "}" ]
// NewVerticalSplitDiffWorker returns a new VerticalSplitDiffWorker object.
[ "NewVerticalSplitDiffWorker", "returns", "a", "new", "VerticalSplitDiffWorker", "object", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/vertical_split_diff.go#L69-L81
train
vitessio/vitess
go/vt/sqlparser/redact_query.go
RedactSQLQuery
func RedactSQLQuery(sql string) (string, error) { bv := map[string]*querypb.BindVariable{} sqlStripped, comments := SplitMarginComments(sql) stmt, err := Parse(sqlStripped) if err != nil { return "", err } prefix := "redacted" Normalize(stmt, bv, prefix) return comments.Leading + String(stmt) + comments.Trailing, nil }
go
func RedactSQLQuery(sql string) (string, error) { bv := map[string]*querypb.BindVariable{} sqlStripped, comments := SplitMarginComments(sql) stmt, err := Parse(sqlStripped) if err != nil { return "", err } prefix := "redacted" Normalize(stmt, bv, prefix) return comments.Leading + String(stmt) + comments.Trailing, nil }
[ "func", "RedactSQLQuery", "(", "sql", "string", ")", "(", "string", ",", "error", ")", "{", "bv", ":=", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", "{", "}", "\n", "sqlStripped", ",", "comments", ":=", "SplitMarginComments", "(", "sql", ")", "\n\n", "stmt", ",", "err", ":=", "Parse", "(", "sqlStripped", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "prefix", ":=", "\"", "\"", "\n", "Normalize", "(", "stmt", ",", "bv", ",", "prefix", ")", "\n\n", "return", "comments", ".", "Leading", "+", "String", "(", "stmt", ")", "+", "comments", ".", "Trailing", ",", "nil", "\n", "}" ]
// RedactSQLQuery returns a sql string with the params stripped out for display
[ "RedactSQLQuery", "returns", "a", "sql", "string", "with", "the", "params", "stripped", "out", "for", "display" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/redact_query.go#L6-L19
train
vitessio/vitess
go/vt/vtctl/fakevtctlclient/fake_loggerevent_streamingclient.go
RegisterResultForAddr
func (f *FakeLoggerEventStreamingClient) RegisterResultForAddr(addr string, args []string, output string, err error) error { f.mu.Lock() defer f.mu.Unlock() k := generateKey(args) v := result{output, err, 1, addr} if result, ok := f.results[k]; ok { if result.Equals(v) { result.count++ return nil } return fmt.Errorf("a different result (%v) is already registered for command: %v", result, args) } f.results[k] = &v return nil }
go
func (f *FakeLoggerEventStreamingClient) RegisterResultForAddr(addr string, args []string, output string, err error) error { f.mu.Lock() defer f.mu.Unlock() k := generateKey(args) v := result{output, err, 1, addr} if result, ok := f.results[k]; ok { if result.Equals(v) { result.count++ return nil } return fmt.Errorf("a different result (%v) is already registered for command: %v", result, args) } f.results[k] = &v return nil }
[ "func", "(", "f", "*", "FakeLoggerEventStreamingClient", ")", "RegisterResultForAddr", "(", "addr", "string", ",", "args", "[", "]", "string", ",", "output", "string", ",", "err", "error", ")", "error", "{", "f", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "f", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "k", ":=", "generateKey", "(", "args", ")", "\n", "v", ":=", "result", "{", "output", ",", "err", ",", "1", ",", "addr", "}", "\n", "if", "result", ",", "ok", ":=", "f", ".", "results", "[", "k", "]", ";", "ok", "{", "if", "result", ".", "Equals", "(", "v", ")", "{", "result", ".", "count", "++", "\n", "return", "nil", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "result", ",", "args", ")", "\n", "}", "\n", "f", ".", "results", "[", "k", "]", "=", "&", "v", "\n", "return", "nil", "\n", "}" ]
// RegisterResultForAddr is identical to RegisterResult but also expects that // the client did dial "addr" as server address.
[ "RegisterResultForAddr", "is", "identical", "to", "RegisterResult", "but", "also", "expects", "that", "the", "client", "did", "dial", "addr", "as", "server", "address", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtctl/fakevtctlclient/fake_loggerevent_streamingclient.go#L75-L90
train
vitessio/vitess
go/vt/vtctl/fakevtctlclient/fake_loggerevent_streamingclient.go
RegisteredCommands
func (f *FakeLoggerEventStreamingClient) RegisteredCommands() []string { f.mu.Lock() defer f.mu.Unlock() var commands []string for k := range f.results { commands = append(commands, k) } return commands }
go
func (f *FakeLoggerEventStreamingClient) RegisteredCommands() []string { f.mu.Lock() defer f.mu.Unlock() var commands []string for k := range f.results { commands = append(commands, k) } return commands }
[ "func", "(", "f", "*", "FakeLoggerEventStreamingClient", ")", "RegisteredCommands", "(", ")", "[", "]", "string", "{", "f", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "f", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "var", "commands", "[", "]", "string", "\n", "for", "k", ":=", "range", "f", ".", "results", "{", "commands", "=", "append", "(", "commands", ",", "k", ")", "\n", "}", "\n", "return", "commands", "\n", "}" ]
// RegisteredCommands returns a list of commands which are currently registered. // This is useful to check that all registered results have been consumed.
[ "RegisteredCommands", "returns", "a", "list", "of", "commands", "which", "are", "currently", "registered", ".", "This", "is", "useful", "to", "check", "that", "all", "registered", "results", "have", "been", "consumed", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtctl/fakevtctlclient/fake_loggerevent_streamingclient.go#L94-L103
train
vitessio/vitess
go/vt/vtctl/fakevtctlclient/fake_loggerevent_streamingclient.go
StreamResult
func (f *FakeLoggerEventStreamingClient) StreamResult(addr string, args []string) (logutil.EventStream, error) { f.mu.Lock() defer f.mu.Unlock() k := generateKey(args) result, ok := f.results[k] if !ok { return nil, fmt.Errorf("no response was registered for args: %v", args) } if result.addr != "" && addr != result.addr { return nil, fmt.Errorf("client sent request to wrong server address. got: %v want: %v", addr, result.addr) } result.count-- if result.count == 0 { delete(f.results, k) } return &streamResultAdapter{ lines: strings.Split(result.output, "\n"), index: 0, err: result.err, }, nil }
go
func (f *FakeLoggerEventStreamingClient) StreamResult(addr string, args []string) (logutil.EventStream, error) { f.mu.Lock() defer f.mu.Unlock() k := generateKey(args) result, ok := f.results[k] if !ok { return nil, fmt.Errorf("no response was registered for args: %v", args) } if result.addr != "" && addr != result.addr { return nil, fmt.Errorf("client sent request to wrong server address. got: %v want: %v", addr, result.addr) } result.count-- if result.count == 0 { delete(f.results, k) } return &streamResultAdapter{ lines: strings.Split(result.output, "\n"), index: 0, err: result.err, }, nil }
[ "func", "(", "f", "*", "FakeLoggerEventStreamingClient", ")", "StreamResult", "(", "addr", "string", ",", "args", "[", "]", "string", ")", "(", "logutil", ".", "EventStream", ",", "error", ")", "{", "f", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "f", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "k", ":=", "generateKey", "(", "args", ")", "\n", "result", ",", "ok", ":=", "f", ".", "results", "[", "k", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "args", ")", "\n", "}", "\n", "if", "result", ".", "addr", "!=", "\"", "\"", "&&", "addr", "!=", "result", ".", "addr", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "addr", ",", "result", ".", "addr", ")", "\n", "}", "\n", "result", ".", "count", "--", "\n", "if", "result", ".", "count", "==", "0", "{", "delete", "(", "f", ".", "results", ",", "k", ")", "\n", "}", "\n\n", "return", "&", "streamResultAdapter", "{", "lines", ":", "strings", ".", "Split", "(", "result", ".", "output", ",", "\"", "\\n", "\"", ")", ",", "index", ":", "0", ",", "err", ":", "result", ".", "err", ",", "}", ",", "nil", "\n", "}" ]
// StreamResult returns an EventStream which streams back a registered result as logging events. // "addr" is the server address which the client dialed and may be empty.
[ "StreamResult", "returns", "an", "EventStream", "which", "streams", "back", "a", "registered", "result", "as", "logging", "events", ".", "addr", "is", "the", "server", "address", "which", "the", "client", "dialed", "and", "may", "be", "empty", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtctl/fakevtctlclient/fake_loggerevent_streamingclient.go#L131-L153
train
vitessio/vitess
go/vt/vttablet/tabletmanager/vreplication/stats.go
StatusSummary
func StatusSummary() (maxSecondsBehindMaster int64, binlogPlayersCount int32) { return globalStats.maxSecondsBehindMaster(), int32(globalStats.numControllers()) }
go
func StatusSummary() (maxSecondsBehindMaster int64, binlogPlayersCount int32) { return globalStats.maxSecondsBehindMaster(), int32(globalStats.numControllers()) }
[ "func", "StatusSummary", "(", ")", "(", "maxSecondsBehindMaster", "int64", ",", "binlogPlayersCount", "int32", ")", "{", "return", "globalStats", ".", "maxSecondsBehindMaster", "(", ")", ",", "int32", "(", "globalStats", ".", "numControllers", "(", ")", ")", "\n", "}" ]
// StatusSummary returns the summary status of vreplication.
[ "StatusSummary", "returns", "the", "summary", "status", "of", "vreplication", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/vreplication/stats.go#L37-L39
train
vitessio/vitess
go/vt/vtgate/buffer/shard_buffer.go
oldestEntry
func (sb *shardBuffer) oldestEntry() *entry { sb.mu.Lock() defer sb.mu.Unlock() if len(sb.queue) > 0 { return sb.queue[0] } return nil }
go
func (sb *shardBuffer) oldestEntry() *entry { sb.mu.Lock() defer sb.mu.Unlock() if len(sb.queue) > 0 { return sb.queue[0] } return nil }
[ "func", "(", "sb", "*", "shardBuffer", ")", "oldestEntry", "(", ")", "*", "entry", "{", "sb", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "sb", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "len", "(", "sb", ".", "queue", ")", ">", "0", "{", "return", "sb", ".", "queue", "[", "0", "]", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// oldestEntry returns the head of the queue or nil if the queue is empty.
[ "oldestEntry", "returns", "the", "head", "of", "the", "queue", "or", "nil", "if", "the", "queue", "is", "empty", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/buffer/shard_buffer.go#L396-L404
train
vitessio/vitess
go/vt/vtgate/buffer/shard_buffer.go
evictOldestEntry
func (sb *shardBuffer) evictOldestEntry(e *entry) { sb.mu.Lock() defer sb.mu.Unlock() if len(sb.queue) == 0 || e != sb.queue[0] { // Entry is already removed e.g. by remove(). Ignore it. return } // Evict the entry. // // NOTE: We're not waiting for the request to finish in order to unblock the // timeout thread as fast as possible. However, the slot of the evicted // request is only returned after it has finished i.e. the buffer may stay // full in the meantime. This is a design tradeoff to keep things simple and // avoid additional pressure on the master tablet. sb.unblockAndWait(e, nil /* err */, true /* releaseSlot */, false /* blockingWait */) sb.queue = sb.queue[1:] statsKeyWithReason := append(sb.statsKey, evictedWindowExceeded) requestsEvicted.Add(statsKeyWithReason, 1) }
go
func (sb *shardBuffer) evictOldestEntry(e *entry) { sb.mu.Lock() defer sb.mu.Unlock() if len(sb.queue) == 0 || e != sb.queue[0] { // Entry is already removed e.g. by remove(). Ignore it. return } // Evict the entry. // // NOTE: We're not waiting for the request to finish in order to unblock the // timeout thread as fast as possible. However, the slot of the evicted // request is only returned after it has finished i.e. the buffer may stay // full in the meantime. This is a design tradeoff to keep things simple and // avoid additional pressure on the master tablet. sb.unblockAndWait(e, nil /* err */, true /* releaseSlot */, false /* blockingWait */) sb.queue = sb.queue[1:] statsKeyWithReason := append(sb.statsKey, evictedWindowExceeded) requestsEvicted.Add(statsKeyWithReason, 1) }
[ "func", "(", "sb", "*", "shardBuffer", ")", "evictOldestEntry", "(", "e", "*", "entry", ")", "{", "sb", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "sb", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "len", "(", "sb", ".", "queue", ")", "==", "0", "||", "e", "!=", "sb", ".", "queue", "[", "0", "]", "{", "// Entry is already removed e.g. by remove(). Ignore it.", "return", "\n", "}", "\n\n", "// Evict the entry.", "//", "// NOTE: We're not waiting for the request to finish in order to unblock the", "// timeout thread as fast as possible. However, the slot of the evicted", "// request is only returned after it has finished i.e. the buffer may stay", "// full in the meantime. This is a design tradeoff to keep things simple and", "// avoid additional pressure on the master tablet.", "sb", ".", "unblockAndWait", "(", "e", ",", "nil", "/* err */", ",", "true", "/* releaseSlot */", ",", "false", "/* blockingWait */", ")", "\n", "sb", ".", "queue", "=", "sb", ".", "queue", "[", "1", ":", "]", "\n", "statsKeyWithReason", ":=", "append", "(", "sb", ".", "statsKey", ",", "evictedWindowExceeded", ")", "\n", "requestsEvicted", ".", "Add", "(", "statsKeyWithReason", ",", "1", ")", "\n", "}" ]
// evictOldestEntry is used by timeoutThread to evict the head entry of the // queue if it exceeded its buffering window.
[ "evictOldestEntry", "is", "used", "by", "timeoutThread", "to", "evict", "the", "head", "entry", "of", "the", "queue", "if", "it", "exceeded", "its", "buffering", "window", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/buffer/shard_buffer.go#L408-L428
train
vitessio/vitess
go/vt/vtgate/buffer/shard_buffer.go
remove
func (sb *shardBuffer) remove(toRemove *entry) { sb.mu.Lock() defer sb.mu.Unlock() if sb.queue == nil { // Queue is cleared because we're already in the DRAIN phase. return } // If entry is still in the queue, delete it and cancel it internally. for i, e := range sb.queue { if e == toRemove { // Delete entry at index "i" from slice. sb.queue = append(sb.queue[:i], sb.queue[i+1:]...) // Cancel the entry's "bufferCtx". // The usual drain or eviction code would unblock the request and then // wait for the "bufferCtx" to be done. // But this code path is different because it's going to return an error // to the request and not the "e.bufferCancel" function i.e. the request // cannot cancel the "bufferCtx" itself. // Therefore, we call "e.bufferCancel". This also avoids that the // context's Go routine could leak. e.bufferCancel() // Release the buffer slot and close the "e.done" channel. // By closing "e.done", we finish it explicitly and timeoutThread will // find out about it as well. sb.unblockAndWait(e, nil /* err */, true /* releaseSlot */, false /* blockingWait */) // Track it as "ContextDone" eviction. statsKeyWithReason := append(sb.statsKey, string(evictedContextDone)) requestsEvicted.Add(statsKeyWithReason, 1) return } } // Entry was already removed. Keep the queue as it is. }
go
func (sb *shardBuffer) remove(toRemove *entry) { sb.mu.Lock() defer sb.mu.Unlock() if sb.queue == nil { // Queue is cleared because we're already in the DRAIN phase. return } // If entry is still in the queue, delete it and cancel it internally. for i, e := range sb.queue { if e == toRemove { // Delete entry at index "i" from slice. sb.queue = append(sb.queue[:i], sb.queue[i+1:]...) // Cancel the entry's "bufferCtx". // The usual drain or eviction code would unblock the request and then // wait for the "bufferCtx" to be done. // But this code path is different because it's going to return an error // to the request and not the "e.bufferCancel" function i.e. the request // cannot cancel the "bufferCtx" itself. // Therefore, we call "e.bufferCancel". This also avoids that the // context's Go routine could leak. e.bufferCancel() // Release the buffer slot and close the "e.done" channel. // By closing "e.done", we finish it explicitly and timeoutThread will // find out about it as well. sb.unblockAndWait(e, nil /* err */, true /* releaseSlot */, false /* blockingWait */) // Track it as "ContextDone" eviction. statsKeyWithReason := append(sb.statsKey, string(evictedContextDone)) requestsEvicted.Add(statsKeyWithReason, 1) return } } // Entry was already removed. Keep the queue as it is. }
[ "func", "(", "sb", "*", "shardBuffer", ")", "remove", "(", "toRemove", "*", "entry", ")", "{", "sb", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "sb", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "sb", ".", "queue", "==", "nil", "{", "// Queue is cleared because we're already in the DRAIN phase.", "return", "\n", "}", "\n\n", "// If entry is still in the queue, delete it and cancel it internally.", "for", "i", ",", "e", ":=", "range", "sb", ".", "queue", "{", "if", "e", "==", "toRemove", "{", "// Delete entry at index \"i\" from slice.", "sb", ".", "queue", "=", "append", "(", "sb", ".", "queue", "[", ":", "i", "]", ",", "sb", ".", "queue", "[", "i", "+", "1", ":", "]", "...", ")", "\n\n", "// Cancel the entry's \"bufferCtx\".", "// The usual drain or eviction code would unblock the request and then", "// wait for the \"bufferCtx\" to be done.", "// But this code path is different because it's going to return an error", "// to the request and not the \"e.bufferCancel\" function i.e. the request", "// cannot cancel the \"bufferCtx\" itself.", "// Therefore, we call \"e.bufferCancel\". This also avoids that the", "// context's Go routine could leak.", "e", ".", "bufferCancel", "(", ")", "\n", "// Release the buffer slot and close the \"e.done\" channel.", "// By closing \"e.done\", we finish it explicitly and timeoutThread will", "// find out about it as well.", "sb", ".", "unblockAndWait", "(", "e", ",", "nil", "/* err */", ",", "true", "/* releaseSlot */", ",", "false", "/* blockingWait */", ")", "\n\n", "// Track it as \"ContextDone\" eviction.", "statsKeyWithReason", ":=", "append", "(", "sb", ".", "statsKey", ",", "string", "(", "evictedContextDone", ")", ")", "\n", "requestsEvicted", ".", "Add", "(", "statsKeyWithReason", ",", "1", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "// Entry was already removed. Keep the queue as it is.", "}" ]
// remove must be called when the request was canceled from outside and not // internally.
[ "remove", "must", "be", "called", "when", "the", "request", "was", "canceled", "from", "outside", "and", "not", "internally", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/buffer/shard_buffer.go#L432-L469
train
vitessio/vitess
go/mysql/auth_server_static.go
InitAuthServerStatic
func InitAuthServerStatic() { // Check parameters. if *mysqlAuthServerStaticFile == "" && *mysqlAuthServerStaticString == "" { // Not configured, nothing to do. log.Infof("Not configuring AuthServerStatic, as mysql_auth_server_static_file and mysql_auth_server_static_string are empty") return } if *mysqlAuthServerStaticFile != "" && *mysqlAuthServerStaticString != "" { // Both parameters specified, can only use one. log.Exitf("Both mysql_auth_server_static_file and mysql_auth_server_static_string specified, can only use one.") } // Create and register auth server. RegisterAuthServerStaticFromParams(*mysqlAuthServerStaticFile, *mysqlAuthServerStaticString) }
go
func InitAuthServerStatic() { // Check parameters. if *mysqlAuthServerStaticFile == "" && *mysqlAuthServerStaticString == "" { // Not configured, nothing to do. log.Infof("Not configuring AuthServerStatic, as mysql_auth_server_static_file and mysql_auth_server_static_string are empty") return } if *mysqlAuthServerStaticFile != "" && *mysqlAuthServerStaticString != "" { // Both parameters specified, can only use one. log.Exitf("Both mysql_auth_server_static_file and mysql_auth_server_static_string specified, can only use one.") } // Create and register auth server. RegisterAuthServerStaticFromParams(*mysqlAuthServerStaticFile, *mysqlAuthServerStaticString) }
[ "func", "InitAuthServerStatic", "(", ")", "{", "// Check parameters.", "if", "*", "mysqlAuthServerStaticFile", "==", "\"", "\"", "&&", "*", "mysqlAuthServerStaticString", "==", "\"", "\"", "{", "// Not configured, nothing to do.", "log", ".", "Infof", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "if", "*", "mysqlAuthServerStaticFile", "!=", "\"", "\"", "&&", "*", "mysqlAuthServerStaticString", "!=", "\"", "\"", "{", "// Both parameters specified, can only use one.", "log", ".", "Exitf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Create and register auth server.", "RegisterAuthServerStaticFromParams", "(", "*", "mysqlAuthServerStaticFile", ",", "*", "mysqlAuthServerStaticString", ")", "\n", "}" ]
// InitAuthServerStatic Handles initializing the AuthServerStatic if necessary.
[ "InitAuthServerStatic", "Handles", "initializing", "the", "AuthServerStatic", "if", "necessary", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/auth_server_static.go#L82-L96
train
vitessio/vitess
go/mysql/auth_server_static.go
RegisterAuthServerStaticFromParams
func RegisterAuthServerStaticFromParams(file, str string) { authServerStatic := NewAuthServerStatic() authServerStatic.loadConfigFromParams(file, str) if len(authServerStatic.Entries) <= 0 { log.Exitf("Failed to populate entries from file: %v", file) } authServerStatic.installSignalHandlers() // And register the server. RegisterAuthServerImpl("static", authServerStatic) }
go
func RegisterAuthServerStaticFromParams(file, str string) { authServerStatic := NewAuthServerStatic() authServerStatic.loadConfigFromParams(file, str) if len(authServerStatic.Entries) <= 0 { log.Exitf("Failed to populate entries from file: %v", file) } authServerStatic.installSignalHandlers() // And register the server. RegisterAuthServerImpl("static", authServerStatic) }
[ "func", "RegisterAuthServerStaticFromParams", "(", "file", ",", "str", "string", ")", "{", "authServerStatic", ":=", "NewAuthServerStatic", "(", ")", "\n\n", "authServerStatic", ".", "loadConfigFromParams", "(", "file", ",", "str", ")", "\n\n", "if", "len", "(", "authServerStatic", ".", "Entries", ")", "<=", "0", "{", "log", ".", "Exitf", "(", "\"", "\"", ",", "file", ")", "\n", "}", "\n", "authServerStatic", ".", "installSignalHandlers", "(", ")", "\n\n", "// And register the server.", "RegisterAuthServerImpl", "(", "\"", "\"", ",", "authServerStatic", ")", "\n", "}" ]
// RegisterAuthServerStaticFromParams creates and registers a new // AuthServerStatic, loaded for a JSON file or string. If file is set, // it uses file. Otherwise, load the string. It log.Exits out in case // of error.
[ "RegisterAuthServerStaticFromParams", "creates", "and", "registers", "a", "new", "AuthServerStatic", "loaded", "for", "a", "JSON", "file", "or", "string", ".", "If", "file", "is", "set", "it", "uses", "file", ".", "Otherwise", "load", "the", "string", ".", "It", "log", ".", "Exits", "out", "in", "case", "of", "error", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/auth_server_static.go#L110-L122
train
vitessio/vitess
go/mysql/auth_server_static.go
ValidateHash
func (a *AuthServerStatic) ValidateHash(salt []byte, user string, authResponse []byte, remoteAddr net.Addr) (Getter, error) { a.mu.Lock() entries, ok := a.Entries[user] a.mu.Unlock() if !ok { return &StaticUserData{}, NewSQLError(ERAccessDeniedError, SSAccessDeniedError, "Access denied for user '%v'", user) } for _, entry := range entries { if entry.MysqlNativePassword != "" { isPass := isPassScrambleMysqlNativePassword(authResponse, salt, entry.MysqlNativePassword) if matchSourceHost(remoteAddr, entry.SourceHost) && isPass { return &StaticUserData{entry.UserData, entry.Groups}, nil } } else { computedAuthResponse := ScramblePassword(salt, []byte(entry.Password)) // Validate the password. if matchSourceHost(remoteAddr, entry.SourceHost) && bytes.Equal(authResponse, computedAuthResponse) { return &StaticUserData{entry.UserData, entry.Groups}, nil } } } return &StaticUserData{}, NewSQLError(ERAccessDeniedError, SSAccessDeniedError, "Access denied for user '%v'", user) }
go
func (a *AuthServerStatic) ValidateHash(salt []byte, user string, authResponse []byte, remoteAddr net.Addr) (Getter, error) { a.mu.Lock() entries, ok := a.Entries[user] a.mu.Unlock() if !ok { return &StaticUserData{}, NewSQLError(ERAccessDeniedError, SSAccessDeniedError, "Access denied for user '%v'", user) } for _, entry := range entries { if entry.MysqlNativePassword != "" { isPass := isPassScrambleMysqlNativePassword(authResponse, salt, entry.MysqlNativePassword) if matchSourceHost(remoteAddr, entry.SourceHost) && isPass { return &StaticUserData{entry.UserData, entry.Groups}, nil } } else { computedAuthResponse := ScramblePassword(salt, []byte(entry.Password)) // Validate the password. if matchSourceHost(remoteAddr, entry.SourceHost) && bytes.Equal(authResponse, computedAuthResponse) { return &StaticUserData{entry.UserData, entry.Groups}, nil } } } return &StaticUserData{}, NewSQLError(ERAccessDeniedError, SSAccessDeniedError, "Access denied for user '%v'", user) }
[ "func", "(", "a", "*", "AuthServerStatic", ")", "ValidateHash", "(", "salt", "[", "]", "byte", ",", "user", "string", ",", "authResponse", "[", "]", "byte", ",", "remoteAddr", "net", ".", "Addr", ")", "(", "Getter", ",", "error", ")", "{", "a", ".", "mu", ".", "Lock", "(", ")", "\n", "entries", ",", "ok", ":=", "a", ".", "Entries", "[", "user", "]", "\n", "a", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "!", "ok", "{", "return", "&", "StaticUserData", "{", "}", ",", "NewSQLError", "(", "ERAccessDeniedError", ",", "SSAccessDeniedError", ",", "\"", "\"", ",", "user", ")", "\n", "}", "\n\n", "for", "_", ",", "entry", ":=", "range", "entries", "{", "if", "entry", ".", "MysqlNativePassword", "!=", "\"", "\"", "{", "isPass", ":=", "isPassScrambleMysqlNativePassword", "(", "authResponse", ",", "salt", ",", "entry", ".", "MysqlNativePassword", ")", "\n", "if", "matchSourceHost", "(", "remoteAddr", ",", "entry", ".", "SourceHost", ")", "&&", "isPass", "{", "return", "&", "StaticUserData", "{", "entry", ".", "UserData", ",", "entry", ".", "Groups", "}", ",", "nil", "\n", "}", "\n", "}", "else", "{", "computedAuthResponse", ":=", "ScramblePassword", "(", "salt", ",", "[", "]", "byte", "(", "entry", ".", "Password", ")", ")", "\n", "// Validate the password.", "if", "matchSourceHost", "(", "remoteAddr", ",", "entry", ".", "SourceHost", ")", "&&", "bytes", ".", "Equal", "(", "authResponse", ",", "computedAuthResponse", ")", "{", "return", "&", "StaticUserData", "{", "entry", ".", "UserData", ",", "entry", ".", "Groups", "}", ",", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "&", "StaticUserData", "{", "}", ",", "NewSQLError", "(", "ERAccessDeniedError", ",", "SSAccessDeniedError", ",", "\"", "\"", ",", "user", ")", "\n", "}" ]
// ValidateHash is part of the AuthServer interface.
[ "ValidateHash", "is", "part", "of", "the", "AuthServer", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/auth_server_static.go#L224-L248
train
vitessio/vitess
go/mysql/auth_server_static.go
Negotiate
func (a *AuthServerStatic) Negotiate(c *Conn, user string, remoteAddr net.Addr) (Getter, error) { // Finish the negotiation. password, err := AuthServerNegotiateClearOrDialog(c, a.Method) if err != nil { return nil, err } a.mu.Lock() entries, ok := a.Entries[user] a.mu.Unlock() if !ok { return &StaticUserData{}, NewSQLError(ERAccessDeniedError, SSAccessDeniedError, "Access denied for user '%v'", user) } for _, entry := range entries { // Validate the password. if matchSourceHost(remoteAddr, entry.SourceHost) && entry.Password == password { return &StaticUserData{entry.UserData, entry.Groups}, nil } } return &StaticUserData{}, NewSQLError(ERAccessDeniedError, SSAccessDeniedError, "Access denied for user '%v'", user) }
go
func (a *AuthServerStatic) Negotiate(c *Conn, user string, remoteAddr net.Addr) (Getter, error) { // Finish the negotiation. password, err := AuthServerNegotiateClearOrDialog(c, a.Method) if err != nil { return nil, err } a.mu.Lock() entries, ok := a.Entries[user] a.mu.Unlock() if !ok { return &StaticUserData{}, NewSQLError(ERAccessDeniedError, SSAccessDeniedError, "Access denied for user '%v'", user) } for _, entry := range entries { // Validate the password. if matchSourceHost(remoteAddr, entry.SourceHost) && entry.Password == password { return &StaticUserData{entry.UserData, entry.Groups}, nil } } return &StaticUserData{}, NewSQLError(ERAccessDeniedError, SSAccessDeniedError, "Access denied for user '%v'", user) }
[ "func", "(", "a", "*", "AuthServerStatic", ")", "Negotiate", "(", "c", "*", "Conn", ",", "user", "string", ",", "remoteAddr", "net", ".", "Addr", ")", "(", "Getter", ",", "error", ")", "{", "// Finish the negotiation.", "password", ",", "err", ":=", "AuthServerNegotiateClearOrDialog", "(", "c", ",", "a", ".", "Method", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "a", ".", "mu", ".", "Lock", "(", ")", "\n", "entries", ",", "ok", ":=", "a", ".", "Entries", "[", "user", "]", "\n", "a", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "!", "ok", "{", "return", "&", "StaticUserData", "{", "}", ",", "NewSQLError", "(", "ERAccessDeniedError", ",", "SSAccessDeniedError", ",", "\"", "\"", ",", "user", ")", "\n", "}", "\n", "for", "_", ",", "entry", ":=", "range", "entries", "{", "// Validate the password.", "if", "matchSourceHost", "(", "remoteAddr", ",", "entry", ".", "SourceHost", ")", "&&", "entry", ".", "Password", "==", "password", "{", "return", "&", "StaticUserData", "{", "entry", ".", "UserData", ",", "entry", ".", "Groups", "}", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "&", "StaticUserData", "{", "}", ",", "NewSQLError", "(", "ERAccessDeniedError", ",", "SSAccessDeniedError", ",", "\"", "\"", ",", "user", ")", "\n", "}" ]
// Negotiate is part of the AuthServer interface. // It will be called if Method is anything else than MysqlNativePassword. // We only recognize MysqlClearPassword and MysqlDialog here.
[ "Negotiate", "is", "part", "of", "the", "AuthServer", "interface", ".", "It", "will", "be", "called", "if", "Method", "is", "anything", "else", "than", "MysqlNativePassword", ".", "We", "only", "recognize", "MysqlClearPassword", "and", "MysqlDialog", "here", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/auth_server_static.go#L253-L274
train
vitessio/vitess
go/mysql/auth_server_static.go
Get
func (sud *StaticUserData) Get() *querypb.VTGateCallerID { return &querypb.VTGateCallerID{Username: sud.username, Groups: sud.groups} }
go
func (sud *StaticUserData) Get() *querypb.VTGateCallerID { return &querypb.VTGateCallerID{Username: sud.username, Groups: sud.groups} }
[ "func", "(", "sud", "*", "StaticUserData", ")", "Get", "(", ")", "*", "querypb", ".", "VTGateCallerID", "{", "return", "&", "querypb", ".", "VTGateCallerID", "{", "Username", ":", "sud", ".", "username", ",", "Groups", ":", "sud", ".", "groups", "}", "\n", "}" ]
// Get returns the wrapped username and groups
[ "Get", "returns", "the", "wrapped", "username", "and", "groups" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/auth_server_static.go#L297-L299
train
vitessio/vitess
go/vt/vtctld/explorer.go
HandlePath
func (ex *backendExplorer) HandlePath(nodePath string, r *http.Request) *Result { ctx := context.Background() result := &Result{} // Handle toplevel display: global, then one line per cell. if nodePath == "/" { cells, err := ex.ts.GetKnownCells(ctx) if err != nil { result.Error = err.Error() return result } sort.Strings(cells) result.Children = append([]string{topo.GlobalCell}, cells...) return result } // Now find the cell. parts := strings.Split(nodePath, "/") if parts[0] != "" || len(parts) < 2 { result.Error = "Invalid path: " + nodePath return result } cell := parts[1] relativePath := nodePath[len(cell)+1:] conn, err := ex.ts.ConnForCell(ctx, cell) if err != nil { result.Error = fmt.Sprintf("Invalid cell: %v", err) return result } // Get the file contents, if any. data, _, err := conn.Get(ctx, relativePath) switch err { case nil: if len(data) > 0 { // It has contents, we just use it if possible. decoded, err := vtctl.DecodeContent(relativePath, data, false) if err != nil { result.Error = err.Error() } else { result.Data = decoded } // With contents, it can't have children, so we're done. return result } default: // Something is wrong. Might not be a file. result.Error = err.Error() } // Get the children, if any. children, err := conn.ListDir(ctx, relativePath, false /*full*/) if err != nil { // It failed as a directory, let's just return what it did // as a file. return result } // It worked as a directory, clear any file error. result.Error = "" result.Children = topo.DirEntriesToStringArray(children) return result }
go
func (ex *backendExplorer) HandlePath(nodePath string, r *http.Request) *Result { ctx := context.Background() result := &Result{} // Handle toplevel display: global, then one line per cell. if nodePath == "/" { cells, err := ex.ts.GetKnownCells(ctx) if err != nil { result.Error = err.Error() return result } sort.Strings(cells) result.Children = append([]string{topo.GlobalCell}, cells...) return result } // Now find the cell. parts := strings.Split(nodePath, "/") if parts[0] != "" || len(parts) < 2 { result.Error = "Invalid path: " + nodePath return result } cell := parts[1] relativePath := nodePath[len(cell)+1:] conn, err := ex.ts.ConnForCell(ctx, cell) if err != nil { result.Error = fmt.Sprintf("Invalid cell: %v", err) return result } // Get the file contents, if any. data, _, err := conn.Get(ctx, relativePath) switch err { case nil: if len(data) > 0 { // It has contents, we just use it if possible. decoded, err := vtctl.DecodeContent(relativePath, data, false) if err != nil { result.Error = err.Error() } else { result.Data = decoded } // With contents, it can't have children, so we're done. return result } default: // Something is wrong. Might not be a file. result.Error = err.Error() } // Get the children, if any. children, err := conn.ListDir(ctx, relativePath, false /*full*/) if err != nil { // It failed as a directory, let's just return what it did // as a file. return result } // It worked as a directory, clear any file error. result.Error = "" result.Children = topo.DirEntriesToStringArray(children) return result }
[ "func", "(", "ex", "*", "backendExplorer", ")", "HandlePath", "(", "nodePath", "string", ",", "r", "*", "http", ".", "Request", ")", "*", "Result", "{", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "result", ":=", "&", "Result", "{", "}", "\n\n", "// Handle toplevel display: global, then one line per cell.", "if", "nodePath", "==", "\"", "\"", "{", "cells", ",", "err", ":=", "ex", ".", "ts", ".", "GetKnownCells", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Error", "=", "err", ".", "Error", "(", ")", "\n", "return", "result", "\n", "}", "\n", "sort", ".", "Strings", "(", "cells", ")", "\n", "result", ".", "Children", "=", "append", "(", "[", "]", "string", "{", "topo", ".", "GlobalCell", "}", ",", "cells", "...", ")", "\n", "return", "result", "\n", "}", "\n\n", "// Now find the cell.", "parts", ":=", "strings", ".", "Split", "(", "nodePath", ",", "\"", "\"", ")", "\n", "if", "parts", "[", "0", "]", "!=", "\"", "\"", "||", "len", "(", "parts", ")", "<", "2", "{", "result", ".", "Error", "=", "\"", "\"", "+", "nodePath", "\n", "return", "result", "\n", "}", "\n", "cell", ":=", "parts", "[", "1", "]", "\n", "relativePath", ":=", "nodePath", "[", "len", "(", "cell", ")", "+", "1", ":", "]", "\n", "conn", ",", "err", ":=", "ex", ".", "ts", ".", "ConnForCell", "(", "ctx", ",", "cell", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Error", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "result", "\n", "}", "\n\n", "// Get the file contents, if any.", "data", ",", "_", ",", "err", ":=", "conn", ".", "Get", "(", "ctx", ",", "relativePath", ")", "\n", "switch", "err", "{", "case", "nil", ":", "if", "len", "(", "data", ")", ">", "0", "{", "// It has contents, we just use it if possible.", "decoded", ",", "err", ":=", "vtctl", ".", "DecodeContent", "(", "relativePath", ",", "data", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "result", ".", "Error", "=", "err", ".", "Error", "(", ")", "\n", "}", "else", "{", "result", ".", "Data", "=", "decoded", "\n", "}", "\n\n", "// With contents, it can't have children, so we're done.", "return", "result", "\n", "}", "\n", "default", ":", "// Something is wrong. Might not be a file.", "result", ".", "Error", "=", "err", ".", "Error", "(", ")", "\n", "}", "\n\n", "// Get the children, if any.", "children", ",", "err", ":=", "conn", ".", "ListDir", "(", "ctx", ",", "relativePath", ",", "false", "/*full*/", ")", "\n", "if", "err", "!=", "nil", "{", "// It failed as a directory, let's just return what it did", "// as a file.", "return", "result", "\n", "}", "\n\n", "// It worked as a directory, clear any file error.", "result", ".", "Error", "=", "\"", "\"", "\n", "result", ".", "Children", "=", "topo", ".", "DirEntriesToStringArray", "(", "children", ")", "\n", "return", "result", "\n", "}" ]
// HandlePath is the main function for this class.
[ "HandlePath", "is", "the", "main", "function", "for", "this", "class", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtctld/explorer.go#L56-L119
train
vitessio/vitess
go/vt/vtctld/explorer.go
handleExplorerRedirect
func handleExplorerRedirect(ctx context.Context, ts *topo.Server, r *http.Request) (string, error) { keyspace := r.FormValue("keyspace") shard := r.FormValue("shard") cell := r.FormValue("cell") switch r.FormValue("type") { case "keyspace": if keyspace == "" { return "", errors.New("keyspace is required for this redirect") } return appPrefix + "#/keyspaces/", nil case "shard": if keyspace == "" || shard == "" { return "", errors.New("keyspace and shard are required for this redirect") } return appPrefix + fmt.Sprintf("#/shard/%s/%s", keyspace, shard), nil case "srv_keyspace": if keyspace == "" || cell == "" { return "", errors.New("keyspace and cell are required for this redirect") } return appPrefix + "#/keyspaces/", nil case "tablet": alias := r.FormValue("alias") if alias == "" { return "", errors.New("alias is required for this redirect") } tabletAlias, err := topoproto.ParseTabletAlias(alias) if err != nil { return "", fmt.Errorf("bad tablet alias %q: %v", alias, err) } ti, err := ts.GetTablet(ctx, tabletAlias) if err != nil { return "", fmt.Errorf("can't get tablet %q: %v", alias, err) } return appPrefix + fmt.Sprintf("#/shard/%s/%s", ti.Keyspace, ti.Shard), nil case "replication": if keyspace == "" || shard == "" || cell == "" { return "", errors.New("keyspace, shard, and cell are required for this redirect") } return appPrefix + fmt.Sprintf("#/shard/%s/%s", keyspace, shard), nil default: return "", errors.New("bad redirect type") } }
go
func handleExplorerRedirect(ctx context.Context, ts *topo.Server, r *http.Request) (string, error) { keyspace := r.FormValue("keyspace") shard := r.FormValue("shard") cell := r.FormValue("cell") switch r.FormValue("type") { case "keyspace": if keyspace == "" { return "", errors.New("keyspace is required for this redirect") } return appPrefix + "#/keyspaces/", nil case "shard": if keyspace == "" || shard == "" { return "", errors.New("keyspace and shard are required for this redirect") } return appPrefix + fmt.Sprintf("#/shard/%s/%s", keyspace, shard), nil case "srv_keyspace": if keyspace == "" || cell == "" { return "", errors.New("keyspace and cell are required for this redirect") } return appPrefix + "#/keyspaces/", nil case "tablet": alias := r.FormValue("alias") if alias == "" { return "", errors.New("alias is required for this redirect") } tabletAlias, err := topoproto.ParseTabletAlias(alias) if err != nil { return "", fmt.Errorf("bad tablet alias %q: %v", alias, err) } ti, err := ts.GetTablet(ctx, tabletAlias) if err != nil { return "", fmt.Errorf("can't get tablet %q: %v", alias, err) } return appPrefix + fmt.Sprintf("#/shard/%s/%s", ti.Keyspace, ti.Shard), nil case "replication": if keyspace == "" || shard == "" || cell == "" { return "", errors.New("keyspace, shard, and cell are required for this redirect") } return appPrefix + fmt.Sprintf("#/shard/%s/%s", keyspace, shard), nil default: return "", errors.New("bad redirect type") } }
[ "func", "handleExplorerRedirect", "(", "ctx", "context", ".", "Context", ",", "ts", "*", "topo", ".", "Server", ",", "r", "*", "http", ".", "Request", ")", "(", "string", ",", "error", ")", "{", "keyspace", ":=", "r", ".", "FormValue", "(", "\"", "\"", ")", "\n", "shard", ":=", "r", ".", "FormValue", "(", "\"", "\"", ")", "\n", "cell", ":=", "r", ".", "FormValue", "(", "\"", "\"", ")", "\n\n", "switch", "r", ".", "FormValue", "(", "\"", "\"", ")", "{", "case", "\"", "\"", ":", "if", "keyspace", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "appPrefix", "+", "\"", "\"", ",", "nil", "\n", "case", "\"", "\"", ":", "if", "keyspace", "==", "\"", "\"", "||", "shard", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "appPrefix", "+", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "keyspace", ",", "shard", ")", ",", "nil", "\n", "case", "\"", "\"", ":", "if", "keyspace", "==", "\"", "\"", "||", "cell", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "appPrefix", "+", "\"", "\"", ",", "nil", "\n", "case", "\"", "\"", ":", "alias", ":=", "r", ".", "FormValue", "(", "\"", "\"", ")", "\n", "if", "alias", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "tabletAlias", ",", "err", ":=", "topoproto", ".", "ParseTabletAlias", "(", "alias", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "alias", ",", "err", ")", "\n", "}", "\n", "ti", ",", "err", ":=", "ts", ".", "GetTablet", "(", "ctx", ",", "tabletAlias", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "alias", ",", "err", ")", "\n", "}", "\n", "return", "appPrefix", "+", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ti", ".", "Keyspace", ",", "ti", ".", "Shard", ")", ",", "nil", "\n", "case", "\"", "\"", ":", "if", "keyspace", "==", "\"", "\"", "||", "shard", "==", "\"", "\"", "||", "cell", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "appPrefix", "+", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "keyspace", ",", "shard", ")", ",", "nil", "\n", "default", ":", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// handleExplorerRedirect returns the redirect target URL.
[ "handleExplorerRedirect", "returns", "the", "redirect", "target", "URL", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtctld/explorer.go#L122-L165
train
vitessio/vitess
go/vt/vtctld/explorer.go
initExplorer
func initExplorer(ts *topo.Server) { // Main backend explorer functions. be := newBackendExplorer(ts) handleCollection("topodata", func(r *http.Request) (interface{}, error) { return be.HandlePath(path.Clean("/"+getItemPath(r.URL.Path)), r), nil }) // Redirects for explorers. http.HandleFunc("/explorers/redirect", func(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { httpErrorf(w, r, "cannot parse form: %s", err) return } target, err := handleExplorerRedirect(context.Background(), ts, r) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } http.Redirect(w, r, target, http.StatusFound) }) }
go
func initExplorer(ts *topo.Server) { // Main backend explorer functions. be := newBackendExplorer(ts) handleCollection("topodata", func(r *http.Request) (interface{}, error) { return be.HandlePath(path.Clean("/"+getItemPath(r.URL.Path)), r), nil }) // Redirects for explorers. http.HandleFunc("/explorers/redirect", func(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { httpErrorf(w, r, "cannot parse form: %s", err) return } target, err := handleExplorerRedirect(context.Background(), ts, r) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } http.Redirect(w, r, target, http.StatusFound) }) }
[ "func", "initExplorer", "(", "ts", "*", "topo", ".", "Server", ")", "{", "// Main backend explorer functions.", "be", ":=", "newBackendExplorer", "(", "ts", ")", "\n", "handleCollection", "(", "\"", "\"", ",", "func", "(", "r", "*", "http", ".", "Request", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "be", ".", "HandlePath", "(", "path", ".", "Clean", "(", "\"", "\"", "+", "getItemPath", "(", "r", ".", "URL", ".", "Path", ")", ")", ",", "r", ")", ",", "nil", "\n", "}", ")", "\n\n", "// Redirects for explorers.", "http", ".", "HandleFunc", "(", "\"", "\"", ",", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "err", ":=", "r", ".", "ParseForm", "(", ")", ";", "err", "!=", "nil", "{", "httpErrorf", "(", "w", ",", "r", ",", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "target", ",", "err", ":=", "handleExplorerRedirect", "(", "context", ".", "Background", "(", ")", ",", "ts", ",", "r", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "err", ".", "Error", "(", ")", ",", "http", ".", "StatusBadRequest", ")", "\n", "return", "\n", "}", "\n\n", "http", ".", "Redirect", "(", "w", ",", "r", ",", "target", ",", "http", ".", "StatusFound", ")", "\n", "}", ")", "\n", "}" ]
// initExplorer initializes the redirects for explorer
[ "initExplorer", "initializes", "the", "redirects", "for", "explorer" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtctld/explorer.go#L168-L190
train
vitessio/vitess
go/vt/vttablet/tabletserver/planbuilder/dml.go
analyzeOnDupExpressions
func analyzeOnDupExpressions(ins *sqlparser.Insert, pkIndex *schema.Index) (pkValues []sqltypes.PlanValue, ok bool) { rowList := ins.Rows.(sqlparser.Values) for _, expr := range ins.OnDup { index := pkIndex.FindColumn(expr.Name.Name) if index == -1 { continue } if pkValues == nil { pkValues = make([]sqltypes.PlanValue, len(pkIndex.Columns)) } if vf, ok := expr.Expr.(*sqlparser.ValuesFuncExpr); ok { if !vf.Name.Qualifier.IsEmpty() && vf.Name.Qualifier != ins.Table { return nil, false } insertCol := ins.Columns.FindColumn(vf.Name.Name) if insertCol == -1 { return nil, false } pkValues[index], ok = extractColumnValues(rowList, insertCol) if !ok { return nil, false } continue } pkValues[index], ok = extractSingleValue(expr.Expr) if !ok { return nil, false } } return pkValues, true }
go
func analyzeOnDupExpressions(ins *sqlparser.Insert, pkIndex *schema.Index) (pkValues []sqltypes.PlanValue, ok bool) { rowList := ins.Rows.(sqlparser.Values) for _, expr := range ins.OnDup { index := pkIndex.FindColumn(expr.Name.Name) if index == -1 { continue } if pkValues == nil { pkValues = make([]sqltypes.PlanValue, len(pkIndex.Columns)) } if vf, ok := expr.Expr.(*sqlparser.ValuesFuncExpr); ok { if !vf.Name.Qualifier.IsEmpty() && vf.Name.Qualifier != ins.Table { return nil, false } insertCol := ins.Columns.FindColumn(vf.Name.Name) if insertCol == -1 { return nil, false } pkValues[index], ok = extractColumnValues(rowList, insertCol) if !ok { return nil, false } continue } pkValues[index], ok = extractSingleValue(expr.Expr) if !ok { return nil, false } } return pkValues, true }
[ "func", "analyzeOnDupExpressions", "(", "ins", "*", "sqlparser", ".", "Insert", ",", "pkIndex", "*", "schema", ".", "Index", ")", "(", "pkValues", "[", "]", "sqltypes", ".", "PlanValue", ",", "ok", "bool", ")", "{", "rowList", ":=", "ins", ".", "Rows", ".", "(", "sqlparser", ".", "Values", ")", "\n", "for", "_", ",", "expr", ":=", "range", "ins", ".", "OnDup", "{", "index", ":=", "pkIndex", ".", "FindColumn", "(", "expr", ".", "Name", ".", "Name", ")", "\n", "if", "index", "==", "-", "1", "{", "continue", "\n", "}", "\n\n", "if", "pkValues", "==", "nil", "{", "pkValues", "=", "make", "(", "[", "]", "sqltypes", ".", "PlanValue", ",", "len", "(", "pkIndex", ".", "Columns", ")", ")", "\n", "}", "\n", "if", "vf", ",", "ok", ":=", "expr", ".", "Expr", ".", "(", "*", "sqlparser", ".", "ValuesFuncExpr", ")", ";", "ok", "{", "if", "!", "vf", ".", "Name", ".", "Qualifier", ".", "IsEmpty", "(", ")", "&&", "vf", ".", "Name", ".", "Qualifier", "!=", "ins", ".", "Table", "{", "return", "nil", ",", "false", "\n", "}", "\n", "insertCol", ":=", "ins", ".", "Columns", ".", "FindColumn", "(", "vf", ".", "Name", ".", "Name", ")", "\n", "if", "insertCol", "==", "-", "1", "{", "return", "nil", ",", "false", "\n", "}", "\n", "pkValues", "[", "index", "]", ",", "ok", "=", "extractColumnValues", "(", "rowList", ",", "insertCol", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "false", "\n", "}", "\n", "continue", "\n", "}", "\n\n", "pkValues", "[", "index", "]", ",", "ok", "=", "extractSingleValue", "(", "expr", ".", "Expr", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "false", "\n", "}", "\n", "}", "\n", "return", "pkValues", ",", "true", "\n", "}" ]
// analyzeOnDupExpressions analyzes the OnDup and returns the list for any pk value changes.
[ "analyzeOnDupExpressions", "analyzes", "the", "OnDup", "and", "returns", "the", "list", "for", "any", "pk", "value", "changes", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/planbuilder/dml.go#L611-L643
train
vitessio/vitess
go/vt/vttablet/tabletserver/planbuilder/dml.go
extractColumnValues
func extractColumnValues(rowList sqlparser.Values, colnum int) (sqltypes.PlanValue, bool) { pv := sqltypes.PlanValue{Values: make([]sqltypes.PlanValue, len(rowList))} for i := 0; i < len(rowList); i++ { var ok bool pv.Values[i], ok = extractSingleValue(rowList[i][colnum]) if !ok { return pv, false } } return pv, true }
go
func extractColumnValues(rowList sqlparser.Values, colnum int) (sqltypes.PlanValue, bool) { pv := sqltypes.PlanValue{Values: make([]sqltypes.PlanValue, len(rowList))} for i := 0; i < len(rowList); i++ { var ok bool pv.Values[i], ok = extractSingleValue(rowList[i][colnum]) if !ok { return pv, false } } return pv, true }
[ "func", "extractColumnValues", "(", "rowList", "sqlparser", ".", "Values", ",", "colnum", "int", ")", "(", "sqltypes", ".", "PlanValue", ",", "bool", ")", "{", "pv", ":=", "sqltypes", ".", "PlanValue", "{", "Values", ":", "make", "(", "[", "]", "sqltypes", ".", "PlanValue", ",", "len", "(", "rowList", ")", ")", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "rowList", ")", ";", "i", "++", "{", "var", "ok", "bool", "\n", "pv", ".", "Values", "[", "i", "]", ",", "ok", "=", "extractSingleValue", "(", "rowList", "[", "i", "]", "[", "colnum", "]", ")", "\n", "if", "!", "ok", "{", "return", "pv", ",", "false", "\n", "}", "\n", "}", "\n", "return", "pv", ",", "true", "\n", "}" ]
// extractColumnValues extracts the values of a column into a PlanValue.
[ "extractColumnValues", "extracts", "the", "values", "of", "a", "column", "into", "a", "PlanValue", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/planbuilder/dml.go#L646-L656
train
vitessio/vitess
go/vt/vtctl/query.go
printQueryResult
func printQueryResult(writer io.Writer, qr *sqltypes.Result) { table := tablewriter.NewWriter(writer) table.SetAutoFormatHeaders(false) // Make header. header := make([]string, 0, len(qr.Fields)) for _, field := range qr.Fields { header = append(header, field.Name) } table.SetHeader(header) // Add rows. for _, row := range qr.Rows { vals := make([]string, 0, len(row)) for _, val := range row { vals = append(vals, val.ToString()) } table.Append(vals) } // Print table. table.Render() }
go
func printQueryResult(writer io.Writer, qr *sqltypes.Result) { table := tablewriter.NewWriter(writer) table.SetAutoFormatHeaders(false) // Make header. header := make([]string, 0, len(qr.Fields)) for _, field := range qr.Fields { header = append(header, field.Name) } table.SetHeader(header) // Add rows. for _, row := range qr.Rows { vals := make([]string, 0, len(row)) for _, val := range row { vals = append(vals, val.ToString()) } table.Append(vals) } // Print table. table.Render() }
[ "func", "printQueryResult", "(", "writer", "io", ".", "Writer", ",", "qr", "*", "sqltypes", ".", "Result", ")", "{", "table", ":=", "tablewriter", ".", "NewWriter", "(", "writer", ")", "\n", "table", ".", "SetAutoFormatHeaders", "(", "false", ")", "\n\n", "// Make header.", "header", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "qr", ".", "Fields", ")", ")", "\n", "for", "_", ",", "field", ":=", "range", "qr", ".", "Fields", "{", "header", "=", "append", "(", "header", ",", "field", ".", "Name", ")", "\n", "}", "\n", "table", ".", "SetHeader", "(", "header", ")", "\n\n", "// Add rows.", "for", "_", ",", "row", ":=", "range", "qr", ".", "Rows", "{", "vals", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "row", ")", ")", "\n", "for", "_", ",", "val", ":=", "range", "row", "{", "vals", "=", "append", "(", "vals", ",", "val", ".", "ToString", "(", ")", ")", "\n", "}", "\n", "table", ".", "Append", "(", "vals", ")", "\n", "}", "\n\n", "// Print table.", "table", ".", "Render", "(", ")", "\n", "}" ]
// printQueryResult will pretty-print a QueryResult to the logger.
[ "printQueryResult", "will", "pretty", "-", "print", "a", "QueryResult", "to", "the", "logger", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtctl/query.go#L708-L730
train
vitessio/vitess
go/vt/vtgate/gateway/status.go
registerAggregator
func registerAggregator(a *TabletStatusAggregator) { muAggr.Lock() defer muAggr.Unlock() aggregators = append(aggregators, a) }
go
func registerAggregator(a *TabletStatusAggregator) { muAggr.Lock() defer muAggr.Unlock() aggregators = append(aggregators, a) }
[ "func", "registerAggregator", "(", "a", "*", "TabletStatusAggregator", ")", "{", "muAggr", ".", "Lock", "(", ")", "\n", "defer", "muAggr", ".", "Unlock", "(", ")", "\n", "aggregators", "=", "append", "(", "aggregators", ",", "a", ")", "\n", "}" ]
// registerAggregator registers an aggregator to the global list.
[ "registerAggregator", "registers", "an", "aggregator", "to", "the", "global", "list", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/gateway/status.go#L99-L103
train
vitessio/vitess
go/vt/vtgate/gateway/status.go
resetAggregators
func resetAggregators() { ticker := time.NewTicker(time.Second) for range ticker.C { muAggr.Lock() for _, a := range aggregators { a.resetNextSlot() } muAggr.Unlock() } }
go
func resetAggregators() { ticker := time.NewTicker(time.Second) for range ticker.C { muAggr.Lock() for _, a := range aggregators { a.resetNextSlot() } muAggr.Unlock() } }
[ "func", "resetAggregators", "(", ")", "{", "ticker", ":=", "time", ".", "NewTicker", "(", "time", ".", "Second", ")", "\n", "for", "range", "ticker", ".", "C", "{", "muAggr", ".", "Lock", "(", ")", "\n", "for", "_", ",", "a", ":=", "range", "aggregators", "{", "a", ".", "resetNextSlot", "(", ")", "\n", "}", "\n", "muAggr", ".", "Unlock", "(", ")", "\n", "}", "\n", "}" ]
// resetAggregators resets the next stats slot for all aggregators every second.
[ "resetAggregators", "resets", "the", "next", "stats", "slot", "for", "all", "aggregators", "every", "second", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/gateway/status.go#L106-L115
train
vitessio/vitess
go/vt/vtgate/gateway/status.go
NewTabletStatusAggregator
func NewTabletStatusAggregator(keyspace, shard string, tabletType topodatapb.TabletType, name string) *TabletStatusAggregator { tsa := &TabletStatusAggregator{ Keyspace: keyspace, Shard: shard, TabletType: tabletType, Name: name, } registerAggregator(tsa) return tsa }
go
func NewTabletStatusAggregator(keyspace, shard string, tabletType topodatapb.TabletType, name string) *TabletStatusAggregator { tsa := &TabletStatusAggregator{ Keyspace: keyspace, Shard: shard, TabletType: tabletType, Name: name, } registerAggregator(tsa) return tsa }
[ "func", "NewTabletStatusAggregator", "(", "keyspace", ",", "shard", "string", ",", "tabletType", "topodatapb", ".", "TabletType", ",", "name", "string", ")", "*", "TabletStatusAggregator", "{", "tsa", ":=", "&", "TabletStatusAggregator", "{", "Keyspace", ":", "keyspace", ",", "Shard", ":", "shard", ",", "TabletType", ":", "tabletType", ",", "Name", ":", "name", ",", "}", "\n", "registerAggregator", "(", "tsa", ")", "\n", "return", "tsa", "\n", "}" ]
// NewTabletStatusAggregator creates a TabletStatusAggregator.
[ "NewTabletStatusAggregator", "creates", "a", "TabletStatusAggregator", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/gateway/status.go#L180-L189
train
vitessio/vitess
go/vt/vtgate/gateway/status.go
UpdateQueryInfo
func (tsa *TabletStatusAggregator) UpdateQueryInfo(addr string, tabletType topodatapb.TabletType, elapsed time.Duration, hasError bool) { qi := &queryInfo{ aggr: tsa, addr: addr, tabletType: tabletType, elapsed: elapsed, hasError: hasError, } select { case aggrChan <- qi: default: gatewayStatsChanFull.Add(1) } }
go
func (tsa *TabletStatusAggregator) UpdateQueryInfo(addr string, tabletType topodatapb.TabletType, elapsed time.Duration, hasError bool) { qi := &queryInfo{ aggr: tsa, addr: addr, tabletType: tabletType, elapsed: elapsed, hasError: hasError, } select { case aggrChan <- qi: default: gatewayStatsChanFull.Add(1) } }
[ "func", "(", "tsa", "*", "TabletStatusAggregator", ")", "UpdateQueryInfo", "(", "addr", "string", ",", "tabletType", "topodatapb", ".", "TabletType", ",", "elapsed", "time", ".", "Duration", ",", "hasError", "bool", ")", "{", "qi", ":=", "&", "queryInfo", "{", "aggr", ":", "tsa", ",", "addr", ":", "addr", ",", "tabletType", ":", "tabletType", ",", "elapsed", ":", "elapsed", ",", "hasError", ":", "hasError", ",", "}", "\n", "select", "{", "case", "aggrChan", "<-", "qi", ":", "default", ":", "gatewayStatsChanFull", ".", "Add", "(", "1", ")", "\n", "}", "\n", "}" ]
// UpdateQueryInfo updates the aggregator with the given information about a query.
[ "UpdateQueryInfo", "updates", "the", "aggregator", "with", "the", "given", "information", "about", "a", "query", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/gateway/status.go#L192-L205
train
vitessio/vitess
go/vt/vtgate/gateway/status.go
GetCacheStatus
func (tsa *TabletStatusAggregator) GetCacheStatus() *TabletCacheStatus { status := &TabletCacheStatus{ Keyspace: tsa.Keyspace, Shard: tsa.Shard, Name: tsa.Name, } tsa.mu.RLock() defer tsa.mu.RUnlock() status.TabletType = tsa.TabletType status.Addr = tsa.Addr status.QueryCount = tsa.QueryCount status.QueryError = tsa.QueryError var totalQuery uint64 for _, c := range tsa.queryCountInMinute { totalQuery += c } var totalLatency time.Duration for _, d := range tsa.latencyInMinute { totalLatency += d } status.QPS = float64(totalQuery) / 60 if totalQuery > 0 { status.AvgLatency = float64(totalLatency.Nanoseconds()) / float64(totalQuery) / 1000000 } return status }
go
func (tsa *TabletStatusAggregator) GetCacheStatus() *TabletCacheStatus { status := &TabletCacheStatus{ Keyspace: tsa.Keyspace, Shard: tsa.Shard, Name: tsa.Name, } tsa.mu.RLock() defer tsa.mu.RUnlock() status.TabletType = tsa.TabletType status.Addr = tsa.Addr status.QueryCount = tsa.QueryCount status.QueryError = tsa.QueryError var totalQuery uint64 for _, c := range tsa.queryCountInMinute { totalQuery += c } var totalLatency time.Duration for _, d := range tsa.latencyInMinute { totalLatency += d } status.QPS = float64(totalQuery) / 60 if totalQuery > 0 { status.AvgLatency = float64(totalLatency.Nanoseconds()) / float64(totalQuery) / 1000000 } return status }
[ "func", "(", "tsa", "*", "TabletStatusAggregator", ")", "GetCacheStatus", "(", ")", "*", "TabletCacheStatus", "{", "status", ":=", "&", "TabletCacheStatus", "{", "Keyspace", ":", "tsa", ".", "Keyspace", ",", "Shard", ":", "tsa", ".", "Shard", ",", "Name", ":", "tsa", ".", "Name", ",", "}", "\n", "tsa", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "tsa", ".", "mu", ".", "RUnlock", "(", ")", "\n", "status", ".", "TabletType", "=", "tsa", ".", "TabletType", "\n", "status", ".", "Addr", "=", "tsa", ".", "Addr", "\n", "status", ".", "QueryCount", "=", "tsa", ".", "QueryCount", "\n", "status", ".", "QueryError", "=", "tsa", ".", "QueryError", "\n", "var", "totalQuery", "uint64", "\n", "for", "_", ",", "c", ":=", "range", "tsa", ".", "queryCountInMinute", "{", "totalQuery", "+=", "c", "\n", "}", "\n", "var", "totalLatency", "time", ".", "Duration", "\n", "for", "_", ",", "d", ":=", "range", "tsa", ".", "latencyInMinute", "{", "totalLatency", "+=", "d", "\n", "}", "\n", "status", ".", "QPS", "=", "float64", "(", "totalQuery", ")", "/", "60", "\n", "if", "totalQuery", ">", "0", "{", "status", ".", "AvgLatency", "=", "float64", "(", "totalLatency", ".", "Nanoseconds", "(", ")", ")", "/", "float64", "(", "totalQuery", ")", "/", "1000000", "\n", "}", "\n", "return", "status", "\n", "}" ]
// GetCacheStatus returns a TabletCacheStatus representing the current gateway status.
[ "GetCacheStatus", "returns", "a", "TabletCacheStatus", "representing", "the", "current", "gateway", "status", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/gateway/status.go#L234-L259
train
vitessio/vitess
go/vt/vtgate/gateway/status.go
resetNextSlot
func (tsa *TabletStatusAggregator) resetNextSlot() { tsa.mu.Lock() defer tsa.mu.Unlock() tsa.tick = (tsa.tick + 1) % 60 tsa.queryCountInMinute[tsa.tick] = 0 tsa.latencyInMinute[tsa.tick] = time.Duration(0) }
go
func (tsa *TabletStatusAggregator) resetNextSlot() { tsa.mu.Lock() defer tsa.mu.Unlock() tsa.tick = (tsa.tick + 1) % 60 tsa.queryCountInMinute[tsa.tick] = 0 tsa.latencyInMinute[tsa.tick] = time.Duration(0) }
[ "func", "(", "tsa", "*", "TabletStatusAggregator", ")", "resetNextSlot", "(", ")", "{", "tsa", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "tsa", ".", "mu", ".", "Unlock", "(", ")", "\n", "tsa", ".", "tick", "=", "(", "tsa", ".", "tick", "+", "1", ")", "%", "60", "\n", "tsa", ".", "queryCountInMinute", "[", "tsa", ".", "tick", "]", "=", "0", "\n", "tsa", ".", "latencyInMinute", "[", "tsa", ".", "tick", "]", "=", "time", ".", "Duration", "(", "0", ")", "\n", "}" ]
// resetNextSlot resets the next tracking slot.
[ "resetNextSlot", "resets", "the", "next", "tracking", "slot", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/gateway/status.go#L262-L268
train
vitessio/vitess
go/vt/vttablet/endtoend/framework/streamqueryz.go
StreamTerminate
func StreamTerminate(connID int) error { response, err := http.Get(fmt.Sprintf("%s/streamqueryz/terminate?format=json&connID=%d", ServerAddress, connID)) if err != nil { return err } response.Body.Close() return nil }
go
func StreamTerminate(connID int) error { response, err := http.Get(fmt.Sprintf("%s/streamqueryz/terminate?format=json&connID=%d", ServerAddress, connID)) if err != nil { return err } response.Body.Close() return nil }
[ "func", "StreamTerminate", "(", "connID", "int", ")", "error", "{", "response", ",", "err", ":=", "http", ".", "Get", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ServerAddress", ",", "connID", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "response", ".", "Body", ".", "Close", "(", ")", "\n", "return", "nil", "\n", "}" ]
// StreamTerminate terminates the specified streaming query.
[ "StreamTerminate", "terminates", "the", "specified", "streaming", "query", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/endtoend/framework/streamqueryz.go#L51-L58
train
vitessio/vitess
go/vt/key/key.go
ParseKeyspaceIDType
func ParseKeyspaceIDType(param string) (topodatapb.KeyspaceIdType, error) { if param == "" { return topodatapb.KeyspaceIdType_UNSET, nil } value, ok := topodatapb.KeyspaceIdType_value[strings.ToUpper(param)] if !ok { return topodatapb.KeyspaceIdType_UNSET, fmt.Errorf("unknown KeyspaceIdType %v", param) } return topodatapb.KeyspaceIdType(value), nil }
go
func ParseKeyspaceIDType(param string) (topodatapb.KeyspaceIdType, error) { if param == "" { return topodatapb.KeyspaceIdType_UNSET, nil } value, ok := topodatapb.KeyspaceIdType_value[strings.ToUpper(param)] if !ok { return topodatapb.KeyspaceIdType_UNSET, fmt.Errorf("unknown KeyspaceIdType %v", param) } return topodatapb.KeyspaceIdType(value), nil }
[ "func", "ParseKeyspaceIDType", "(", "param", "string", ")", "(", "topodatapb", ".", "KeyspaceIdType", ",", "error", ")", "{", "if", "param", "==", "\"", "\"", "{", "return", "topodatapb", ".", "KeyspaceIdType_UNSET", ",", "nil", "\n", "}", "\n", "value", ",", "ok", ":=", "topodatapb", ".", "KeyspaceIdType_value", "[", "strings", ".", "ToUpper", "(", "param", ")", "]", "\n", "if", "!", "ok", "{", "return", "topodatapb", ".", "KeyspaceIdType_UNSET", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "param", ")", "\n", "}", "\n", "return", "topodatapb", ".", "KeyspaceIdType", "(", "value", ")", ",", "nil", "\n", "}" ]
// // KeyspaceIdType helper methods // // ParseKeyspaceIDType parses the keyspace id type into the enum
[ "KeyspaceIdType", "helper", "methods", "ParseKeyspaceIDType", "parses", "the", "keyspace", "id", "type", "into", "the", "enum" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/key/key.go#L53-L62
train
vitessio/vitess
go/vt/key/key.go
KeyRangeContains
func KeyRangeContains(kr *topodatapb.KeyRange, id []byte) bool { if kr == nil { return true } return bytes.Compare(kr.Start, id) <= 0 && (len(kr.End) == 0 || bytes.Compare(id, kr.End) < 0) }
go
func KeyRangeContains(kr *topodatapb.KeyRange, id []byte) bool { if kr == nil { return true } return bytes.Compare(kr.Start, id) <= 0 && (len(kr.End) == 0 || bytes.Compare(id, kr.End) < 0) }
[ "func", "KeyRangeContains", "(", "kr", "*", "topodatapb", ".", "KeyRange", ",", "id", "[", "]", "byte", ")", "bool", "{", "if", "kr", "==", "nil", "{", "return", "true", "\n", "}", "\n", "return", "bytes", ".", "Compare", "(", "kr", ".", "Start", ",", "id", ")", "<=", "0", "&&", "(", "len", "(", "kr", ".", "End", ")", "==", "0", "||", "bytes", ".", "Compare", "(", "id", ",", "kr", ".", "End", ")", "<", "0", ")", "\n", "}" ]
// KeyRangeContains returns true if the provided id is in the keyrange.
[ "KeyRangeContains", "returns", "true", "if", "the", "provided", "id", "is", "in", "the", "keyrange", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/key/key.go#L123-L129
train