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/vttablet/tabletserver/replication_watcher.go
EventToken
func (rpw *ReplicationWatcher) EventToken() *querypb.EventToken { rpw.mu.Lock() defer rpw.mu.Unlock() return rpw.eventToken }
go
func (rpw *ReplicationWatcher) EventToken() *querypb.EventToken { rpw.mu.Lock() defer rpw.mu.Unlock() return rpw.eventToken }
[ "func", "(", "rpw", "*", "ReplicationWatcher", ")", "EventToken", "(", ")", "*", "querypb", ".", "EventToken", "{", "rpw", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "rpw", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "rpw", ".", "eventToken", "\n", "}" ]
// EventToken returns the current event token.
[ "EventToken", "returns", "the", "current", "event", "token", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/replication_watcher.go#L194-L198
train
vitessio/vitess
go/vt/vttablet/tabletserver/vstreamer/planbuilder.go
fields
func (plan *Plan) fields() []*querypb.Field { fields := make([]*querypb.Field, len(plan.ColExprs)) for i, ce := range plan.ColExprs { fields[i] = &querypb.Field{ Name: ce.Alias.String(), Type: ce.Type, } } return fields }
go
func (plan *Plan) fields() []*querypb.Field { fields := make([]*querypb.Field, len(plan.ColExprs)) for i, ce := range plan.ColExprs { fields[i] = &querypb.Field{ Name: ce.Alias.String(), Type: ce.Type, } } return fields }
[ "func", "(", "plan", "*", "Plan", ")", "fields", "(", ")", "[", "]", "*", "querypb", ".", "Field", "{", "fields", ":=", "make", "(", "[", "]", "*", "querypb", ".", "Field", ",", "len", "(", "plan", ".", "ColExprs", ")", ")", "\n", "for", "i", ",", "ce", ":=", "range", "plan", ".", "ColExprs", "{", "fields", "[", "i", "]", "=", "&", "querypb", ".", "Field", "{", "Name", ":", "ce", ".", "Alias", ".", "String", "(", ")", ",", "Type", ":", "ce", ".", "Type", ",", "}", "\n", "}", "\n", "return", "fields", "\n", "}" ]
// fields returns the fields for the plan.
[ "fields", "returns", "the", "fields", "for", "the", "plan", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/vstreamer/planbuilder.go#L59-L68
train
vitessio/vitess
go/vt/vttablet/tabletserver/vstreamer/planbuilder.go
filter
func (plan *Plan) filter(values []sqltypes.Value) (bool, []sqltypes.Value, error) { result := make([]sqltypes.Value, len(plan.ColExprs)) for i, colExpr := range plan.ColExprs { result[i] = values[colExpr.ColNum] } if plan.Vindex == nil { return true, result, nil } // Filter by Vindex. destinations, err := plan.Vindex.Map(nil, []sqltypes.Value{result[plan.VindexColumn]}) if err != nil { return false, nil, err } if len(destinations) != 1 { return false, nil, fmt.Errorf("mapping row to keyspace id returned an invalid array of destinations: %v", key.DestinationsString(destinations)) } ksid, ok := destinations[0].(key.DestinationKeyspaceID) if !ok || len(ksid) == 0 { return false, nil, fmt.Errorf("could not map %v to a keyspace id, got destination %v", result[plan.VindexColumn], destinations[0]) } if !key.KeyRangeContains(plan.KeyRange, ksid) { return false, nil, nil } return true, result, nil }
go
func (plan *Plan) filter(values []sqltypes.Value) (bool, []sqltypes.Value, error) { result := make([]sqltypes.Value, len(plan.ColExprs)) for i, colExpr := range plan.ColExprs { result[i] = values[colExpr.ColNum] } if plan.Vindex == nil { return true, result, nil } // Filter by Vindex. destinations, err := plan.Vindex.Map(nil, []sqltypes.Value{result[plan.VindexColumn]}) if err != nil { return false, nil, err } if len(destinations) != 1 { return false, nil, fmt.Errorf("mapping row to keyspace id returned an invalid array of destinations: %v", key.DestinationsString(destinations)) } ksid, ok := destinations[0].(key.DestinationKeyspaceID) if !ok || len(ksid) == 0 { return false, nil, fmt.Errorf("could not map %v to a keyspace id, got destination %v", result[plan.VindexColumn], destinations[0]) } if !key.KeyRangeContains(plan.KeyRange, ksid) { return false, nil, nil } return true, result, nil }
[ "func", "(", "plan", "*", "Plan", ")", "filter", "(", "values", "[", "]", "sqltypes", ".", "Value", ")", "(", "bool", ",", "[", "]", "sqltypes", ".", "Value", ",", "error", ")", "{", "result", ":=", "make", "(", "[", "]", "sqltypes", ".", "Value", ",", "len", "(", "plan", ".", "ColExprs", ")", ")", "\n", "for", "i", ",", "colExpr", ":=", "range", "plan", ".", "ColExprs", "{", "result", "[", "i", "]", "=", "values", "[", "colExpr", ".", "ColNum", "]", "\n", "}", "\n", "if", "plan", ".", "Vindex", "==", "nil", "{", "return", "true", ",", "result", ",", "nil", "\n", "}", "\n\n", "// Filter by Vindex.", "destinations", ",", "err", ":=", "plan", ".", "Vindex", ".", "Map", "(", "nil", ",", "[", "]", "sqltypes", ".", "Value", "{", "result", "[", "plan", ".", "VindexColumn", "]", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "destinations", ")", "!=", "1", "{", "return", "false", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "key", ".", "DestinationsString", "(", "destinations", ")", ")", "\n", "}", "\n", "ksid", ",", "ok", ":=", "destinations", "[", "0", "]", ".", "(", "key", ".", "DestinationKeyspaceID", ")", "\n", "if", "!", "ok", "||", "len", "(", "ksid", ")", "==", "0", "{", "return", "false", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "result", "[", "plan", ".", "VindexColumn", "]", ",", "destinations", "[", "0", "]", ")", "\n", "}", "\n", "if", "!", "key", ".", "KeyRangeContains", "(", "plan", ".", "KeyRange", ",", "ksid", ")", "{", "return", "false", ",", "nil", ",", "nil", "\n", "}", "\n", "return", "true", ",", "result", ",", "nil", "\n", "}" ]
// filter filters the row against the plan. It returns false if the row did not match. // If the row matched, it returns the columns to be sent.
[ "filter", "filters", "the", "row", "against", "the", "plan", ".", "It", "returns", "false", "if", "the", "row", "did", "not", "match", ".", "If", "the", "row", "matched", "it", "returns", "the", "columns", "to", "be", "sent", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/vstreamer/planbuilder.go#L72-L97
train
vitessio/vitess
go/sync2/consolidator.go
Create
func (co *Consolidator) Create(query string) (r *Result, created bool) { co.mu.Lock() defer co.mu.Unlock() if r, ok := co.queries[query]; ok { return r, false } r = &Result{consolidator: co, query: query} r.executing.Lock() co.queries[query] = r return r, true }
go
func (co *Consolidator) Create(query string) (r *Result, created bool) { co.mu.Lock() defer co.mu.Unlock() if r, ok := co.queries[query]; ok { return r, false } r = &Result{consolidator: co, query: query} r.executing.Lock() co.queries[query] = r return r, true }
[ "func", "(", "co", "*", "Consolidator", ")", "Create", "(", "query", "string", ")", "(", "r", "*", "Result", ",", "created", "bool", ")", "{", "co", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "co", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "r", ",", "ok", ":=", "co", ".", "queries", "[", "query", "]", ";", "ok", "{", "return", "r", ",", "false", "\n", "}", "\n", "r", "=", "&", "Result", "{", "consolidator", ":", "co", ",", "query", ":", "query", "}", "\n", "r", ".", "executing", ".", "Lock", "(", ")", "\n", "co", ".", "queries", "[", "query", "]", "=", "r", "\n", "return", "r", ",", "true", "\n", "}" ]
// Create adds a query to currently executing queries and acquires a // lock on its Result if it is not already present. If the query is // a duplicate, Create returns false.
[ "Create", "adds", "a", "query", "to", "currently", "executing", "queries", "and", "acquires", "a", "lock", "on", "its", "Result", "if", "it", "is", "not", "already", "present", ".", "If", "the", "query", "is", "a", "duplicate", "Create", "returns", "false", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sync2/consolidator.go#L58-L68
train
vitessio/vitess
go/sync2/consolidator.go
Broadcast
func (rs *Result) Broadcast() { rs.consolidator.mu.Lock() defer rs.consolidator.mu.Unlock() delete(rs.consolidator.queries, rs.query) rs.executing.Unlock() }
go
func (rs *Result) Broadcast() { rs.consolidator.mu.Lock() defer rs.consolidator.mu.Unlock() delete(rs.consolidator.queries, rs.query) rs.executing.Unlock() }
[ "func", "(", "rs", "*", "Result", ")", "Broadcast", "(", ")", "{", "rs", ".", "consolidator", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "rs", ".", "consolidator", ".", "mu", ".", "Unlock", "(", ")", "\n", "delete", "(", "rs", ".", "consolidator", ".", "queries", ",", "rs", ".", "query", ")", "\n", "rs", ".", "executing", ".", "Unlock", "(", ")", "\n", "}" ]
// Broadcast removes the entry from current queries and releases the // lock on its Result. Broadcast should be invoked when original // query completes execution.
[ "Broadcast", "removes", "the", "entry", "from", "current", "queries", "and", "releases", "the", "lock", "on", "its", "Result", ".", "Broadcast", "should", "be", "invoked", "when", "original", "query", "completes", "execution", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sync2/consolidator.go#L73-L78
train
vitessio/vitess
go/sync2/consolidator.go
Wait
func (rs *Result) Wait() { rs.consolidator.Record(rs.query) rs.executing.RLock() }
go
func (rs *Result) Wait() { rs.consolidator.Record(rs.query) rs.executing.RLock() }
[ "func", "(", "rs", "*", "Result", ")", "Wait", "(", ")", "{", "rs", ".", "consolidator", ".", "Record", "(", "rs", ".", "query", ")", "\n", "rs", ".", "executing", ".", "RLock", "(", ")", "\n", "}" ]
// Wait waits for the original query to complete execution. Wait should // be invoked for duplicate queries.
[ "Wait", "waits", "for", "the", "original", "query", "to", "complete", "execution", ".", "Wait", "should", "be", "invoked", "for", "duplicate", "queries", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sync2/consolidator.go#L82-L85
train
vitessio/vitess
go/sync2/consolidator.go
Record
func (cc *ConsolidatorCache) Record(query string) { if v, ok := cc.Get(query); ok { v.(*ccount).add(1) } else { c := ccount(1) cc.Set(query, &c) } }
go
func (cc *ConsolidatorCache) Record(query string) { if v, ok := cc.Get(query); ok { v.(*ccount).add(1) } else { c := ccount(1) cc.Set(query, &c) } }
[ "func", "(", "cc", "*", "ConsolidatorCache", ")", "Record", "(", "query", "string", ")", "{", "if", "v", ",", "ok", ":=", "cc", ".", "Get", "(", "query", ")", ";", "ok", "{", "v", ".", "(", "*", "ccount", ")", ".", "add", "(", "1", ")", "\n", "}", "else", "{", "c", ":=", "ccount", "(", "1", ")", "\n", "cc", ".", "Set", "(", "query", ",", "&", "c", ")", "\n", "}", "\n", "}" ]
// Record increments the count for "query" by 1. // If it's not in the cache yet, it will be added.
[ "Record", "increments", "the", "count", "for", "query", "by", "1", ".", "If", "it", "s", "not", "in", "the", "cache", "yet", "it", "will", "be", "added", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sync2/consolidator.go#L102-L109
train
vitessio/vitess
go/sync2/consolidator.go
Items
func (cc *ConsolidatorCache) Items() []ConsolidatorCacheItem { items := cc.LRUCache.Items() ret := make([]ConsolidatorCacheItem, len(items)) for i, v := range items { ret[i] = ConsolidatorCacheItem{Query: v.Key, Count: v.Value.(*ccount).get()} } return ret }
go
func (cc *ConsolidatorCache) Items() []ConsolidatorCacheItem { items := cc.LRUCache.Items() ret := make([]ConsolidatorCacheItem, len(items)) for i, v := range items { ret[i] = ConsolidatorCacheItem{Query: v.Key, Count: v.Value.(*ccount).get()} } return ret }
[ "func", "(", "cc", "*", "ConsolidatorCache", ")", "Items", "(", ")", "[", "]", "ConsolidatorCacheItem", "{", "items", ":=", "cc", ".", "LRUCache", ".", "Items", "(", ")", "\n", "ret", ":=", "make", "(", "[", "]", "ConsolidatorCacheItem", ",", "len", "(", "items", ")", ")", "\n", "for", "i", ",", "v", ":=", "range", "items", "{", "ret", "[", "i", "]", "=", "ConsolidatorCacheItem", "{", "Query", ":", "v", ".", "Key", ",", "Count", ":", "v", ".", "Value", ".", "(", "*", "ccount", ")", ".", "get", "(", ")", "}", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// Items returns the items in the cache as an array of String, int64 structs
[ "Items", "returns", "the", "items", "in", "the", "cache", "as", "an", "array", "of", "String", "int64", "structs" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sync2/consolidator.go#L118-L125
train
vitessio/vitess
go/vt/vtgate/planbuilder/postprocess.go
pushGroupBy
func (pb *primitiveBuilder) pushGroupBy(sel *sqlparser.Select, grouper groupByHandler) error { if sel.Distinct != "" { // We can be here only if the builder could handle a group by. if err := grouper.MakeDistinct(); err != nil { return err } } if len(sel.GroupBy) == 0 { return nil } if err := pb.st.ResolveSymbols(sel.GroupBy); err != nil { return fmt.Errorf("unsupported: in group by: %v", err) } // We can be here only if the builder could handle a group by. return grouper.SetGroupBy(sel.GroupBy) }
go
func (pb *primitiveBuilder) pushGroupBy(sel *sqlparser.Select, grouper groupByHandler) error { if sel.Distinct != "" { // We can be here only if the builder could handle a group by. if err := grouper.MakeDistinct(); err != nil { return err } } if len(sel.GroupBy) == 0 { return nil } if err := pb.st.ResolveSymbols(sel.GroupBy); err != nil { return fmt.Errorf("unsupported: in group by: %v", err) } // We can be here only if the builder could handle a group by. return grouper.SetGroupBy(sel.GroupBy) }
[ "func", "(", "pb", "*", "primitiveBuilder", ")", "pushGroupBy", "(", "sel", "*", "sqlparser", ".", "Select", ",", "grouper", "groupByHandler", ")", "error", "{", "if", "sel", ".", "Distinct", "!=", "\"", "\"", "{", "// We can be here only if the builder could handle a group by.", "if", "err", ":=", "grouper", ".", "MakeDistinct", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "sel", ".", "GroupBy", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "if", "err", ":=", "pb", ".", "st", ".", "ResolveSymbols", "(", "sel", ".", "GroupBy", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// We can be here only if the builder could handle a group by.", "return", "grouper", ".", "SetGroupBy", "(", "sel", ".", "GroupBy", ")", "\n", "}" ]
// pushGroupBy processes the group by clause. It resolves all symbols, // and ensures that there are no subqueries.
[ "pushGroupBy", "processes", "the", "group", "by", "clause", ".", "It", "resolves", "all", "symbols", "and", "ensures", "that", "there", "are", "no", "subqueries", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/postprocess.go#L42-L59
train
vitessio/vitess
go/vt/vtgate/planbuilder/postprocess.go
pushOrderBy
func (pb *primitiveBuilder) pushOrderBy(orderBy sqlparser.OrderBy) error { if oa, ok := pb.bldr.(*orderedAggregate); ok { return oa.PushOrderBy(pb, orderBy) } switch len(orderBy) { case 0: return nil case 1: // Special handling for ORDER BY NULL. Push it everywhere. if _, ok := orderBy[0].Expr.(*sqlparser.NullVal); ok { pb.bldr.PushOrderByNull() return nil } else if f, ok := orderBy[0].Expr.(*sqlparser.FuncExpr); ok { if f.Name.Lowered() == "rand" { pb.bldr.PushOrderByRand() return nil } } } firstRB, ok := pb.bldr.First().(*route) if !ok { return errors.New("unsupported: cannot order by on a cross-shard subquery") } for _, order := range orderBy { if node, ok := order.Expr.(*sqlparser.SQLVal); ok { // This block handles constructs that use ordinals for 'ORDER BY'. For example: // SELECT a, b, c FROM t1, t2 ORDER BY 1, 2, 3. num, err := ResultFromNumber(pb.st.ResultColumns, node) if err != nil { return err } target := pb.st.ResultColumns[num].column.Origin() if target != firstRB { return errors.New("unsupported: order by spans across shards") } } else { // Analyze column references within the expression to make sure they all // go to the same route. err := sqlparser.Walk(func(node sqlparser.SQLNode) (kontinue bool, err error) { switch node := node.(type) { case *sqlparser.ColName: target, _, err := pb.st.Find(node) if err != nil { return false, err } if target != firstRB { return false, errors.New("unsupported: order by spans across shards") } case *sqlparser.Subquery: return false, errors.New("unsupported: order by has subquery") } return true, nil }, order.Expr) if err != nil { return err } } // There were no errors. We can push the order by to the left-most route. if err := firstRB.PushOrderBy(order); err != nil { return err } } return nil }
go
func (pb *primitiveBuilder) pushOrderBy(orderBy sqlparser.OrderBy) error { if oa, ok := pb.bldr.(*orderedAggregate); ok { return oa.PushOrderBy(pb, orderBy) } switch len(orderBy) { case 0: return nil case 1: // Special handling for ORDER BY NULL. Push it everywhere. if _, ok := orderBy[0].Expr.(*sqlparser.NullVal); ok { pb.bldr.PushOrderByNull() return nil } else if f, ok := orderBy[0].Expr.(*sqlparser.FuncExpr); ok { if f.Name.Lowered() == "rand" { pb.bldr.PushOrderByRand() return nil } } } firstRB, ok := pb.bldr.First().(*route) if !ok { return errors.New("unsupported: cannot order by on a cross-shard subquery") } for _, order := range orderBy { if node, ok := order.Expr.(*sqlparser.SQLVal); ok { // This block handles constructs that use ordinals for 'ORDER BY'. For example: // SELECT a, b, c FROM t1, t2 ORDER BY 1, 2, 3. num, err := ResultFromNumber(pb.st.ResultColumns, node) if err != nil { return err } target := pb.st.ResultColumns[num].column.Origin() if target != firstRB { return errors.New("unsupported: order by spans across shards") } } else { // Analyze column references within the expression to make sure they all // go to the same route. err := sqlparser.Walk(func(node sqlparser.SQLNode) (kontinue bool, err error) { switch node := node.(type) { case *sqlparser.ColName: target, _, err := pb.st.Find(node) if err != nil { return false, err } if target != firstRB { return false, errors.New("unsupported: order by spans across shards") } case *sqlparser.Subquery: return false, errors.New("unsupported: order by has subquery") } return true, nil }, order.Expr) if err != nil { return err } } // There were no errors. We can push the order by to the left-most route. if err := firstRB.PushOrderBy(order); err != nil { return err } } return nil }
[ "func", "(", "pb", "*", "primitiveBuilder", ")", "pushOrderBy", "(", "orderBy", "sqlparser", ".", "OrderBy", ")", "error", "{", "if", "oa", ",", "ok", ":=", "pb", ".", "bldr", ".", "(", "*", "orderedAggregate", ")", ";", "ok", "{", "return", "oa", ".", "PushOrderBy", "(", "pb", ",", "orderBy", ")", "\n", "}", "\n\n", "switch", "len", "(", "orderBy", ")", "{", "case", "0", ":", "return", "nil", "\n", "case", "1", ":", "// Special handling for ORDER BY NULL. Push it everywhere.", "if", "_", ",", "ok", ":=", "orderBy", "[", "0", "]", ".", "Expr", ".", "(", "*", "sqlparser", ".", "NullVal", ")", ";", "ok", "{", "pb", ".", "bldr", ".", "PushOrderByNull", "(", ")", "\n", "return", "nil", "\n", "}", "else", "if", "f", ",", "ok", ":=", "orderBy", "[", "0", "]", ".", "Expr", ".", "(", "*", "sqlparser", ".", "FuncExpr", ")", ";", "ok", "{", "if", "f", ".", "Name", ".", "Lowered", "(", ")", "==", "\"", "\"", "{", "pb", ".", "bldr", ".", "PushOrderByRand", "(", ")", "\n", "return", "nil", "\n", "}", "\n", "}", "\n", "}", "\n\n", "firstRB", ",", "ok", ":=", "pb", ".", "bldr", ".", "First", "(", ")", ".", "(", "*", "route", ")", "\n", "if", "!", "ok", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "for", "_", ",", "order", ":=", "range", "orderBy", "{", "if", "node", ",", "ok", ":=", "order", ".", "Expr", ".", "(", "*", "sqlparser", ".", "SQLVal", ")", ";", "ok", "{", "// This block handles constructs that use ordinals for 'ORDER BY'. For example:", "// SELECT a, b, c FROM t1, t2 ORDER BY 1, 2, 3.", "num", ",", "err", ":=", "ResultFromNumber", "(", "pb", ".", "st", ".", "ResultColumns", ",", "node", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "target", ":=", "pb", ".", "st", ".", "ResultColumns", "[", "num", "]", ".", "column", ".", "Origin", "(", ")", "\n", "if", "target", "!=", "firstRB", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "else", "{", "// Analyze column references within the expression to make sure they all", "// go to the same route.", "err", ":=", "sqlparser", ".", "Walk", "(", "func", "(", "node", "sqlparser", ".", "SQLNode", ")", "(", "kontinue", "bool", ",", "err", "error", ")", "{", "switch", "node", ":=", "node", ".", "(", "type", ")", "{", "case", "*", "sqlparser", ".", "ColName", ":", "target", ",", "_", ",", "err", ":=", "pb", ".", "st", ".", "Find", "(", "node", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "if", "target", "!=", "firstRB", "{", "return", "false", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "case", "*", "sqlparser", ".", "Subquery", ":", "return", "false", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}", ",", "order", ".", "Expr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "// There were no errors. We can push the order by to the left-most route.", "if", "err", ":=", "firstRB", ".", "PushOrderBy", "(", "order", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// pushOrderBy pushes the order by clause to the appropriate route. // In the case of a join, it's only possible to push down if the // order by references columns of the left-most route. Otherwise, the // function returns an unsupported error.
[ "pushOrderBy", "pushes", "the", "order", "by", "clause", "to", "the", "appropriate", "route", ".", "In", "the", "case", "of", "a", "join", "it", "s", "only", "possible", "to", "push", "down", "if", "the", "order", "by", "references", "columns", "of", "the", "left", "-", "most", "route", ".", "Otherwise", "the", "function", "returns", "an", "unsupported", "error", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/postprocess.go#L65-L131
train
vitessio/vitess
go/vt/throttler/memory.go
touchBadRateAge
func (m *memory) touchBadRateAge(now time.Time) { m.nextBadRateAging = now.Add(m.ageBadRateAfter) }
go
func (m *memory) touchBadRateAge(now time.Time) { m.nextBadRateAging = now.Add(m.ageBadRateAfter) }
[ "func", "(", "m", "*", "memory", ")", "touchBadRateAge", "(", "now", "time", ".", "Time", ")", "{", "m", ".", "nextBadRateAging", "=", "now", ".", "Add", "(", "m", ".", "ageBadRateAfter", ")", "\n", "}" ]
// touchBadRateAge records that the bad rate was changed and the aging should be // further delayed.
[ "touchBadRateAge", "records", "that", "the", "bad", "rate", "was", "changed", "and", "the", "aging", "should", "be", "further", "delayed", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/memory.go#L142-L144
train
vitessio/vitess
go/vt/worker/diff_utils.go
RollbackTransaction
func RollbackTransaction(ctx context.Context, ts *topo.Server, tabletAlias *topodatapb.TabletAlias, txID int64) error { shortCtx, cancel := context.WithTimeout(ctx, *remoteActionsTimeout) tablet, err := ts.GetTablet(shortCtx, tabletAlias) cancel() if err != nil { return err } conn, err := tabletconn.GetDialer()(tablet.Tablet, grpcclient.FailFast(false)) if err != nil { return err } return conn.Rollback(ctx, &querypb.Target{ Keyspace: tablet.Tablet.Keyspace, Shard: tablet.Tablet.Shard, TabletType: tablet.Tablet.Type, }, txID) }
go
func RollbackTransaction(ctx context.Context, ts *topo.Server, tabletAlias *topodatapb.TabletAlias, txID int64) error { shortCtx, cancel := context.WithTimeout(ctx, *remoteActionsTimeout) tablet, err := ts.GetTablet(shortCtx, tabletAlias) cancel() if err != nil { return err } conn, err := tabletconn.GetDialer()(tablet.Tablet, grpcclient.FailFast(false)) if err != nil { return err } return conn.Rollback(ctx, &querypb.Target{ Keyspace: tablet.Tablet.Keyspace, Shard: tablet.Tablet.Shard, TabletType: tablet.Tablet.Type, }, txID) }
[ "func", "RollbackTransaction", "(", "ctx", "context", ".", "Context", ",", "ts", "*", "topo", ".", "Server", ",", "tabletAlias", "*", "topodatapb", ".", "TabletAlias", ",", "txID", "int64", ")", "error", "{", "shortCtx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "ctx", ",", "*", "remoteActionsTimeout", ")", "\n", "tablet", ",", "err", ":=", "ts", ".", "GetTablet", "(", "shortCtx", ",", "tabletAlias", ")", "\n", "cancel", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "conn", ",", "err", ":=", "tabletconn", ".", "GetDialer", "(", ")", "(", "tablet", ".", "Tablet", ",", "grpcclient", ".", "FailFast", "(", "false", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "conn", ".", "Rollback", "(", "ctx", ",", "&", "querypb", ".", "Target", "{", "Keyspace", ":", "tablet", ".", "Tablet", ".", "Keyspace", ",", "Shard", ":", "tablet", ".", "Tablet", ".", "Shard", ",", "TabletType", ":", "tablet", ".", "Tablet", ".", "Type", ",", "}", ",", "txID", ")", "\n", "}" ]
// RollbackTransaction rolls back the transaction
[ "RollbackTransaction", "rolls", "back", "the", "transaction" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/diff_utils.go#L132-L150
train
vitessio/vitess
go/vt/worker/diff_utils.go
Recv
func (f *v3KeyRangeFilter) Recv() (*sqltypes.Result, error) { r, err := f.input.Recv() if err != nil { return nil, err } rows := make([][]sqltypes.Value, 0, len(r.Rows)) for _, row := range r.Rows { ksid, err := f.resolver.keyspaceID(row) if err != nil { return nil, err } if key.KeyRangeContains(f.keyRange, ksid) { rows = append(rows, row) } } r.Rows = rows return r, nil }
go
func (f *v3KeyRangeFilter) Recv() (*sqltypes.Result, error) { r, err := f.input.Recv() if err != nil { return nil, err } rows := make([][]sqltypes.Value, 0, len(r.Rows)) for _, row := range r.Rows { ksid, err := f.resolver.keyspaceID(row) if err != nil { return nil, err } if key.KeyRangeContains(f.keyRange, ksid) { rows = append(rows, row) } } r.Rows = rows return r, nil }
[ "func", "(", "f", "*", "v3KeyRangeFilter", ")", "Recv", "(", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "r", ",", "err", ":=", "f", ".", "input", ".", "Recv", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "rows", ":=", "make", "(", "[", "]", "[", "]", "sqltypes", ".", "Value", ",", "0", ",", "len", "(", "r", ".", "Rows", ")", ")", "\n", "for", "_", ",", "row", ":=", "range", "r", ".", "Rows", "{", "ksid", ",", "err", ":=", "f", ".", "resolver", ".", "keyspaceID", "(", "row", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "key", ".", "KeyRangeContains", "(", "f", ".", "keyRange", ",", "ksid", ")", "{", "rows", "=", "append", "(", "rows", ",", "row", ")", "\n", "}", "\n", "}", "\n", "r", ".", "Rows", "=", "rows", "\n", "return", "r", ",", "nil", "\n", "}" ]
// Recv is part of sqltypes.ResultStream interface.
[ "Recv", "is", "part", "of", "sqltypes", ".", "ResultStream", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/diff_utils.go#L176-L195
train
vitessio/vitess
go/vt/worker/diff_utils.go
uint64FromKeyspaceID
func uint64FromKeyspaceID(keyspaceID []byte) uint64 { // Copy into 8 bytes because keyspaceID could be shorter. bits := make([]byte, 8) copy(bits, keyspaceID) return binary.BigEndian.Uint64(bits) }
go
func uint64FromKeyspaceID(keyspaceID []byte) uint64 { // Copy into 8 bytes because keyspaceID could be shorter. bits := make([]byte, 8) copy(bits, keyspaceID) return binary.BigEndian.Uint64(bits) }
[ "func", "uint64FromKeyspaceID", "(", "keyspaceID", "[", "]", "byte", ")", "uint64", "{", "// Copy into 8 bytes because keyspaceID could be shorter.", "bits", ":=", "make", "(", "[", "]", "byte", ",", "8", ")", "\n", "copy", "(", "bits", ",", "keyspaceID", ")", "\n", "return", "binary", ".", "BigEndian", ".", "Uint64", "(", "bits", ")", "\n", "}" ]
// uint64FromKeyspaceID returns the 64 bit number representation // of the keyspaceID.
[ "uint64FromKeyspaceID", "returns", "the", "64", "bit", "number", "representation", "of", "the", "keyspaceID", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/diff_utils.go#L243-L248
train
vitessio/vitess
go/vt/worker/diff_utils.go
TableScan
func TableScan(ctx context.Context, log logutil.Logger, ts *topo.Server, tabletAlias *topodatapb.TabletAlias, td *tabletmanagerdatapb.TableDefinition) (*QueryResultReader, error) { sql := fmt.Sprintf("SELECT %v FROM %v", strings.Join(escapeAll(orderedColumns(td)), ", "), sqlescape.EscapeID(td.Name)) if len(td.PrimaryKeyColumns) > 0 { sql += fmt.Sprintf(" ORDER BY %v", strings.Join(escapeAll(td.PrimaryKeyColumns), ", ")) } log.Infof("SQL query for %v/%v: %v", topoproto.TabletAliasString(tabletAlias), td.Name, sql) return NewQueryResultReaderForTablet(ctx, ts, tabletAlias, sql) }
go
func TableScan(ctx context.Context, log logutil.Logger, ts *topo.Server, tabletAlias *topodatapb.TabletAlias, td *tabletmanagerdatapb.TableDefinition) (*QueryResultReader, error) { sql := fmt.Sprintf("SELECT %v FROM %v", strings.Join(escapeAll(orderedColumns(td)), ", "), sqlescape.EscapeID(td.Name)) if len(td.PrimaryKeyColumns) > 0 { sql += fmt.Sprintf(" ORDER BY %v", strings.Join(escapeAll(td.PrimaryKeyColumns), ", ")) } log.Infof("SQL query for %v/%v: %v", topoproto.TabletAliasString(tabletAlias), td.Name, sql) return NewQueryResultReaderForTablet(ctx, ts, tabletAlias, sql) }
[ "func", "TableScan", "(", "ctx", "context", ".", "Context", ",", "log", "logutil", ".", "Logger", ",", "ts", "*", "topo", ".", "Server", ",", "tabletAlias", "*", "topodatapb", ".", "TabletAlias", ",", "td", "*", "tabletmanagerdatapb", ".", "TableDefinition", ")", "(", "*", "QueryResultReader", ",", "error", ")", "{", "sql", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "escapeAll", "(", "orderedColumns", "(", "td", ")", ")", ",", "\"", "\"", ")", ",", "sqlescape", ".", "EscapeID", "(", "td", ".", "Name", ")", ")", "\n", "if", "len", "(", "td", ".", "PrimaryKeyColumns", ")", ">", "0", "{", "sql", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "escapeAll", "(", "td", ".", "PrimaryKeyColumns", ")", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "topoproto", ".", "TabletAliasString", "(", "tabletAlias", ")", ",", "td", ".", "Name", ",", "sql", ")", "\n", "return", "NewQueryResultReaderForTablet", "(", "ctx", ",", "ts", ",", "tabletAlias", ",", "sql", ")", "\n", "}" ]
// TableScan returns a QueryResultReader that gets all the rows from a // table, ordered by Primary Key. The returned columns are ordered // with the Primary Key columns in front.
[ "TableScan", "returns", "a", "QueryResultReader", "that", "gets", "all", "the", "rows", "from", "a", "table", "ordered", "by", "Primary", "Key", ".", "The", "returned", "columns", "are", "ordered", "with", "the", "Primary", "Key", "columns", "in", "front", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/diff_utils.go#L253-L260
train
vitessio/vitess
go/vt/worker/diff_utils.go
CreateTargetFrom
func CreateTargetFrom(tablet *topodatapb.Tablet) *query.Target { return &query.Target{ Cell: tablet.Alias.Cell, Keyspace: tablet.Keyspace, Shard: tablet.Shard, TabletType: tablet.Type, } }
go
func CreateTargetFrom(tablet *topodatapb.Tablet) *query.Target { return &query.Target{ Cell: tablet.Alias.Cell, Keyspace: tablet.Keyspace, Shard: tablet.Shard, TabletType: tablet.Type, } }
[ "func", "CreateTargetFrom", "(", "tablet", "*", "topodatapb", ".", "Tablet", ")", "*", "query", ".", "Target", "{", "return", "&", "query", ".", "Target", "{", "Cell", ":", "tablet", ".", "Alias", ".", "Cell", ",", "Keyspace", ":", "tablet", ".", "Keyspace", ",", "Shard", ":", "tablet", ".", "Shard", ",", "TabletType", ":", "tablet", ".", "Type", ",", "}", "\n", "}" ]
// CreateTargetFrom is a helper function
[ "CreateTargetFrom", "is", "a", "helper", "function" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/diff_utils.go#L273-L280
train
vitessio/vitess
go/vt/worker/diff_utils.go
Drain
func (rr *RowReader) Drain() (int, error) { count := 0 for { row, err := rr.Next() if err != nil { return 0, err } if row == nil { return count, nil } count++ } }
go
func (rr *RowReader) Drain() (int, error) { count := 0 for { row, err := rr.Next() if err != nil { return 0, err } if row == nil { return count, nil } count++ } }
[ "func", "(", "rr", "*", "RowReader", ")", "Drain", "(", ")", "(", "int", ",", "error", ")", "{", "count", ":=", "0", "\n", "for", "{", "row", ",", "err", ":=", "rr", ".", "Next", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "if", "row", "==", "nil", "{", "return", "count", ",", "nil", "\n", "}", "\n", "count", "++", "\n", "}", "\n", "}" ]
// Drain will empty the RowReader and return how many rows we got
[ "Drain", "will", "empty", "the", "RowReader", "and", "return", "how", "many", "rows", "we", "got" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/diff_utils.go#L407-L419
train
vitessio/vitess
go/vt/worker/diff_utils.go
HasDifferences
func (dr *DiffReport) HasDifferences() bool { return dr.mismatchedRows > 0 || dr.extraRowsLeft > 0 || dr.extraRowsRight > 0 }
go
func (dr *DiffReport) HasDifferences() bool { return dr.mismatchedRows > 0 || dr.extraRowsLeft > 0 || dr.extraRowsRight > 0 }
[ "func", "(", "dr", "*", "DiffReport", ")", "HasDifferences", "(", ")", "bool", "{", "return", "dr", ".", "mismatchedRows", ">", "0", "||", "dr", ".", "extraRowsLeft", ">", "0", "||", "dr", ".", "extraRowsRight", ">", "0", "\n", "}" ]
// HasDifferences returns true if the diff job recorded any difference
[ "HasDifferences", "returns", "true", "if", "the", "diff", "job", "recorded", "any", "difference" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/diff_utils.go#L448-L450
train
vitessio/vitess
go/vt/worker/diff_utils.go
ComputeQPS
func (dr *DiffReport) ComputeQPS() { if dr.processedRows > 0 { dr.processingQPS = int(time.Duration(dr.processedRows) * time.Second / time.Since(dr.startingTime)) } }
go
func (dr *DiffReport) ComputeQPS() { if dr.processedRows > 0 { dr.processingQPS = int(time.Duration(dr.processedRows) * time.Second / time.Since(dr.startingTime)) } }
[ "func", "(", "dr", "*", "DiffReport", ")", "ComputeQPS", "(", ")", "{", "if", "dr", ".", "processedRows", ">", "0", "{", "dr", ".", "processingQPS", "=", "int", "(", "time", ".", "Duration", "(", "dr", ".", "processedRows", ")", "*", "time", ".", "Second", "/", "time", ".", "Since", "(", "dr", ".", "startingTime", ")", ")", "\n", "}", "\n", "}" ]
// ComputeQPS fills in processingQPS
[ "ComputeQPS", "fills", "in", "processingQPS" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/diff_utils.go#L453-L457
train
vitessio/vitess
go/vt/worker/diff_utils.go
RowsEqual
func RowsEqual(left, right []sqltypes.Value) int { for i, l := range left { if !bytes.Equal(l.Raw(), right[i].Raw()) { return i } } return -1 }
go
func RowsEqual(left, right []sqltypes.Value) int { for i, l := range left { if !bytes.Equal(l.Raw(), right[i].Raw()) { return i } } return -1 }
[ "func", "RowsEqual", "(", "left", ",", "right", "[", "]", "sqltypes", ".", "Value", ")", "int", "{", "for", "i", ",", "l", ":=", "range", "left", "{", "if", "!", "bytes", ".", "Equal", "(", "l", ".", "Raw", "(", ")", ",", "right", "[", "i", "]", ".", "Raw", "(", ")", ")", "{", "return", "i", "\n", "}", "\n", "}", "\n", "return", "-", "1", "\n", "}" ]
// RowsEqual returns the index of the first different column, or -1 if // both rows are the same.
[ "RowsEqual", "returns", "the", "index", "of", "the", "first", "different", "column", "or", "-", "1", "if", "both", "rows", "are", "the", "same", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/diff_utils.go#L465-L472
train
vitessio/vitess
go/vt/worker/diff_utils.go
NewRowDiffer
func NewRowDiffer(left, right ResultReader, tableDefinition *tabletmanagerdatapb.TableDefinition) (*RowDiffer, error) { leftFields := left.Fields() rightFields := right.Fields() if len(leftFields) != len(rightFields) { return nil, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "[table=%v] Cannot diff inputs with different types", tableDefinition.Name) } for i, field := range leftFields { if field.Type != rightFields[i].Type { return nil, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "[table=%v] Cannot diff inputs with different types: field %v types are %v and %v", tableDefinition.Name, i, field.Type, rightFields[i].Type) } } return &RowDiffer{ left: NewRowReader(left), right: NewRowReader(right), tableDefinition: tableDefinition, }, nil }
go
func NewRowDiffer(left, right ResultReader, tableDefinition *tabletmanagerdatapb.TableDefinition) (*RowDiffer, error) { leftFields := left.Fields() rightFields := right.Fields() if len(leftFields) != len(rightFields) { return nil, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "[table=%v] Cannot diff inputs with different types", tableDefinition.Name) } for i, field := range leftFields { if field.Type != rightFields[i].Type { return nil, vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "[table=%v] Cannot diff inputs with different types: field %v types are %v and %v", tableDefinition.Name, i, field.Type, rightFields[i].Type) } } return &RowDiffer{ left: NewRowReader(left), right: NewRowReader(right), tableDefinition: tableDefinition, }, nil }
[ "func", "NewRowDiffer", "(", "left", ",", "right", "ResultReader", ",", "tableDefinition", "*", "tabletmanagerdatapb", ".", "TableDefinition", ")", "(", "*", "RowDiffer", ",", "error", ")", "{", "leftFields", ":=", "left", ".", "Fields", "(", ")", "\n", "rightFields", ":=", "right", ".", "Fields", "(", ")", "\n", "if", "len", "(", "leftFields", ")", "!=", "len", "(", "rightFields", ")", "{", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpc", ".", "Code_FAILED_PRECONDITION", ",", "\"", "\"", ",", "tableDefinition", ".", "Name", ")", "\n", "}", "\n", "for", "i", ",", "field", ":=", "range", "leftFields", "{", "if", "field", ".", "Type", "!=", "rightFields", "[", "i", "]", ".", "Type", "{", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpc", ".", "Code_FAILED_PRECONDITION", ",", "\"", "\"", ",", "tableDefinition", ".", "Name", ",", "i", ",", "field", ".", "Type", ",", "rightFields", "[", "i", "]", ".", "Type", ")", "\n", "}", "\n", "}", "\n", "return", "&", "RowDiffer", "{", "left", ":", "NewRowReader", "(", "left", ")", ",", "right", ":", "NewRowReader", "(", "right", ")", ",", "tableDefinition", ":", "tableDefinition", ",", "}", ",", "nil", "\n", "}" ]
// NewRowDiffer returns a new RowDiffer
[ "NewRowDiffer", "returns", "a", "new", "RowDiffer" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/diff_utils.go#L527-L543
train
vitessio/vitess
go/vt/worker/diff_utils.go
createTransactions
func createTransactions(ctx context.Context, numberOfScanners int, wr *wrangler.Wrangler, cleaner *wrangler.Cleaner, queryService queryservice.QueryService, target *query.Target, tabletInfo *topodatapb.Tablet) ([]int64, error) { scanners := make([]int64, numberOfScanners) for i := 0; i < numberOfScanners; i++ { tx, err := queryService.Begin(ctx, target, &query.ExecuteOptions{ // Make sure our tx is not killed by tx sniper Workload: query.ExecuteOptions_DBA, TransactionIsolation: query.ExecuteOptions_CONSISTENT_SNAPSHOT_READ_ONLY, }) if err != nil { return nil, vterrors.Wrapf(err, "could not open transaction on %v", topoproto.TabletAliasString(tabletInfo.Alias)) } // Remember to rollback the transactions cleaner.Record("CloseTransaction", topoproto.TabletAliasString(tabletInfo.Alias), func(ctx context.Context, wr *wrangler.Wrangler) error { queryService, err := tabletconn.GetDialer()(tabletInfo, true) if err != nil { return err } return queryService.Rollback(ctx, target, tx) }) scanners[i] = tx } return scanners, nil }
go
func createTransactions(ctx context.Context, numberOfScanners int, wr *wrangler.Wrangler, cleaner *wrangler.Cleaner, queryService queryservice.QueryService, target *query.Target, tabletInfo *topodatapb.Tablet) ([]int64, error) { scanners := make([]int64, numberOfScanners) for i := 0; i < numberOfScanners; i++ { tx, err := queryService.Begin(ctx, target, &query.ExecuteOptions{ // Make sure our tx is not killed by tx sniper Workload: query.ExecuteOptions_DBA, TransactionIsolation: query.ExecuteOptions_CONSISTENT_SNAPSHOT_READ_ONLY, }) if err != nil { return nil, vterrors.Wrapf(err, "could not open transaction on %v", topoproto.TabletAliasString(tabletInfo.Alias)) } // Remember to rollback the transactions cleaner.Record("CloseTransaction", topoproto.TabletAliasString(tabletInfo.Alias), func(ctx context.Context, wr *wrangler.Wrangler) error { queryService, err := tabletconn.GetDialer()(tabletInfo, true) if err != nil { return err } return queryService.Rollback(ctx, target, tx) }) scanners[i] = tx } return scanners, nil }
[ "func", "createTransactions", "(", "ctx", "context", ".", "Context", ",", "numberOfScanners", "int", ",", "wr", "*", "wrangler", ".", "Wrangler", ",", "cleaner", "*", "wrangler", ".", "Cleaner", ",", "queryService", "queryservice", ".", "QueryService", ",", "target", "*", "query", ".", "Target", ",", "tabletInfo", "*", "topodatapb", ".", "Tablet", ")", "(", "[", "]", "int64", ",", "error", ")", "{", "scanners", ":=", "make", "(", "[", "]", "int64", ",", "numberOfScanners", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "numberOfScanners", ";", "i", "++", "{", "tx", ",", "err", ":=", "queryService", ".", "Begin", "(", "ctx", ",", "target", ",", "&", "query", ".", "ExecuteOptions", "{", "// Make sure our tx is not killed by tx sniper", "Workload", ":", "query", ".", "ExecuteOptions_DBA", ",", "TransactionIsolation", ":", "query", ".", "ExecuteOptions_CONSISTENT_SNAPSHOT_READ_ONLY", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "topoproto", ".", "TabletAliasString", "(", "tabletInfo", ".", "Alias", ")", ")", "\n", "}", "\n\n", "// Remember to rollback the transactions", "cleaner", ".", "Record", "(", "\"", "\"", ",", "topoproto", ".", "TabletAliasString", "(", "tabletInfo", ".", "Alias", ")", ",", "func", "(", "ctx", "context", ".", "Context", ",", "wr", "*", "wrangler", ".", "Wrangler", ")", "error", "{", "queryService", ",", "err", ":=", "tabletconn", ".", "GetDialer", "(", ")", "(", "tabletInfo", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "queryService", ".", "Rollback", "(", "ctx", ",", "target", ",", "tx", ")", "\n", "}", ")", "\n\n", "scanners", "[", "i", "]", "=", "tx", "\n", "}", "\n\n", "return", "scanners", ",", "nil", "\n", "}" ]
// createTransactions returns an array of transactions that all share the same view of the data. // It will check that no new transactions have been seen between the creation of the underlying transactions, // to guarantee that all TransactionalTableScanner are pointing to the same point
[ "createTransactions", "returns", "an", "array", "of", "transactions", "that", "all", "share", "the", "same", "view", "of", "the", "data", ".", "It", "will", "check", "that", "no", "new", "transactions", "have", "been", "seen", "between", "the", "creation", "of", "the", "underlying", "transactions", "to", "guarantee", "that", "all", "TransactionalTableScanner", "are", "pointing", "to", "the", "same", "point" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/diff_utils.go#L657-L683
train
vitessio/vitess
go/vt/worker/diff_utils.go
CreateConsistentTableScanners
func CreateConsistentTableScanners(ctx context.Context, tablet *topo.TabletInfo, wr *wrangler.Wrangler, cleaner *wrangler.Cleaner, numberOfScanners int) ([]TableScanner, string, error) { txs, gtid, err := CreateConsistentTransactions(ctx, tablet, wr, cleaner, numberOfScanners) if err != nil { return nil, "", err } queryService, _ := tabletconn.GetDialer()(tablet.Tablet, true) defer queryService.Close(ctx) scanners := make([]TableScanner, numberOfScanners) for i, tx := range txs { scanners[i] = TransactionalTableScanner{ wr: wr, cleaner: cleaner, tabletAlias: tablet.Alias, queryService: queryService, tx: tx, } } return scanners, gtid, nil }
go
func CreateConsistentTableScanners(ctx context.Context, tablet *topo.TabletInfo, wr *wrangler.Wrangler, cleaner *wrangler.Cleaner, numberOfScanners int) ([]TableScanner, string, error) { txs, gtid, err := CreateConsistentTransactions(ctx, tablet, wr, cleaner, numberOfScanners) if err != nil { return nil, "", err } queryService, _ := tabletconn.GetDialer()(tablet.Tablet, true) defer queryService.Close(ctx) scanners := make([]TableScanner, numberOfScanners) for i, tx := range txs { scanners[i] = TransactionalTableScanner{ wr: wr, cleaner: cleaner, tabletAlias: tablet.Alias, queryService: queryService, tx: tx, } } return scanners, gtid, nil }
[ "func", "CreateConsistentTableScanners", "(", "ctx", "context", ".", "Context", ",", "tablet", "*", "topo", ".", "TabletInfo", ",", "wr", "*", "wrangler", ".", "Wrangler", ",", "cleaner", "*", "wrangler", ".", "Cleaner", ",", "numberOfScanners", "int", ")", "(", "[", "]", "TableScanner", ",", "string", ",", "error", ")", "{", "txs", ",", "gtid", ",", "err", ":=", "CreateConsistentTransactions", "(", "ctx", ",", "tablet", ",", "wr", ",", "cleaner", ",", "numberOfScanners", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "err", "\n", "}", "\n\n", "queryService", ",", "_", ":=", "tabletconn", ".", "GetDialer", "(", ")", "(", "tablet", ".", "Tablet", ",", "true", ")", "\n", "defer", "queryService", ".", "Close", "(", "ctx", ")", "\n\n", "scanners", ":=", "make", "(", "[", "]", "TableScanner", ",", "numberOfScanners", ")", "\n", "for", "i", ",", "tx", ":=", "range", "txs", "{", "scanners", "[", "i", "]", "=", "TransactionalTableScanner", "{", "wr", ":", "wr", ",", "cleaner", ":", "cleaner", ",", "tabletAlias", ":", "tablet", ".", "Alias", ",", "queryService", ":", "queryService", ",", "tx", ":", "tx", ",", "}", "\n", "}", "\n\n", "return", "scanners", ",", "gtid", ",", "nil", "\n", "}" ]
// CreateConsistentTableScanners will momentarily stop updates on the tablet, and then create connections that are all // consistent snapshots of the same point in the transaction history
[ "CreateConsistentTableScanners", "will", "momentarily", "stop", "updates", "on", "the", "tablet", "and", "then", "create", "connections", "that", "are", "all", "consistent", "snapshots", "of", "the", "same", "point", "in", "the", "transaction", "history" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/diff_utils.go#L720-L741
train
vitessio/vitess
go/vt/worker/diff_utils.go
CreateConsistentTransactions
func CreateConsistentTransactions(ctx context.Context, tablet *topo.TabletInfo, wr *wrangler.Wrangler, cleaner *wrangler.Cleaner, numberOfScanners int) ([]int64, string, error) { if numberOfScanners < 1 { return nil, "", vterrors.Errorf(vtrpc.Code_INVALID_ARGUMENT, "need more than zero scanners: %d", numberOfScanners) } tm := tmclient.NewTabletManagerClient() defer tm.Close() // Lock all tables with a read lock to pause replication err := tm.LockTables(ctx, tablet.Tablet) if err != nil { return nil, "", vterrors.Wrapf(err, "could not lock tables on %v", topoproto.TabletAliasString(tablet.Tablet.Alias)) } defer func() { tm := tmclient.NewTabletManagerClient() defer tm.Close() tm.UnlockTables(ctx, tablet.Tablet) wr.Logger().Infof("tables unlocked on %v", topoproto.TabletAliasString(tablet.Tablet.Alias)) }() wr.Logger().Infof("tables locked on %v", topoproto.TabletAliasString(tablet.Tablet.Alias)) target := CreateTargetFrom(tablet.Tablet) // Create transactions queryService, _ := tabletconn.GetDialer()(tablet.Tablet, true) defer queryService.Close(ctx) connections, err := createTransactions(ctx, numberOfScanners, wr, cleaner, queryService, target, tablet.Tablet) if err != nil { return nil, "", vterrors.Wrapf(err, "failed to create transactions on %v", topoproto.TabletAliasString(tablet.Tablet.Alias)) } wr.Logger().Infof("transactions created on %v", topoproto.TabletAliasString(tablet.Tablet.Alias)) executedGtid, err := tm.MasterPosition(ctx, tablet.Tablet) if err != nil { return nil, "", vterrors.Wrapf(err, "could not read executed GTID set on %v", topoproto.TabletAliasString(tablet.Tablet.Alias)) } return connections, executedGtid, nil }
go
func CreateConsistentTransactions(ctx context.Context, tablet *topo.TabletInfo, wr *wrangler.Wrangler, cleaner *wrangler.Cleaner, numberOfScanners int) ([]int64, string, error) { if numberOfScanners < 1 { return nil, "", vterrors.Errorf(vtrpc.Code_INVALID_ARGUMENT, "need more than zero scanners: %d", numberOfScanners) } tm := tmclient.NewTabletManagerClient() defer tm.Close() // Lock all tables with a read lock to pause replication err := tm.LockTables(ctx, tablet.Tablet) if err != nil { return nil, "", vterrors.Wrapf(err, "could not lock tables on %v", topoproto.TabletAliasString(tablet.Tablet.Alias)) } defer func() { tm := tmclient.NewTabletManagerClient() defer tm.Close() tm.UnlockTables(ctx, tablet.Tablet) wr.Logger().Infof("tables unlocked on %v", topoproto.TabletAliasString(tablet.Tablet.Alias)) }() wr.Logger().Infof("tables locked on %v", topoproto.TabletAliasString(tablet.Tablet.Alias)) target := CreateTargetFrom(tablet.Tablet) // Create transactions queryService, _ := tabletconn.GetDialer()(tablet.Tablet, true) defer queryService.Close(ctx) connections, err := createTransactions(ctx, numberOfScanners, wr, cleaner, queryService, target, tablet.Tablet) if err != nil { return nil, "", vterrors.Wrapf(err, "failed to create transactions on %v", topoproto.TabletAliasString(tablet.Tablet.Alias)) } wr.Logger().Infof("transactions created on %v", topoproto.TabletAliasString(tablet.Tablet.Alias)) executedGtid, err := tm.MasterPosition(ctx, tablet.Tablet) if err != nil { return nil, "", vterrors.Wrapf(err, "could not read executed GTID set on %v", topoproto.TabletAliasString(tablet.Tablet.Alias)) } return connections, executedGtid, nil }
[ "func", "CreateConsistentTransactions", "(", "ctx", "context", ".", "Context", ",", "tablet", "*", "topo", ".", "TabletInfo", ",", "wr", "*", "wrangler", ".", "Wrangler", ",", "cleaner", "*", "wrangler", ".", "Cleaner", ",", "numberOfScanners", "int", ")", "(", "[", "]", "int64", ",", "string", ",", "error", ")", "{", "if", "numberOfScanners", "<", "1", "{", "return", "nil", ",", "\"", "\"", ",", "vterrors", ".", "Errorf", "(", "vtrpc", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "numberOfScanners", ")", "\n", "}", "\n\n", "tm", ":=", "tmclient", ".", "NewTabletManagerClient", "(", ")", "\n", "defer", "tm", ".", "Close", "(", ")", "\n\n", "// Lock all tables with a read lock to pause replication", "err", ":=", "tm", ".", "LockTables", "(", "ctx", ",", "tablet", ".", "Tablet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "topoproto", ".", "TabletAliasString", "(", "tablet", ".", "Tablet", ".", "Alias", ")", ")", "\n", "}", "\n", "defer", "func", "(", ")", "{", "tm", ":=", "tmclient", ".", "NewTabletManagerClient", "(", ")", "\n", "defer", "tm", ".", "Close", "(", ")", "\n", "tm", ".", "UnlockTables", "(", "ctx", ",", "tablet", ".", "Tablet", ")", "\n", "wr", ".", "Logger", "(", ")", ".", "Infof", "(", "\"", "\"", ",", "topoproto", ".", "TabletAliasString", "(", "tablet", ".", "Tablet", ".", "Alias", ")", ")", "\n", "}", "(", ")", "\n\n", "wr", ".", "Logger", "(", ")", ".", "Infof", "(", "\"", "\"", ",", "topoproto", ".", "TabletAliasString", "(", "tablet", ".", "Tablet", ".", "Alias", ")", ")", "\n", "target", ":=", "CreateTargetFrom", "(", "tablet", ".", "Tablet", ")", "\n\n", "// Create transactions", "queryService", ",", "_", ":=", "tabletconn", ".", "GetDialer", "(", ")", "(", "tablet", ".", "Tablet", ",", "true", ")", "\n", "defer", "queryService", ".", "Close", "(", "ctx", ")", "\n", "connections", ",", "err", ":=", "createTransactions", "(", "ctx", ",", "numberOfScanners", ",", "wr", ",", "cleaner", ",", "queryService", ",", "target", ",", "tablet", ".", "Tablet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "topoproto", ".", "TabletAliasString", "(", "tablet", ".", "Tablet", ".", "Alias", ")", ")", "\n", "}", "\n", "wr", ".", "Logger", "(", ")", ".", "Infof", "(", "\"", "\"", ",", "topoproto", ".", "TabletAliasString", "(", "tablet", ".", "Tablet", ".", "Alias", ")", ")", "\n", "executedGtid", ",", "err", ":=", "tm", ".", "MasterPosition", "(", "ctx", ",", "tablet", ".", "Tablet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "topoproto", ".", "TabletAliasString", "(", "tablet", ".", "Tablet", ".", "Alias", ")", ")", "\n", "}", "\n\n", "return", "connections", ",", "executedGtid", ",", "nil", "\n", "}" ]
// CreateConsistentTransactions creates a number of consistent snapshot transactions, // all starting from the same spot in the tx log
[ "CreateConsistentTransactions", "creates", "a", "number", "of", "consistent", "snapshot", "transactions", "all", "starting", "from", "the", "same", "spot", "in", "the", "tx", "log" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/diff_utils.go#L745-L782
train
vitessio/vitess
go/vt/worker/ping.go
NewPingWorker
func NewPingWorker(wr *wrangler.Wrangler, message string) (Worker, error) { return &PingWorker{ StatusWorker: NewStatusWorker(), wr: wr, message: message, }, nil }
go
func NewPingWorker(wr *wrangler.Wrangler, message string) (Worker, error) { return &PingWorker{ StatusWorker: NewStatusWorker(), wr: wr, message: message, }, nil }
[ "func", "NewPingWorker", "(", "wr", "*", "wrangler", ".", "Wrangler", ",", "message", "string", ")", "(", "Worker", ",", "error", ")", "{", "return", "&", "PingWorker", "{", "StatusWorker", ":", "NewStatusWorker", "(", ")", ",", "wr", ":", "wr", ",", "message", ":", "message", ",", "}", ",", "nil", "\n", "}" ]
// NewPingWorker returns a new PingWorker object.
[ "NewPingWorker", "returns", "a", "new", "PingWorker", "object", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/ping.go#L37-L43
train
vitessio/vitess
go/vt/vtctl/backup.go
execBackup
func execBackup(ctx context.Context, wr *wrangler.Wrangler, tablet *topodatapb.Tablet, concurrency int, allowMaster bool) error { stream, err := wr.TabletManagerClient().Backup(ctx, tablet, concurrency, allowMaster) if err != nil { return err } for { e, err := stream.Recv() switch err { case nil: logutil.LogEvent(wr.Logger(), e) case io.EOF: return nil default: return err } } }
go
func execBackup(ctx context.Context, wr *wrangler.Wrangler, tablet *topodatapb.Tablet, concurrency int, allowMaster bool) error { stream, err := wr.TabletManagerClient().Backup(ctx, tablet, concurrency, allowMaster) if err != nil { return err } for { e, err := stream.Recv() switch err { case nil: logutil.LogEvent(wr.Logger(), e) case io.EOF: return nil default: return err } } }
[ "func", "execBackup", "(", "ctx", "context", ".", "Context", ",", "wr", "*", "wrangler", ".", "Wrangler", ",", "tablet", "*", "topodatapb", ".", "Tablet", ",", "concurrency", "int", ",", "allowMaster", "bool", ")", "error", "{", "stream", ",", "err", ":=", "wr", ".", "TabletManagerClient", "(", ")", ".", "Backup", "(", "ctx", ",", "tablet", ",", "concurrency", ",", "allowMaster", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "{", "e", ",", "err", ":=", "stream", ".", "Recv", "(", ")", "\n", "switch", "err", "{", "case", "nil", ":", "logutil", ".", "LogEvent", "(", "wr", ".", "Logger", "(", ")", ",", "e", ")", "\n", "case", "io", ".", "EOF", ":", "return", "nil", "\n", "default", ":", "return", "err", "\n", "}", "\n", "}", "\n", "}" ]
// execBackup is shared by Backup and BackupShard
[ "execBackup", "is", "shared", "by", "Backup", "and", "BackupShard" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtctl/backup.go#L153-L169
train
vitessio/vitess
go/vt/vttablet/customrule/filecustomrule/filecustomrule.go
NewFileCustomRule
func NewFileCustomRule() (fcr *FileCustomRule) { fcr = new(FileCustomRule) fcr.path = "" fcr.currentRuleSet = rules.New() return fcr }
go
func NewFileCustomRule() (fcr *FileCustomRule) { fcr = new(FileCustomRule) fcr.path = "" fcr.currentRuleSet = rules.New() return fcr }
[ "func", "NewFileCustomRule", "(", ")", "(", "fcr", "*", "FileCustomRule", ")", "{", "fcr", "=", "new", "(", "FileCustomRule", ")", "\n", "fcr", ".", "path", "=", "\"", "\"", "\n", "fcr", ".", "currentRuleSet", "=", "rules", ".", "New", "(", ")", "\n", "return", "fcr", "\n", "}" ]
// NewFileCustomRule returns pointer to new FileCustomRule structure
[ "NewFileCustomRule", "returns", "pointer", "to", "new", "FileCustomRule", "structure" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/customrule/filecustomrule/filecustomrule.go#L49-L54
train
vitessio/vitess
go/vt/vttablet/customrule/filecustomrule/filecustomrule.go
Open
func (fcr *FileCustomRule) Open(qsc tabletserver.Controller, rulePath string) error { fcr.path = rulePath if fcr.path == "" { // Don't go further if path is empty return nil } data, err := ioutil.ReadFile(fcr.path) if err != nil { log.Warningf("Error reading file %v: %v", fcr.path, err) // Don't update any internal cache, just return error return err } qrs := rules.New() err = qrs.UnmarshalJSON(data) if err != nil { log.Warningf("Error unmarshaling query rules %v", err) return err } fcr.currentRuleSetTimestamp = time.Now().Unix() fcr.currentRuleSet = qrs.Copy() // Push query rules to vttablet qsc.SetQueryRules(FileCustomRuleSource, qrs.Copy()) log.Infof("Custom rule loaded from file: %s", fcr.path) return nil }
go
func (fcr *FileCustomRule) Open(qsc tabletserver.Controller, rulePath string) error { fcr.path = rulePath if fcr.path == "" { // Don't go further if path is empty return nil } data, err := ioutil.ReadFile(fcr.path) if err != nil { log.Warningf("Error reading file %v: %v", fcr.path, err) // Don't update any internal cache, just return error return err } qrs := rules.New() err = qrs.UnmarshalJSON(data) if err != nil { log.Warningf("Error unmarshaling query rules %v", err) return err } fcr.currentRuleSetTimestamp = time.Now().Unix() fcr.currentRuleSet = qrs.Copy() // Push query rules to vttablet qsc.SetQueryRules(FileCustomRuleSource, qrs.Copy()) log.Infof("Custom rule loaded from file: %s", fcr.path) return nil }
[ "func", "(", "fcr", "*", "FileCustomRule", ")", "Open", "(", "qsc", "tabletserver", ".", "Controller", ",", "rulePath", "string", ")", "error", "{", "fcr", ".", "path", "=", "rulePath", "\n", "if", "fcr", ".", "path", "==", "\"", "\"", "{", "// Don't go further if path is empty", "return", "nil", "\n", "}", "\n", "data", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "fcr", ".", "path", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "fcr", ".", "path", ",", "err", ")", "\n", "// Don't update any internal cache, just return error", "return", "err", "\n", "}", "\n", "qrs", ":=", "rules", ".", "New", "(", ")", "\n", "err", "=", "qrs", ".", "UnmarshalJSON", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "fcr", ".", "currentRuleSetTimestamp", "=", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", "\n", "fcr", ".", "currentRuleSet", "=", "qrs", ".", "Copy", "(", ")", "\n", "// Push query rules to vttablet", "qsc", ".", "SetQueryRules", "(", "FileCustomRuleSource", ",", "qrs", ".", "Copy", "(", ")", ")", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "fcr", ".", "path", ")", "\n", "return", "nil", "\n", "}" ]
// Open try to build query rules from local file and push the rules to vttablet
[ "Open", "try", "to", "build", "query", "rules", "from", "local", "file", "and", "push", "the", "rules", "to", "vttablet" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/customrule/filecustomrule/filecustomrule.go#L57-L81
train
vitessio/vitess
go/vt/vttablet/customrule/filecustomrule/filecustomrule.go
GetRules
func (fcr *FileCustomRule) GetRules() (qrs *rules.Rules, version int64, err error) { return fcr.currentRuleSet.Copy(), fcr.currentRuleSetTimestamp, nil }
go
func (fcr *FileCustomRule) GetRules() (qrs *rules.Rules, version int64, err error) { return fcr.currentRuleSet.Copy(), fcr.currentRuleSetTimestamp, nil }
[ "func", "(", "fcr", "*", "FileCustomRule", ")", "GetRules", "(", ")", "(", "qrs", "*", "rules", ".", "Rules", ",", "version", "int64", ",", "err", "error", ")", "{", "return", "fcr", ".", "currentRuleSet", ".", "Copy", "(", ")", ",", "fcr", ".", "currentRuleSetTimestamp", ",", "nil", "\n", "}" ]
// GetRules returns query rules built from local file
[ "GetRules", "returns", "query", "rules", "built", "from", "local", "file" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/customrule/filecustomrule/filecustomrule.go#L84-L86
train
vitessio/vitess
go/vt/vttablet/customrule/filecustomrule/filecustomrule.go
ActivateFileCustomRules
func ActivateFileCustomRules(qsc tabletserver.Controller) { if *fileRulePath != "" { qsc.RegisterQueryRuleSource(FileCustomRuleSource) fileCustomRule.Open(qsc, *fileRulePath) } }
go
func ActivateFileCustomRules(qsc tabletserver.Controller) { if *fileRulePath != "" { qsc.RegisterQueryRuleSource(FileCustomRuleSource) fileCustomRule.Open(qsc, *fileRulePath) } }
[ "func", "ActivateFileCustomRules", "(", "qsc", "tabletserver", ".", "Controller", ")", "{", "if", "*", "fileRulePath", "!=", "\"", "\"", "{", "qsc", ".", "RegisterQueryRuleSource", "(", "FileCustomRuleSource", ")", "\n", "fileCustomRule", ".", "Open", "(", "qsc", ",", "*", "fileRulePath", ")", "\n", "}", "\n", "}" ]
// ActivateFileCustomRules activates this static file based custom rule mechanism
[ "ActivateFileCustomRules", "activates", "this", "static", "file", "based", "custom", "rule", "mechanism" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/customrule/filecustomrule/filecustomrule.go#L89-L94
train
vitessio/vitess
go/vt/topotools/rebuild_keyspace.go
RebuildKeyspace
func RebuildKeyspace(ctx context.Context, log logutil.Logger, ts *topo.Server, keyspace string, cells []string) (err error) { ctx, unlock, lockErr := ts.LockKeyspace(ctx, keyspace, "RebuildKeyspace") if lockErr != nil { return lockErr } defer unlock(&err) return RebuildKeyspaceLocked(ctx, log, ts, keyspace, cells) }
go
func RebuildKeyspace(ctx context.Context, log logutil.Logger, ts *topo.Server, keyspace string, cells []string) (err error) { ctx, unlock, lockErr := ts.LockKeyspace(ctx, keyspace, "RebuildKeyspace") if lockErr != nil { return lockErr } defer unlock(&err) return RebuildKeyspaceLocked(ctx, log, ts, keyspace, cells) }
[ "func", "RebuildKeyspace", "(", "ctx", "context", ".", "Context", ",", "log", "logutil", ".", "Logger", ",", "ts", "*", "topo", ".", "Server", ",", "keyspace", "string", ",", "cells", "[", "]", "string", ")", "(", "err", "error", ")", "{", "ctx", ",", "unlock", ",", "lockErr", ":=", "ts", ".", "LockKeyspace", "(", "ctx", ",", "keyspace", ",", "\"", "\"", ")", "\n", "if", "lockErr", "!=", "nil", "{", "return", "lockErr", "\n", "}", "\n", "defer", "unlock", "(", "&", "err", ")", "\n\n", "return", "RebuildKeyspaceLocked", "(", "ctx", ",", "log", ",", "ts", ",", "keyspace", ",", "cells", ")", "\n", "}" ]
// RebuildKeyspace rebuilds the serving graph data while locking out other changes.
[ "RebuildKeyspace", "rebuilds", "the", "serving", "graph", "data", "while", "locking", "out", "other", "changes", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topotools/rebuild_keyspace.go#L33-L41
train
vitessio/vitess
go/vt/vttablet/tabletmanager/vreplication/controller_plan.go
buildControllerPlan
func buildControllerPlan(query string) (*controllerPlan, error) { stmt, err := sqlparser.Parse(query) if err != nil { return nil, err } switch stmt := stmt.(type) { case *sqlparser.Insert: return buildInsertPlan(stmt) case *sqlparser.Update: return buildUpdatePlan(stmt) case *sqlparser.Delete: return buildDeletePlan(stmt) case *sqlparser.Select: return buildSelectPlan(stmt) default: return nil, fmt.Errorf("unsupported construct: %s", sqlparser.String(stmt)) } }
go
func buildControllerPlan(query string) (*controllerPlan, error) { stmt, err := sqlparser.Parse(query) if err != nil { return nil, err } switch stmt := stmt.(type) { case *sqlparser.Insert: return buildInsertPlan(stmt) case *sqlparser.Update: return buildUpdatePlan(stmt) case *sqlparser.Delete: return buildDeletePlan(stmt) case *sqlparser.Select: return buildSelectPlan(stmt) default: return nil, fmt.Errorf("unsupported construct: %s", sqlparser.String(stmt)) } }
[ "func", "buildControllerPlan", "(", "query", "string", ")", "(", "*", "controllerPlan", ",", "error", ")", "{", "stmt", ",", "err", ":=", "sqlparser", ".", "Parse", "(", "query", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "switch", "stmt", ":=", "stmt", ".", "(", "type", ")", "{", "case", "*", "sqlparser", ".", "Insert", ":", "return", "buildInsertPlan", "(", "stmt", ")", "\n", "case", "*", "sqlparser", ".", "Update", ":", "return", "buildUpdatePlan", "(", "stmt", ")", "\n", "case", "*", "sqlparser", ".", "Delete", ":", "return", "buildDeletePlan", "(", "stmt", ")", "\n", "case", "*", "sqlparser", ".", "Select", ":", "return", "buildSelectPlan", "(", "stmt", ")", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "sqlparser", ".", "String", "(", "stmt", ")", ")", "\n", "}", "\n", "}" ]
// buildControllerPlan parses the input query and returns an appropriate plan.
[ "buildControllerPlan", "parses", "the", "input", "query", "and", "returns", "an", "appropriate", "plan", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/vreplication/controller_plan.go#L41-L58
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletenv/tabletenv.go
RecordUserQuery
func RecordUserQuery(ctx context.Context, tableName sqlparser.TableIdent, queryType string, duration int64) { username := callerid.GetPrincipal(callerid.EffectiveCallerIDFromContext(ctx)) if username == "" { username = callerid.GetUsername(callerid.ImmediateCallerIDFromContext(ctx)) } UserTableQueryCount.Add([]string{tableName.String(), username, queryType}, 1) UserTableQueryTimesNs.Add([]string{tableName.String(), username, queryType}, int64(duration)) }
go
func RecordUserQuery(ctx context.Context, tableName sqlparser.TableIdent, queryType string, duration int64) { username := callerid.GetPrincipal(callerid.EffectiveCallerIDFromContext(ctx)) if username == "" { username = callerid.GetUsername(callerid.ImmediateCallerIDFromContext(ctx)) } UserTableQueryCount.Add([]string{tableName.String(), username, queryType}, 1) UserTableQueryTimesNs.Add([]string{tableName.String(), username, queryType}, int64(duration)) }
[ "func", "RecordUserQuery", "(", "ctx", "context", ".", "Context", ",", "tableName", "sqlparser", ".", "TableIdent", ",", "queryType", "string", ",", "duration", "int64", ")", "{", "username", ":=", "callerid", ".", "GetPrincipal", "(", "callerid", ".", "EffectiveCallerIDFromContext", "(", "ctx", ")", ")", "\n", "if", "username", "==", "\"", "\"", "{", "username", "=", "callerid", ".", "GetUsername", "(", "callerid", ".", "ImmediateCallerIDFromContext", "(", "ctx", ")", ")", "\n", "}", "\n", "UserTableQueryCount", ".", "Add", "(", "[", "]", "string", "{", "tableName", ".", "String", "(", ")", ",", "username", ",", "queryType", "}", ",", "1", ")", "\n", "UserTableQueryTimesNs", ".", "Add", "(", "[", "]", "string", "{", "tableName", ".", "String", "(", ")", ",", "username", ",", "queryType", "}", ",", "int64", "(", "duration", ")", ")", "\n", "}" ]
// RecordUserQuery records the query data against the user.
[ "RecordUserQuery", "records", "the", "query", "data", "against", "the", "user", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletenv/tabletenv.go#L123-L130
train
vitessio/vitess
go/vt/vttablet/tabletserver/tabletenv/tabletenv.go
LogError
func LogError() { if x := recover(); x != nil { log.Errorf("Uncaught panic:\n%v\n%s", x, tb.Stack(4)) InternalErrors.Add("Panic", 1) } }
go
func LogError() { if x := recover(); x != nil { log.Errorf("Uncaught panic:\n%v\n%s", x, tb.Stack(4)) InternalErrors.Add("Panic", 1) } }
[ "func", "LogError", "(", ")", "{", "if", "x", ":=", "recover", "(", ")", ";", "x", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\\n", "\\n", "\"", ",", "x", ",", "tb", ".", "Stack", "(", "4", ")", ")", "\n", "InternalErrors", ".", "Add", "(", "\"", "\"", ",", "1", ")", "\n", "}", "\n", "}" ]
// LogError logs panics and increments InternalErrors.
[ "LogError", "logs", "panics", "and", "increments", "InternalErrors", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletenv/tabletenv.go#L133-L138
train
vitessio/vitess
go/vt/vttablet/tabletservermock/controller.go
NewController
func NewController() *Controller { return &Controller{ queryServiceEnabled: false, BroadcastData: make(chan *BroadcastData, 10), StateChanges: make(chan *StateChange, 10), queryRulesMap: make(map[string]*rules.Rules), } }
go
func NewController() *Controller { return &Controller{ queryServiceEnabled: false, BroadcastData: make(chan *BroadcastData, 10), StateChanges: make(chan *StateChange, 10), queryRulesMap: make(map[string]*rules.Rules), } }
[ "func", "NewController", "(", ")", "*", "Controller", "{", "return", "&", "Controller", "{", "queryServiceEnabled", ":", "false", ",", "BroadcastData", ":", "make", "(", "chan", "*", "BroadcastData", ",", "10", ")", ",", "StateChanges", ":", "make", "(", "chan", "*", "StateChange", ",", "10", ")", ",", "queryRulesMap", ":", "make", "(", "map", "[", "string", "]", "*", "rules", ".", "Rules", ")", ",", "}", "\n", "}" ]
// NewController returns a mock of tabletserver.Controller
[ "NewController", "returns", "a", "mock", "of", "tabletserver", ".", "Controller" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletservermock/controller.go#L94-L101
train
vitessio/vitess
go/vt/vttablet/tabletservermock/controller.go
InitDBConfig
func (tqsc *Controller) InitDBConfig(target querypb.Target, dbcfgs *dbconfigs.DBConfigs) error { tqsc.mu.Lock() defer tqsc.mu.Unlock() tqsc.CurrentTarget = target return nil }
go
func (tqsc *Controller) InitDBConfig(target querypb.Target, dbcfgs *dbconfigs.DBConfigs) error { tqsc.mu.Lock() defer tqsc.mu.Unlock() tqsc.CurrentTarget = target return nil }
[ "func", "(", "tqsc", "*", "Controller", ")", "InitDBConfig", "(", "target", "querypb", ".", "Target", ",", "dbcfgs", "*", "dbconfigs", ".", "DBConfigs", ")", "error", "{", "tqsc", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "tqsc", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "tqsc", ".", "CurrentTarget", "=", "target", "\n", "return", "nil", "\n", "}" ]
// InitDBConfig is part of the tabletserver.Controller interface
[ "InitDBConfig", "is", "part", "of", "the", "tabletserver", ".", "Controller", "interface" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletservermock/controller.go#L112-L118
train
vitessio/vitess
go/vt/vttablet/tabletservermock/controller.go
SetServingType
func (tqsc *Controller) SetServingType(tabletType topodatapb.TabletType, serving bool, alsoAllow []topodatapb.TabletType) (bool, error) { tqsc.mu.Lock() defer tqsc.mu.Unlock() stateChanged := false if tqsc.SetServingTypeError == nil { stateChanged = tqsc.queryServiceEnabled != serving || tqsc.CurrentTarget.TabletType != tabletType tqsc.CurrentTarget.TabletType = tabletType tqsc.queryServiceEnabled = serving } if stateChanged { tqsc.StateChanges <- &StateChange{ Serving: serving, TabletType: tabletType, } } tqsc.isInLameduck = false return stateChanged, tqsc.SetServingTypeError }
go
func (tqsc *Controller) SetServingType(tabletType topodatapb.TabletType, serving bool, alsoAllow []topodatapb.TabletType) (bool, error) { tqsc.mu.Lock() defer tqsc.mu.Unlock() stateChanged := false if tqsc.SetServingTypeError == nil { stateChanged = tqsc.queryServiceEnabled != serving || tqsc.CurrentTarget.TabletType != tabletType tqsc.CurrentTarget.TabletType = tabletType tqsc.queryServiceEnabled = serving } if stateChanged { tqsc.StateChanges <- &StateChange{ Serving: serving, TabletType: tabletType, } } tqsc.isInLameduck = false return stateChanged, tqsc.SetServingTypeError }
[ "func", "(", "tqsc", "*", "Controller", ")", "SetServingType", "(", "tabletType", "topodatapb", ".", "TabletType", ",", "serving", "bool", ",", "alsoAllow", "[", "]", "topodatapb", ".", "TabletType", ")", "(", "bool", ",", "error", ")", "{", "tqsc", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "tqsc", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "stateChanged", ":=", "false", "\n", "if", "tqsc", ".", "SetServingTypeError", "==", "nil", "{", "stateChanged", "=", "tqsc", ".", "queryServiceEnabled", "!=", "serving", "||", "tqsc", ".", "CurrentTarget", ".", "TabletType", "!=", "tabletType", "\n", "tqsc", ".", "CurrentTarget", ".", "TabletType", "=", "tabletType", "\n", "tqsc", ".", "queryServiceEnabled", "=", "serving", "\n", "}", "\n", "if", "stateChanged", "{", "tqsc", ".", "StateChanges", "<-", "&", "StateChange", "{", "Serving", ":", "serving", ",", "TabletType", ":", "tabletType", ",", "}", "\n", "}", "\n", "tqsc", ".", "isInLameduck", "=", "false", "\n", "return", "stateChanged", ",", "tqsc", ".", "SetServingTypeError", "\n", "}" ]
// SetServingType is part of the tabletserver.Controller interface
[ "SetServingType", "is", "part", "of", "the", "tabletserver", ".", "Controller", "interface" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletservermock/controller.go#L121-L139
train
vitessio/vitess
go/vt/vttablet/tabletservermock/controller.go
IsServing
func (tqsc *Controller) IsServing() bool { tqsc.mu.Lock() defer tqsc.mu.Unlock() return tqsc.queryServiceEnabled }
go
func (tqsc *Controller) IsServing() bool { tqsc.mu.Lock() defer tqsc.mu.Unlock() return tqsc.queryServiceEnabled }
[ "func", "(", "tqsc", "*", "Controller", ")", "IsServing", "(", ")", "bool", "{", "tqsc", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "tqsc", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "return", "tqsc", ".", "queryServiceEnabled", "\n", "}" ]
// IsServing is part of the tabletserver.Controller interface
[ "IsServing", "is", "part", "of", "the", "tabletserver", ".", "Controller", "interface" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletservermock/controller.go#L142-L147
train
vitessio/vitess
go/vt/vttablet/tabletservermock/controller.go
SetQueryRules
func (tqsc *Controller) SetQueryRules(ruleSource string, qrs *rules.Rules) error { tqsc.mu.Lock() defer tqsc.mu.Unlock() tqsc.queryRulesMap[ruleSource] = qrs return nil }
go
func (tqsc *Controller) SetQueryRules(ruleSource string, qrs *rules.Rules) error { tqsc.mu.Lock() defer tqsc.mu.Unlock() tqsc.queryRulesMap[ruleSource] = qrs return nil }
[ "func", "(", "tqsc", "*", "Controller", ")", "SetQueryRules", "(", "ruleSource", "string", ",", "qrs", "*", "rules", ".", "Rules", ")", "error", "{", "tqsc", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "tqsc", ".", "mu", ".", "Unlock", "(", ")", "\n", "tqsc", ".", "queryRulesMap", "[", "ruleSource", "]", "=", "qrs", "\n", "return", "nil", "\n", "}" ]
// SetQueryRules is part of the tabletserver.Controller interface
[ "SetQueryRules", "is", "part", "of", "the", "tabletserver", ".", "Controller", "interface" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletservermock/controller.go#L172-L177
train
vitessio/vitess
go/vt/vttablet/tabletservermock/controller.go
BroadcastHealth
func (tqsc *Controller) BroadcastHealth(terTimestamp int64, stats *querypb.RealtimeStats, maxCache time.Duration) { tqsc.mu.Lock() defer tqsc.mu.Unlock() tqsc.BroadcastData <- &BroadcastData{ TERTimestamp: terTimestamp, RealtimeStats: *stats, Serving: tqsc.queryServiceEnabled && (!tqsc.isInLameduck), } }
go
func (tqsc *Controller) BroadcastHealth(terTimestamp int64, stats *querypb.RealtimeStats, maxCache time.Duration) { tqsc.mu.Lock() defer tqsc.mu.Unlock() tqsc.BroadcastData <- &BroadcastData{ TERTimestamp: terTimestamp, RealtimeStats: *stats, Serving: tqsc.queryServiceEnabled && (!tqsc.isInLameduck), } }
[ "func", "(", "tqsc", "*", "Controller", ")", "BroadcastHealth", "(", "terTimestamp", "int64", ",", "stats", "*", "querypb", ".", "RealtimeStats", ",", "maxCache", "time", ".", "Duration", ")", "{", "tqsc", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "tqsc", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "tqsc", ".", "BroadcastData", "<-", "&", "BroadcastData", "{", "TERTimestamp", ":", "terTimestamp", ",", "RealtimeStats", ":", "*", "stats", ",", "Serving", ":", "tqsc", ".", "queryServiceEnabled", "&&", "(", "!", "tqsc", ".", "isInLameduck", ")", ",", "}", "\n", "}" ]
// BroadcastHealth is part of the tabletserver.Controller interface
[ "BroadcastHealth", "is", "part", "of", "the", "tabletserver", ".", "Controller", "interface" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletservermock/controller.go#L190-L199
train
vitessio/vitess
go/vt/vttablet/tabletservermock/controller.go
EnterLameduck
func (tqsc *Controller) EnterLameduck() { tqsc.mu.Lock() defer tqsc.mu.Unlock() tqsc.isInLameduck = true }
go
func (tqsc *Controller) EnterLameduck() { tqsc.mu.Lock() defer tqsc.mu.Unlock() tqsc.isInLameduck = true }
[ "func", "(", "tqsc", "*", "Controller", ")", "EnterLameduck", "(", ")", "{", "tqsc", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "tqsc", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "tqsc", ".", "isInLameduck", "=", "true", "\n", "}" ]
// EnterLameduck implements tabletserver.Controller.
[ "EnterLameduck", "implements", "tabletserver", ".", "Controller", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletservermock/controller.go#L212-L217
train
vitessio/vitess
go/vt/vttablet/tabletservermock/controller.go
GetQueryRules
func (tqsc *Controller) GetQueryRules(ruleSource string) *rules.Rules { tqsc.mu.Lock() defer tqsc.mu.Unlock() return tqsc.queryRulesMap[ruleSource] }
go
func (tqsc *Controller) GetQueryRules(ruleSource string) *rules.Rules { tqsc.mu.Lock() defer tqsc.mu.Unlock() return tqsc.queryRulesMap[ruleSource] }
[ "func", "(", "tqsc", "*", "Controller", ")", "GetQueryRules", "(", "ruleSource", "string", ")", "*", "rules", ".", "Rules", "{", "tqsc", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "tqsc", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "tqsc", ".", "queryRulesMap", "[", "ruleSource", "]", "\n", "}" ]
// GetQueryRules allows a test to check what was set.
[ "GetQueryRules", "allows", "a", "test", "to", "check", "what", "was", "set", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletservermock/controller.go#L228-L232
train
vitessio/vitess
go/vt/vttablet/tabletserver/txthrottler/tx_throttler.go
CreateTxThrottlerFromTabletConfig
func CreateTxThrottlerFromTabletConfig(topoServer *topo.Server) *TxThrottler { txThrottler, err := tryCreateTxThrottler(topoServer) if err != nil { log.Errorf("Error creating transaction throttler. Transaction throttling will"+ " be disabled. Error: %v", err) txThrottler, err = newTxThrottler(&txThrottlerConfig{enabled: false}) if err != nil { panic("BUG: Can't create a disabled transaction throttler") } } else { log.Infof("Initialized transaction throttler with config: %+v", txThrottler.config) } return txThrottler }
go
func CreateTxThrottlerFromTabletConfig(topoServer *topo.Server) *TxThrottler { txThrottler, err := tryCreateTxThrottler(topoServer) if err != nil { log.Errorf("Error creating transaction throttler. Transaction throttling will"+ " be disabled. Error: %v", err) txThrottler, err = newTxThrottler(&txThrottlerConfig{enabled: false}) if err != nil { panic("BUG: Can't create a disabled transaction throttler") } } else { log.Infof("Initialized transaction throttler with config: %+v", txThrottler.config) } return txThrottler }
[ "func", "CreateTxThrottlerFromTabletConfig", "(", "topoServer", "*", "topo", ".", "Server", ")", "*", "TxThrottler", "{", "txThrottler", ",", "err", ":=", "tryCreateTxThrottler", "(", "topoServer", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "err", ")", "\n", "txThrottler", ",", "err", "=", "newTxThrottler", "(", "&", "txThrottlerConfig", "{", "enabled", ":", "false", "}", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "else", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "txThrottler", ".", "config", ")", "\n", "}", "\n", "return", "txThrottler", "\n", "}" ]
// CreateTxThrottlerFromTabletConfig tries to construct a TxThrottler from the // relevant fields in the tabletenv.Config object. It returns a disabled TxThrottler if // any error occurs. // This function calls tryCreateTxThrottler that does the actual creation work // and returns an error if one occurred.
[ "CreateTxThrottlerFromTabletConfig", "tries", "to", "construct", "a", "TxThrottler", "from", "the", "relevant", "fields", "in", "the", "tabletenv", ".", "Config", "object", ".", "It", "returns", "a", "disabled", "TxThrottler", "if", "any", "error", "occurs", ".", "This", "function", "calls", "tryCreateTxThrottler", "that", "does", "the", "actual", "creation", "work", "and", "returns", "an", "error", "if", "one", "occurred", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/txthrottler/tx_throttler.go#L79-L92
train
vitessio/vitess
go/vt/vttablet/tabletserver/txthrottler/tx_throttler.go
Open
func (t *TxThrottler) Open(keyspace, shard string) error { if !t.config.enabled { return nil } if t.state != nil { return fmt.Errorf("transaction throttler already opened") } var err error t.state, err = newTxThrottlerState(t.config, keyspace, shard) return err }
go
func (t *TxThrottler) Open(keyspace, shard string) error { if !t.config.enabled { return nil } if t.state != nil { return fmt.Errorf("transaction throttler already opened") } var err error t.state, err = newTxThrottlerState(t.config, keyspace, shard) return err }
[ "func", "(", "t", "*", "TxThrottler", ")", "Open", "(", "keyspace", ",", "shard", "string", ")", "error", "{", "if", "!", "t", ".", "config", ".", "enabled", "{", "return", "nil", "\n", "}", "\n", "if", "t", ".", "state", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "err", "error", "\n", "t", ".", "state", ",", "err", "=", "newTxThrottlerState", "(", "t", ".", "config", ",", "keyspace", ",", "shard", ")", "\n", "return", "err", "\n", "}" ]
// Open opens the transaction throttler. It must be called prior to 'Throttle'.
[ "Open", "opens", "the", "transaction", "throttler", ".", "It", "must", "be", "called", "prior", "to", "Throttle", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/txthrottler/tx_throttler.go#L213-L223
train
vitessio/vitess
go/vt/vitessdriver/driver.go
toJSON
func (c Configuration) toJSON() (string, error) { c.setDefaults() jsonBytes, err := json.Marshal(c) if err != nil { return "", err } return string(jsonBytes), nil }
go
func (c Configuration) toJSON() (string, error) { c.setDefaults() jsonBytes, err := json.Marshal(c) if err != nil { return "", err } return string(jsonBytes), nil }
[ "func", "(", "c", "Configuration", ")", "toJSON", "(", ")", "(", "string", ",", "error", ")", "{", "c", ".", "setDefaults", "(", ")", "\n", "jsonBytes", ",", "err", ":=", "json", ".", "Marshal", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "string", "(", "jsonBytes", ")", ",", "nil", "\n", "}" ]
// toJSON converts Configuration to the JSON string which is required by the // Vitess driver. Default values for empty fields will be set.
[ "toJSON", "converts", "Configuration", "to", "the", "JSON", "string", "which", "is", "required", "by", "the", "Vitess", "driver", ".", "Default", "values", "for", "empty", "fields", "will", "be", "set", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vitessdriver/driver.go#L146-L153
train
vitessio/vitess
go/acl/fallback_policy.go
CheckAccessHTTP
func (fp FallbackPolicy) CheckAccessHTTP(req *http.Request, role string) error { return errFallback }
go
func (fp FallbackPolicy) CheckAccessHTTP(req *http.Request, role string) error { return errFallback }
[ "func", "(", "fp", "FallbackPolicy", ")", "CheckAccessHTTP", "(", "req", "*", "http", ".", "Request", ",", "role", "string", ")", "error", "{", "return", "errFallback", "\n", "}" ]
// CheckAccessHTTP disallows all HTTP access.
[ "CheckAccessHTTP", "disallows", "all", "HTTP", "access", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/acl/fallback_policy.go#L37-L39
train
vitessio/vitess
go/vt/logutil/console_logger.go
WarningDepth
func (cl *ConsoleLogger) WarningDepth(depth int, s string) { log.WarningDepth(1+depth, s) }
go
func (cl *ConsoleLogger) WarningDepth(depth int, s string) { log.WarningDepth(1+depth, s) }
[ "func", "(", "cl", "*", "ConsoleLogger", ")", "WarningDepth", "(", "depth", "int", ",", "s", "string", ")", "{", "log", ".", "WarningDepth", "(", "1", "+", "depth", ",", "s", ")", "\n", "}" ]
// WarningDepth is part of the Logger interface.
[ "WarningDepth", "is", "part", "of", "the", "Logger", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/logutil/console_logger.go#L74-L76
train
vitessio/vitess
go/vt/logutil/console_logger.go
ErrorDepth
func (cl *ConsoleLogger) ErrorDepth(depth int, s string) { log.ErrorDepth(1+depth, s) }
go
func (cl *ConsoleLogger) ErrorDepth(depth int, s string) { log.ErrorDepth(1+depth, s) }
[ "func", "(", "cl", "*", "ConsoleLogger", ")", "ErrorDepth", "(", "depth", "int", ",", "s", "string", ")", "{", "log", ".", "ErrorDepth", "(", "1", "+", "depth", ",", "s", ")", "\n", "}" ]
// ErrorDepth is part of the Logger interface.
[ "ErrorDepth", "is", "part", "of", "the", "Logger", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/logutil/console_logger.go#L79-L81
train
vitessio/vitess
go/vt/topo/srv_keyspace.go
WatchSrvKeyspace
func (ts *Server) WatchSrvKeyspace(ctx context.Context, cell, keyspace string) (*WatchSrvKeyspaceData, <-chan *WatchSrvKeyspaceData, CancelFunc) { conn, err := ts.ConnForCell(ctx, cell) if err != nil { return &WatchSrvKeyspaceData{Err: err}, nil, nil } filePath := srvKeyspaceFileName(keyspace) current, wdChannel, cancel := conn.Watch(ctx, filePath) if current.Err != nil { return &WatchSrvKeyspaceData{Err: current.Err}, nil, nil } value := &topodatapb.SrvKeyspace{} if err := proto.Unmarshal(current.Contents, value); err != nil { // Cancel the watch, drain channel. cancel() for range wdChannel { } return &WatchSrvKeyspaceData{Err: vterrors.Wrapf(err, "error unpacking initial SrvKeyspace object")}, nil, nil } changes := make(chan *WatchSrvKeyspaceData, 10) // The background routine reads any event from the watch channel, // translates it, and sends it to the caller. // If cancel() is called, the underlying Watch() code will // send an ErrInterrupted and then close the channel. We'll // just propagate that back to our caller. go func() { defer close(changes) for wd := range wdChannel { if wd.Err != nil { // Last error value, we're done. // wdChannel will be closed right after // this, no need to do anything. changes <- &WatchSrvKeyspaceData{Err: wd.Err} return } value := &topodatapb.SrvKeyspace{} if err := proto.Unmarshal(wd.Contents, value); err != nil { cancel() for range wdChannel { } changes <- &WatchSrvKeyspaceData{Err: vterrors.Wrapf(err, "error unpacking SrvKeyspace object")} return } changes <- &WatchSrvKeyspaceData{Value: value} } }() return &WatchSrvKeyspaceData{Value: value}, changes, cancel }
go
func (ts *Server) WatchSrvKeyspace(ctx context.Context, cell, keyspace string) (*WatchSrvKeyspaceData, <-chan *WatchSrvKeyspaceData, CancelFunc) { conn, err := ts.ConnForCell(ctx, cell) if err != nil { return &WatchSrvKeyspaceData{Err: err}, nil, nil } filePath := srvKeyspaceFileName(keyspace) current, wdChannel, cancel := conn.Watch(ctx, filePath) if current.Err != nil { return &WatchSrvKeyspaceData{Err: current.Err}, nil, nil } value := &topodatapb.SrvKeyspace{} if err := proto.Unmarshal(current.Contents, value); err != nil { // Cancel the watch, drain channel. cancel() for range wdChannel { } return &WatchSrvKeyspaceData{Err: vterrors.Wrapf(err, "error unpacking initial SrvKeyspace object")}, nil, nil } changes := make(chan *WatchSrvKeyspaceData, 10) // The background routine reads any event from the watch channel, // translates it, and sends it to the caller. // If cancel() is called, the underlying Watch() code will // send an ErrInterrupted and then close the channel. We'll // just propagate that back to our caller. go func() { defer close(changes) for wd := range wdChannel { if wd.Err != nil { // Last error value, we're done. // wdChannel will be closed right after // this, no need to do anything. changes <- &WatchSrvKeyspaceData{Err: wd.Err} return } value := &topodatapb.SrvKeyspace{} if err := proto.Unmarshal(wd.Contents, value); err != nil { cancel() for range wdChannel { } changes <- &WatchSrvKeyspaceData{Err: vterrors.Wrapf(err, "error unpacking SrvKeyspace object")} return } changes <- &WatchSrvKeyspaceData{Value: value} } }() return &WatchSrvKeyspaceData{Value: value}, changes, cancel }
[ "func", "(", "ts", "*", "Server", ")", "WatchSrvKeyspace", "(", "ctx", "context", ".", "Context", ",", "cell", ",", "keyspace", "string", ")", "(", "*", "WatchSrvKeyspaceData", ",", "<-", "chan", "*", "WatchSrvKeyspaceData", ",", "CancelFunc", ")", "{", "conn", ",", "err", ":=", "ts", ".", "ConnForCell", "(", "ctx", ",", "cell", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "WatchSrvKeyspaceData", "{", "Err", ":", "err", "}", ",", "nil", ",", "nil", "\n", "}", "\n\n", "filePath", ":=", "srvKeyspaceFileName", "(", "keyspace", ")", "\n", "current", ",", "wdChannel", ",", "cancel", ":=", "conn", ".", "Watch", "(", "ctx", ",", "filePath", ")", "\n", "if", "current", ".", "Err", "!=", "nil", "{", "return", "&", "WatchSrvKeyspaceData", "{", "Err", ":", "current", ".", "Err", "}", ",", "nil", ",", "nil", "\n", "}", "\n", "value", ":=", "&", "topodatapb", ".", "SrvKeyspace", "{", "}", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "current", ".", "Contents", ",", "value", ")", ";", "err", "!=", "nil", "{", "// Cancel the watch, drain channel.", "cancel", "(", ")", "\n", "for", "range", "wdChannel", "{", "}", "\n", "return", "&", "WatchSrvKeyspaceData", "{", "Err", ":", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ")", "}", ",", "nil", ",", "nil", "\n", "}", "\n\n", "changes", ":=", "make", "(", "chan", "*", "WatchSrvKeyspaceData", ",", "10", ")", "\n\n", "// The background routine reads any event from the watch channel,", "// translates it, and sends it to the caller.", "// If cancel() is called, the underlying Watch() code will", "// send an ErrInterrupted and then close the channel. We'll", "// just propagate that back to our caller.", "go", "func", "(", ")", "{", "defer", "close", "(", "changes", ")", "\n\n", "for", "wd", ":=", "range", "wdChannel", "{", "if", "wd", ".", "Err", "!=", "nil", "{", "// Last error value, we're done.", "// wdChannel will be closed right after", "// this, no need to do anything.", "changes", "<-", "&", "WatchSrvKeyspaceData", "{", "Err", ":", "wd", ".", "Err", "}", "\n", "return", "\n", "}", "\n\n", "value", ":=", "&", "topodatapb", ".", "SrvKeyspace", "{", "}", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "wd", ".", "Contents", ",", "value", ")", ";", "err", "!=", "nil", "{", "cancel", "(", ")", "\n", "for", "range", "wdChannel", "{", "}", "\n", "changes", "<-", "&", "WatchSrvKeyspaceData", "{", "Err", ":", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ")", "}", "\n", "return", "\n", "}", "\n\n", "changes", "<-", "&", "WatchSrvKeyspaceData", "{", "Value", ":", "value", "}", "\n", "}", "\n", "}", "(", ")", "\n\n", "return", "&", "WatchSrvKeyspaceData", "{", "Value", ":", "value", "}", ",", "changes", ",", "cancel", "\n", "}" ]
// WatchSrvKeyspace will set a watch on the SrvKeyspace object. // It has the same contract as Conn.Watch, but it also unpacks the // contents into a SrvKeyspace object.
[ "WatchSrvKeyspace", "will", "set", "a", "watch", "on", "the", "SrvKeyspace", "object", ".", "It", "has", "the", "same", "contract", "as", "Conn", ".", "Watch", "but", "it", "also", "unpacks", "the", "contents", "into", "a", "SrvKeyspace", "object", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/srv_keyspace.go#L54-L107
train
vitessio/vitess
go/vt/topo/srv_keyspace.go
GetSrvKeyspaceNames
func (ts *Server) GetSrvKeyspaceNames(ctx context.Context, cell string) ([]string, error) { conn, err := ts.ConnForCell(ctx, cell) if err != nil { return nil, err } children, err := conn.ListDir(ctx, KeyspacesPath, false /*full*/) switch { case err == nil: return DirEntriesToStringArray(children), nil case IsErrType(err, NoNode): return nil, nil default: return nil, err } }
go
func (ts *Server) GetSrvKeyspaceNames(ctx context.Context, cell string) ([]string, error) { conn, err := ts.ConnForCell(ctx, cell) if err != nil { return nil, err } children, err := conn.ListDir(ctx, KeyspacesPath, false /*full*/) switch { case err == nil: return DirEntriesToStringArray(children), nil case IsErrType(err, NoNode): return nil, nil default: return nil, err } }
[ "func", "(", "ts", "*", "Server", ")", "GetSrvKeyspaceNames", "(", "ctx", "context", ".", "Context", ",", "cell", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "conn", ",", "err", ":=", "ts", ".", "ConnForCell", "(", "ctx", ",", "cell", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "children", ",", "err", ":=", "conn", ".", "ListDir", "(", "ctx", ",", "KeyspacesPath", ",", "false", "/*full*/", ")", "\n", "switch", "{", "case", "err", "==", "nil", ":", "return", "DirEntriesToStringArray", "(", "children", ")", ",", "nil", "\n", "case", "IsErrType", "(", "err", ",", "NoNode", ")", ":", "return", "nil", ",", "nil", "\n", "default", ":", "return", "nil", ",", "err", "\n", "}", "\n", "}" ]
// GetSrvKeyspaceNames returns the SrvKeyspace objects for a cell.
[ "GetSrvKeyspaceNames", "returns", "the", "SrvKeyspace", "objects", "for", "a", "cell", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/srv_keyspace.go#L110-L125
train
vitessio/vitess
go/vt/topo/srv_keyspace.go
GetShardServingCells
func (ts *Server) GetShardServingCells(ctx context.Context, si *ShardInfo) (servingCells []string, err error) { cells, err := ts.GetCellInfoNames(ctx) if err != nil { return nil, err } wg := sync.WaitGroup{} rec := concurrency.AllErrorRecorder{} servingCells = make([]string, 0) var mu sync.Mutex for _, cell := range cells { wg.Add(1) go func(cell, keyspace string) { defer wg.Done() srvKeyspace, err := ts.GetSrvKeyspace(ctx, cell, si.keyspace) switch { case err == nil: for _, partition := range srvKeyspace.GetPartitions() { for _, shardReference := range partition.ShardReferences { if shardReference.GetName() == si.ShardName() { func() { mu.Lock() defer mu.Unlock() // Check that this cell hasn't been added already for _, servingCell := range servingCells { if servingCell == cell { return } } servingCells = append(servingCells, cell) }() } } } case IsErrType(err, NoNode): // NOOP return default: rec.RecordError(err) return } }(cell, si.Keyspace()) } wg.Wait() if rec.HasErrors() { return nil, NewError(PartialResult, rec.Error().Error()) } return servingCells, nil }
go
func (ts *Server) GetShardServingCells(ctx context.Context, si *ShardInfo) (servingCells []string, err error) { cells, err := ts.GetCellInfoNames(ctx) if err != nil { return nil, err } wg := sync.WaitGroup{} rec := concurrency.AllErrorRecorder{} servingCells = make([]string, 0) var mu sync.Mutex for _, cell := range cells { wg.Add(1) go func(cell, keyspace string) { defer wg.Done() srvKeyspace, err := ts.GetSrvKeyspace(ctx, cell, si.keyspace) switch { case err == nil: for _, partition := range srvKeyspace.GetPartitions() { for _, shardReference := range partition.ShardReferences { if shardReference.GetName() == si.ShardName() { func() { mu.Lock() defer mu.Unlock() // Check that this cell hasn't been added already for _, servingCell := range servingCells { if servingCell == cell { return } } servingCells = append(servingCells, cell) }() } } } case IsErrType(err, NoNode): // NOOP return default: rec.RecordError(err) return } }(cell, si.Keyspace()) } wg.Wait() if rec.HasErrors() { return nil, NewError(PartialResult, rec.Error().Error()) } return servingCells, nil }
[ "func", "(", "ts", "*", "Server", ")", "GetShardServingCells", "(", "ctx", "context", ".", "Context", ",", "si", "*", "ShardInfo", ")", "(", "servingCells", "[", "]", "string", ",", "err", "error", ")", "{", "cells", ",", "err", ":=", "ts", ".", "GetCellInfoNames", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "wg", ":=", "sync", ".", "WaitGroup", "{", "}", "\n", "rec", ":=", "concurrency", ".", "AllErrorRecorder", "{", "}", "\n", "servingCells", "=", "make", "(", "[", "]", "string", ",", "0", ")", "\n", "var", "mu", "sync", ".", "Mutex", "\n", "for", "_", ",", "cell", ":=", "range", "cells", "{", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "cell", ",", "keyspace", "string", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "srvKeyspace", ",", "err", ":=", "ts", ".", "GetSrvKeyspace", "(", "ctx", ",", "cell", ",", "si", ".", "keyspace", ")", "\n", "switch", "{", "case", "err", "==", "nil", ":", "for", "_", ",", "partition", ":=", "range", "srvKeyspace", ".", "GetPartitions", "(", ")", "{", "for", "_", ",", "shardReference", ":=", "range", "partition", ".", "ShardReferences", "{", "if", "shardReference", ".", "GetName", "(", ")", "==", "si", ".", "ShardName", "(", ")", "{", "func", "(", ")", "{", "mu", ".", "Lock", "(", ")", "\n", "defer", "mu", ".", "Unlock", "(", ")", "\n", "// Check that this cell hasn't been added already", "for", "_", ",", "servingCell", ":=", "range", "servingCells", "{", "if", "servingCell", "==", "cell", "{", "return", "\n", "}", "\n", "}", "\n", "servingCells", "=", "append", "(", "servingCells", ",", "cell", ")", "\n", "}", "(", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "case", "IsErrType", "(", "err", ",", "NoNode", ")", ":", "// NOOP", "return", "\n", "default", ":", "rec", ".", "RecordError", "(", "err", ")", "\n", "return", "\n", "}", "\n", "}", "(", "cell", ",", "si", ".", "Keyspace", "(", ")", ")", "\n", "}", "\n", "wg", ".", "Wait", "(", ")", "\n", "if", "rec", ".", "HasErrors", "(", ")", "{", "return", "nil", ",", "NewError", "(", "PartialResult", ",", "rec", ".", "Error", "(", ")", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "servingCells", ",", "nil", "\n", "}" ]
// GetShardServingCells returns cells where this shard is serving
[ "GetShardServingCells", "returns", "cells", "where", "this", "shard", "is", "serving" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/srv_keyspace.go#L128-L176
train
vitessio/vitess
go/vt/topo/srv_keyspace.go
GetShardServingTypes
func (ts *Server) GetShardServingTypes(ctx context.Context, si *ShardInfo) (servingTypes []topodatapb.TabletType, err error) { cells, err := ts.GetCellInfoNames(ctx) if err != nil { return nil, err } wg := sync.WaitGroup{} rec := concurrency.AllErrorRecorder{} servingTypes = make([]topodatapb.TabletType, 0) var mu sync.Mutex for _, cell := range cells { wg.Add(1) go func(cell, keyspace string) { defer wg.Done() srvKeyspace, err := ts.GetSrvKeyspace(ctx, cell, si.keyspace) switch { case err == nil: func() { mu.Lock() defer mu.Unlock() for _, partition := range srvKeyspace.GetPartitions() { partitionAlreadyAdded := false for _, servingType := range servingTypes { if servingType == partition.ServedType { partitionAlreadyAdded = true break } } if !partitionAlreadyAdded { for _, shardReference := range partition.ShardReferences { if shardReference.GetName() == si.ShardName() { servingTypes = append(servingTypes, partition.ServedType) break } } } } }() case IsErrType(err, NoNode): // NOOP return default: rec.RecordError(err) return } }(cell, si.Keyspace()) } wg.Wait() if rec.HasErrors() { return nil, NewError(PartialResult, rec.Error().Error()) } return servingTypes, nil }
go
func (ts *Server) GetShardServingTypes(ctx context.Context, si *ShardInfo) (servingTypes []topodatapb.TabletType, err error) { cells, err := ts.GetCellInfoNames(ctx) if err != nil { return nil, err } wg := sync.WaitGroup{} rec := concurrency.AllErrorRecorder{} servingTypes = make([]topodatapb.TabletType, 0) var mu sync.Mutex for _, cell := range cells { wg.Add(1) go func(cell, keyspace string) { defer wg.Done() srvKeyspace, err := ts.GetSrvKeyspace(ctx, cell, si.keyspace) switch { case err == nil: func() { mu.Lock() defer mu.Unlock() for _, partition := range srvKeyspace.GetPartitions() { partitionAlreadyAdded := false for _, servingType := range servingTypes { if servingType == partition.ServedType { partitionAlreadyAdded = true break } } if !partitionAlreadyAdded { for _, shardReference := range partition.ShardReferences { if shardReference.GetName() == si.ShardName() { servingTypes = append(servingTypes, partition.ServedType) break } } } } }() case IsErrType(err, NoNode): // NOOP return default: rec.RecordError(err) return } }(cell, si.Keyspace()) } wg.Wait() if rec.HasErrors() { return nil, NewError(PartialResult, rec.Error().Error()) } return servingTypes, nil }
[ "func", "(", "ts", "*", "Server", ")", "GetShardServingTypes", "(", "ctx", "context", ".", "Context", ",", "si", "*", "ShardInfo", ")", "(", "servingTypes", "[", "]", "topodatapb", ".", "TabletType", ",", "err", "error", ")", "{", "cells", ",", "err", ":=", "ts", ".", "GetCellInfoNames", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "wg", ":=", "sync", ".", "WaitGroup", "{", "}", "\n", "rec", ":=", "concurrency", ".", "AllErrorRecorder", "{", "}", "\n", "servingTypes", "=", "make", "(", "[", "]", "topodatapb", ".", "TabletType", ",", "0", ")", "\n", "var", "mu", "sync", ".", "Mutex", "\n", "for", "_", ",", "cell", ":=", "range", "cells", "{", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "cell", ",", "keyspace", "string", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "srvKeyspace", ",", "err", ":=", "ts", ".", "GetSrvKeyspace", "(", "ctx", ",", "cell", ",", "si", ".", "keyspace", ")", "\n", "switch", "{", "case", "err", "==", "nil", ":", "func", "(", ")", "{", "mu", ".", "Lock", "(", ")", "\n", "defer", "mu", ".", "Unlock", "(", ")", "\n", "for", "_", ",", "partition", ":=", "range", "srvKeyspace", ".", "GetPartitions", "(", ")", "{", "partitionAlreadyAdded", ":=", "false", "\n", "for", "_", ",", "servingType", ":=", "range", "servingTypes", "{", "if", "servingType", "==", "partition", ".", "ServedType", "{", "partitionAlreadyAdded", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n\n", "if", "!", "partitionAlreadyAdded", "{", "for", "_", ",", "shardReference", ":=", "range", "partition", ".", "ShardReferences", "{", "if", "shardReference", ".", "GetName", "(", ")", "==", "si", ".", "ShardName", "(", ")", "{", "servingTypes", "=", "append", "(", "servingTypes", ",", "partition", ".", "ServedType", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n\n", "}", "\n", "}", "(", ")", "\n", "case", "IsErrType", "(", "err", ",", "NoNode", ")", ":", "// NOOP", "return", "\n", "default", ":", "rec", ".", "RecordError", "(", "err", ")", "\n", "return", "\n", "}", "\n", "}", "(", "cell", ",", "si", ".", "Keyspace", "(", ")", ")", "\n", "}", "\n", "wg", ".", "Wait", "(", ")", "\n", "if", "rec", ".", "HasErrors", "(", ")", "{", "return", "nil", ",", "NewError", "(", "PartialResult", ",", "rec", ".", "Error", "(", ")", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "servingTypes", ",", "nil", "\n", "}" ]
// GetShardServingTypes returns served types for given shard across all cells
[ "GetShardServingTypes", "returns", "served", "types", "for", "given", "shard", "across", "all", "cells" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/srv_keyspace.go#L179-L233
train
vitessio/vitess
go/vt/topo/srv_keyspace.go
AddSrvKeyspacePartitions
func (ts *Server) AddSrvKeyspacePartitions(ctx context.Context, keyspace string, shards []*ShardInfo, tabletType topodatapb.TabletType, cells []string) (err error) { if err = CheckKeyspaceLocked(ctx, keyspace); err != nil { return err } // The caller intents to update all cells in this case if len(cells) == 0 { cells, err = ts.GetCellInfoNames(ctx) if err != nil { return err } } wg := sync.WaitGroup{} rec := concurrency.AllErrorRecorder{} for _, cell := range cells { wg.Add(1) go func(cell string) { defer wg.Done() srvKeyspace, err := ts.GetSrvKeyspace(ctx, cell, keyspace) switch { case err == nil: partitionFound := false for _, partition := range srvKeyspace.GetPartitions() { if partition.GetServedType() != tabletType { continue } partitionFound = true for _, si := range shards { found := false for _, shardReference := range partition.GetShardReferences() { if key.KeyRangeEqual(shardReference.GetKeyRange(), si.GetKeyRange()) { found = true } } if !found { shardReference := &topodatapb.ShardReference{ Name: si.ShardName(), KeyRange: si.KeyRange, } partition.ShardReferences = append(partition.GetShardReferences(), shardReference) } } } // Partition does not exist at all, we need to create it if !partitionFound { partition := &topodatapb.SrvKeyspace_KeyspacePartition{ ServedType: tabletType, } shardReferences := make([]*topodatapb.ShardReference, 0) for _, si := range shards { shardReference := &topodatapb.ShardReference{ Name: si.ShardName(), KeyRange: si.KeyRange, } shardReferences = append(shardReferences, shardReference) } partition.ShardReferences = shardReferences srvKeyspace.Partitions = append(srvKeyspace.GetPartitions(), partition) } err = ts.UpdateSrvKeyspace(ctx, cell, keyspace, srvKeyspace) if err != nil { rec.RecordError(err) return } case IsErrType(err, NoNode): // NOOP default: rec.RecordError(err) return } }(cell) } wg.Wait() if rec.HasErrors() { return NewError(PartialResult, rec.Error().Error()) } return nil }
go
func (ts *Server) AddSrvKeyspacePartitions(ctx context.Context, keyspace string, shards []*ShardInfo, tabletType topodatapb.TabletType, cells []string) (err error) { if err = CheckKeyspaceLocked(ctx, keyspace); err != nil { return err } // The caller intents to update all cells in this case if len(cells) == 0 { cells, err = ts.GetCellInfoNames(ctx) if err != nil { return err } } wg := sync.WaitGroup{} rec := concurrency.AllErrorRecorder{} for _, cell := range cells { wg.Add(1) go func(cell string) { defer wg.Done() srvKeyspace, err := ts.GetSrvKeyspace(ctx, cell, keyspace) switch { case err == nil: partitionFound := false for _, partition := range srvKeyspace.GetPartitions() { if partition.GetServedType() != tabletType { continue } partitionFound = true for _, si := range shards { found := false for _, shardReference := range partition.GetShardReferences() { if key.KeyRangeEqual(shardReference.GetKeyRange(), si.GetKeyRange()) { found = true } } if !found { shardReference := &topodatapb.ShardReference{ Name: si.ShardName(), KeyRange: si.KeyRange, } partition.ShardReferences = append(partition.GetShardReferences(), shardReference) } } } // Partition does not exist at all, we need to create it if !partitionFound { partition := &topodatapb.SrvKeyspace_KeyspacePartition{ ServedType: tabletType, } shardReferences := make([]*topodatapb.ShardReference, 0) for _, si := range shards { shardReference := &topodatapb.ShardReference{ Name: si.ShardName(), KeyRange: si.KeyRange, } shardReferences = append(shardReferences, shardReference) } partition.ShardReferences = shardReferences srvKeyspace.Partitions = append(srvKeyspace.GetPartitions(), partition) } err = ts.UpdateSrvKeyspace(ctx, cell, keyspace, srvKeyspace) if err != nil { rec.RecordError(err) return } case IsErrType(err, NoNode): // NOOP default: rec.RecordError(err) return } }(cell) } wg.Wait() if rec.HasErrors() { return NewError(PartialResult, rec.Error().Error()) } return nil }
[ "func", "(", "ts", "*", "Server", ")", "AddSrvKeyspacePartitions", "(", "ctx", "context", ".", "Context", ",", "keyspace", "string", ",", "shards", "[", "]", "*", "ShardInfo", ",", "tabletType", "topodatapb", ".", "TabletType", ",", "cells", "[", "]", "string", ")", "(", "err", "error", ")", "{", "if", "err", "=", "CheckKeyspaceLocked", "(", "ctx", ",", "keyspace", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// The caller intents to update all cells in this case", "if", "len", "(", "cells", ")", "==", "0", "{", "cells", ",", "err", "=", "ts", ".", "GetCellInfoNames", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "wg", ":=", "sync", ".", "WaitGroup", "{", "}", "\n", "rec", ":=", "concurrency", ".", "AllErrorRecorder", "{", "}", "\n", "for", "_", ",", "cell", ":=", "range", "cells", "{", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "cell", "string", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "srvKeyspace", ",", "err", ":=", "ts", ".", "GetSrvKeyspace", "(", "ctx", ",", "cell", ",", "keyspace", ")", "\n", "switch", "{", "case", "err", "==", "nil", ":", "partitionFound", ":=", "false", "\n\n", "for", "_", ",", "partition", ":=", "range", "srvKeyspace", ".", "GetPartitions", "(", ")", "{", "if", "partition", ".", "GetServedType", "(", ")", "!=", "tabletType", "{", "continue", "\n", "}", "\n", "partitionFound", "=", "true", "\n\n", "for", "_", ",", "si", ":=", "range", "shards", "{", "found", ":=", "false", "\n", "for", "_", ",", "shardReference", ":=", "range", "partition", ".", "GetShardReferences", "(", ")", "{", "if", "key", ".", "KeyRangeEqual", "(", "shardReference", ".", "GetKeyRange", "(", ")", ",", "si", ".", "GetKeyRange", "(", ")", ")", "{", "found", "=", "true", "\n", "}", "\n", "}", "\n\n", "if", "!", "found", "{", "shardReference", ":=", "&", "topodatapb", ".", "ShardReference", "{", "Name", ":", "si", ".", "ShardName", "(", ")", ",", "KeyRange", ":", "si", ".", "KeyRange", ",", "}", "\n", "partition", ".", "ShardReferences", "=", "append", "(", "partition", ".", "GetShardReferences", "(", ")", ",", "shardReference", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Partition does not exist at all, we need to create it", "if", "!", "partitionFound", "{", "partition", ":=", "&", "topodatapb", ".", "SrvKeyspace_KeyspacePartition", "{", "ServedType", ":", "tabletType", ",", "}", "\n\n", "shardReferences", ":=", "make", "(", "[", "]", "*", "topodatapb", ".", "ShardReference", ",", "0", ")", "\n", "for", "_", ",", "si", ":=", "range", "shards", "{", "shardReference", ":=", "&", "topodatapb", ".", "ShardReference", "{", "Name", ":", "si", ".", "ShardName", "(", ")", ",", "KeyRange", ":", "si", ".", "KeyRange", ",", "}", "\n", "shardReferences", "=", "append", "(", "shardReferences", ",", "shardReference", ")", "\n", "}", "\n\n", "partition", ".", "ShardReferences", "=", "shardReferences", "\n\n", "srvKeyspace", ".", "Partitions", "=", "append", "(", "srvKeyspace", ".", "GetPartitions", "(", ")", ",", "partition", ")", "\n", "}", "\n\n", "err", "=", "ts", ".", "UpdateSrvKeyspace", "(", "ctx", ",", "cell", ",", "keyspace", ",", "srvKeyspace", ")", "\n", "if", "err", "!=", "nil", "{", "rec", ".", "RecordError", "(", "err", ")", "\n", "return", "\n", "}", "\n", "case", "IsErrType", "(", "err", ",", "NoNode", ")", ":", "// NOOP", "default", ":", "rec", ".", "RecordError", "(", "err", ")", "\n", "return", "\n", "}", "\n", "}", "(", "cell", ")", "\n", "}", "\n", "wg", ".", "Wait", "(", ")", "\n", "if", "rec", ".", "HasErrors", "(", ")", "{", "return", "NewError", "(", "PartialResult", ",", "rec", ".", "Error", "(", ")", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// AddSrvKeyspacePartitions adds partitions to srvKeyspace
[ "AddSrvKeyspacePartitions", "adds", "partitions", "to", "srvKeyspace" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/srv_keyspace.go#L236-L323
train
vitessio/vitess
go/vt/topo/srv_keyspace.go
UpdateDisableQueryService
func (ts *Server) UpdateDisableQueryService(ctx context.Context, keyspace string, shards []*ShardInfo, tabletType topodatapb.TabletType, cells []string, disableQueryService bool) (err error) { if err = CheckKeyspaceLocked(ctx, keyspace); err != nil { return err } // The caller intents to update all cells in this case if len(cells) == 0 { cells, err = ts.GetCellInfoNames(ctx) if err != nil { return err } } for _, shard := range shards { for _, tc := range shard.TabletControls { if len(tc.BlacklistedTables) > 0 { return fmt.Errorf("cannot safely alter DisableQueryService as BlacklistedTables is set for shard %v", shard) } } } if !disableQueryService { for _, si := range shards { tc := si.GetTabletControl(tabletType) if tc == nil { continue } if tc.Frozen { return fmt.Errorf("migrate has gone past the point of no return, cannot re-enable serving for %v/%v", si.keyspace, si.shardName) } } } wg := sync.WaitGroup{} rec := concurrency.AllErrorRecorder{} for _, cell := range cells { wg.Add(1) go func(cell string) { defer wg.Done() srvKeyspace, err := ts.GetSrvKeyspace(ctx, cell, keyspace) switch { case err == nil: for _, partition := range srvKeyspace.GetPartitions() { if partition.GetServedType() != tabletType { continue } for _, si := range shards { found := false for _, tabletControl := range partition.GetShardTabletControls() { if key.KeyRangeEqual(tabletControl.GetKeyRange(), si.GetKeyRange()) { found = true tabletControl.QueryServiceDisabled = disableQueryService } } if !found { shardTabletControl := &topodatapb.ShardTabletControl{ Name: si.ShardName(), KeyRange: si.KeyRange, QueryServiceDisabled: disableQueryService, } partition.ShardTabletControls = append(partition.GetShardTabletControls(), shardTabletControl) } } } err = ts.UpdateSrvKeyspace(ctx, cell, keyspace, srvKeyspace) if err != nil { rec.RecordError(err) return } case IsErrType(err, NoNode): // NOOP default: rec.RecordError(err) return } }(cell) } wg.Wait() if rec.HasErrors() { return NewError(PartialResult, rec.Error().Error()) } return nil }
go
func (ts *Server) UpdateDisableQueryService(ctx context.Context, keyspace string, shards []*ShardInfo, tabletType topodatapb.TabletType, cells []string, disableQueryService bool) (err error) { if err = CheckKeyspaceLocked(ctx, keyspace); err != nil { return err } // The caller intents to update all cells in this case if len(cells) == 0 { cells, err = ts.GetCellInfoNames(ctx) if err != nil { return err } } for _, shard := range shards { for _, tc := range shard.TabletControls { if len(tc.BlacklistedTables) > 0 { return fmt.Errorf("cannot safely alter DisableQueryService as BlacklistedTables is set for shard %v", shard) } } } if !disableQueryService { for _, si := range shards { tc := si.GetTabletControl(tabletType) if tc == nil { continue } if tc.Frozen { return fmt.Errorf("migrate has gone past the point of no return, cannot re-enable serving for %v/%v", si.keyspace, si.shardName) } } } wg := sync.WaitGroup{} rec := concurrency.AllErrorRecorder{} for _, cell := range cells { wg.Add(1) go func(cell string) { defer wg.Done() srvKeyspace, err := ts.GetSrvKeyspace(ctx, cell, keyspace) switch { case err == nil: for _, partition := range srvKeyspace.GetPartitions() { if partition.GetServedType() != tabletType { continue } for _, si := range shards { found := false for _, tabletControl := range partition.GetShardTabletControls() { if key.KeyRangeEqual(tabletControl.GetKeyRange(), si.GetKeyRange()) { found = true tabletControl.QueryServiceDisabled = disableQueryService } } if !found { shardTabletControl := &topodatapb.ShardTabletControl{ Name: si.ShardName(), KeyRange: si.KeyRange, QueryServiceDisabled: disableQueryService, } partition.ShardTabletControls = append(partition.GetShardTabletControls(), shardTabletControl) } } } err = ts.UpdateSrvKeyspace(ctx, cell, keyspace, srvKeyspace) if err != nil { rec.RecordError(err) return } case IsErrType(err, NoNode): // NOOP default: rec.RecordError(err) return } }(cell) } wg.Wait() if rec.HasErrors() { return NewError(PartialResult, rec.Error().Error()) } return nil }
[ "func", "(", "ts", "*", "Server", ")", "UpdateDisableQueryService", "(", "ctx", "context", ".", "Context", ",", "keyspace", "string", ",", "shards", "[", "]", "*", "ShardInfo", ",", "tabletType", "topodatapb", ".", "TabletType", ",", "cells", "[", "]", "string", ",", "disableQueryService", "bool", ")", "(", "err", "error", ")", "{", "if", "err", "=", "CheckKeyspaceLocked", "(", "ctx", ",", "keyspace", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// The caller intents to update all cells in this case", "if", "len", "(", "cells", ")", "==", "0", "{", "cells", ",", "err", "=", "ts", ".", "GetCellInfoNames", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "shard", ":=", "range", "shards", "{", "for", "_", ",", "tc", ":=", "range", "shard", ".", "TabletControls", "{", "if", "len", "(", "tc", ".", "BlacklistedTables", ")", ">", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "shard", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "!", "disableQueryService", "{", "for", "_", ",", "si", ":=", "range", "shards", "{", "tc", ":=", "si", ".", "GetTabletControl", "(", "tabletType", ")", "\n", "if", "tc", "==", "nil", "{", "continue", "\n", "}", "\n", "if", "tc", ".", "Frozen", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "si", ".", "keyspace", ",", "si", ".", "shardName", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "wg", ":=", "sync", ".", "WaitGroup", "{", "}", "\n", "rec", ":=", "concurrency", ".", "AllErrorRecorder", "{", "}", "\n", "for", "_", ",", "cell", ":=", "range", "cells", "{", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "cell", "string", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "srvKeyspace", ",", "err", ":=", "ts", ".", "GetSrvKeyspace", "(", "ctx", ",", "cell", ",", "keyspace", ")", "\n", "switch", "{", "case", "err", "==", "nil", ":", "for", "_", ",", "partition", ":=", "range", "srvKeyspace", ".", "GetPartitions", "(", ")", "{", "if", "partition", ".", "GetServedType", "(", ")", "!=", "tabletType", "{", "continue", "\n", "}", "\n\n", "for", "_", ",", "si", ":=", "range", "shards", "{", "found", ":=", "false", "\n", "for", "_", ",", "tabletControl", ":=", "range", "partition", ".", "GetShardTabletControls", "(", ")", "{", "if", "key", ".", "KeyRangeEqual", "(", "tabletControl", ".", "GetKeyRange", "(", ")", ",", "si", ".", "GetKeyRange", "(", ")", ")", "{", "found", "=", "true", "\n", "tabletControl", ".", "QueryServiceDisabled", "=", "disableQueryService", "\n", "}", "\n", "}", "\n\n", "if", "!", "found", "{", "shardTabletControl", ":=", "&", "topodatapb", ".", "ShardTabletControl", "{", "Name", ":", "si", ".", "ShardName", "(", ")", ",", "KeyRange", ":", "si", ".", "KeyRange", ",", "QueryServiceDisabled", ":", "disableQueryService", ",", "}", "\n", "partition", ".", "ShardTabletControls", "=", "append", "(", "partition", ".", "GetShardTabletControls", "(", ")", ",", "shardTabletControl", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "err", "=", "ts", ".", "UpdateSrvKeyspace", "(", "ctx", ",", "cell", ",", "keyspace", ",", "srvKeyspace", ")", "\n", "if", "err", "!=", "nil", "{", "rec", ".", "RecordError", "(", "err", ")", "\n", "return", "\n", "}", "\n", "case", "IsErrType", "(", "err", ",", "NoNode", ")", ":", "// NOOP", "default", ":", "rec", ".", "RecordError", "(", "err", ")", "\n", "return", "\n", "}", "\n", "}", "(", "cell", ")", "\n", "}", "\n", "wg", ".", "Wait", "(", ")", "\n", "if", "rec", ".", "HasErrors", "(", ")", "{", "return", "NewError", "(", "PartialResult", ",", "rec", ".", "Error", "(", ")", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UpdateDisableQueryService will make sure the disableQueryService is // set appropriately in tablet controls in srvKeyspace.
[ "UpdateDisableQueryService", "will", "make", "sure", "the", "disableQueryService", "is", "set", "appropriately", "in", "tablet", "controls", "in", "srvKeyspace", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/srv_keyspace.go#L395-L480
train
vitessio/vitess
go/vt/topo/srv_keyspace.go
UpdateSrvKeyspace
func (ts *Server) UpdateSrvKeyspace(ctx context.Context, cell, keyspace string, srvKeyspace *topodatapb.SrvKeyspace) error { conn, err := ts.ConnForCell(ctx, cell) if err != nil { return err } nodePath := srvKeyspaceFileName(keyspace) data, err := proto.Marshal(srvKeyspace) if err != nil { return err } _, err = conn.Update(ctx, nodePath, data, nil) return err }
go
func (ts *Server) UpdateSrvKeyspace(ctx context.Context, cell, keyspace string, srvKeyspace *topodatapb.SrvKeyspace) error { conn, err := ts.ConnForCell(ctx, cell) if err != nil { return err } nodePath := srvKeyspaceFileName(keyspace) data, err := proto.Marshal(srvKeyspace) if err != nil { return err } _, err = conn.Update(ctx, nodePath, data, nil) return err }
[ "func", "(", "ts", "*", "Server", ")", "UpdateSrvKeyspace", "(", "ctx", "context", ".", "Context", ",", "cell", ",", "keyspace", "string", ",", "srvKeyspace", "*", "topodatapb", ".", "SrvKeyspace", ")", "error", "{", "conn", ",", "err", ":=", "ts", ".", "ConnForCell", "(", "ctx", ",", "cell", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "nodePath", ":=", "srvKeyspaceFileName", "(", "keyspace", ")", "\n", "data", ",", "err", ":=", "proto", ".", "Marshal", "(", "srvKeyspace", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "conn", ".", "Update", "(", "ctx", ",", "nodePath", ",", "data", ",", "nil", ")", "\n", "return", "err", "\n", "}" ]
// UpdateSrvKeyspace saves a new SrvKeyspace. It is a blind write.
[ "UpdateSrvKeyspace", "saves", "a", "new", "SrvKeyspace", ".", "It", "is", "a", "blind", "write", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/srv_keyspace.go#L582-L595
train
vitessio/vitess
go/vt/topo/srv_keyspace.go
DeleteSrvKeyspace
func (ts *Server) DeleteSrvKeyspace(ctx context.Context, cell, keyspace string) error { conn, err := ts.ConnForCell(ctx, cell) if err != nil { return err } nodePath := srvKeyspaceFileName(keyspace) return conn.Delete(ctx, nodePath, nil) }
go
func (ts *Server) DeleteSrvKeyspace(ctx context.Context, cell, keyspace string) error { conn, err := ts.ConnForCell(ctx, cell) if err != nil { return err } nodePath := srvKeyspaceFileName(keyspace) return conn.Delete(ctx, nodePath, nil) }
[ "func", "(", "ts", "*", "Server", ")", "DeleteSrvKeyspace", "(", "ctx", "context", ".", "Context", ",", "cell", ",", "keyspace", "string", ")", "error", "{", "conn", ",", "err", ":=", "ts", ".", "ConnForCell", "(", "ctx", ",", "cell", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "nodePath", ":=", "srvKeyspaceFileName", "(", "keyspace", ")", "\n", "return", "conn", ".", "Delete", "(", "ctx", ",", "nodePath", ",", "nil", ")", "\n", "}" ]
// DeleteSrvKeyspace deletes a SrvKeyspace.
[ "DeleteSrvKeyspace", "deletes", "a", "SrvKeyspace", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/srv_keyspace.go#L598-L606
train
vitessio/vitess
go/vt/topo/srv_keyspace.go
GetSrvKeyspaceAllCells
func (ts *Server) GetSrvKeyspaceAllCells(ctx context.Context, keyspace string) ([]*topodatapb.SrvKeyspace, error) { cells, err := ts.GetCellInfoNames(ctx) if err != nil { return nil, err } srvKeyspaces := make([]*topodatapb.SrvKeyspace, len(cells)) for _, cell := range cells { srvKeyspace, err := ts.GetSrvKeyspace(ctx, cell, keyspace) switch { case err == nil: srvKeyspaces = append(srvKeyspaces, srvKeyspace) case IsErrType(err, NoNode): // NOOP default: return srvKeyspaces, err } } return srvKeyspaces, nil }
go
func (ts *Server) GetSrvKeyspaceAllCells(ctx context.Context, keyspace string) ([]*topodatapb.SrvKeyspace, error) { cells, err := ts.GetCellInfoNames(ctx) if err != nil { return nil, err } srvKeyspaces := make([]*topodatapb.SrvKeyspace, len(cells)) for _, cell := range cells { srvKeyspace, err := ts.GetSrvKeyspace(ctx, cell, keyspace) switch { case err == nil: srvKeyspaces = append(srvKeyspaces, srvKeyspace) case IsErrType(err, NoNode): // NOOP default: return srvKeyspaces, err } } return srvKeyspaces, nil }
[ "func", "(", "ts", "*", "Server", ")", "GetSrvKeyspaceAllCells", "(", "ctx", "context", ".", "Context", ",", "keyspace", "string", ")", "(", "[", "]", "*", "topodatapb", ".", "SrvKeyspace", ",", "error", ")", "{", "cells", ",", "err", ":=", "ts", ".", "GetCellInfoNames", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "srvKeyspaces", ":=", "make", "(", "[", "]", "*", "topodatapb", ".", "SrvKeyspace", ",", "len", "(", "cells", ")", ")", "\n", "for", "_", ",", "cell", ":=", "range", "cells", "{", "srvKeyspace", ",", "err", ":=", "ts", ".", "GetSrvKeyspace", "(", "ctx", ",", "cell", ",", "keyspace", ")", "\n", "switch", "{", "case", "err", "==", "nil", ":", "srvKeyspaces", "=", "append", "(", "srvKeyspaces", ",", "srvKeyspace", ")", "\n", "case", "IsErrType", "(", "err", ",", "NoNode", ")", ":", "// NOOP", "default", ":", "return", "srvKeyspaces", ",", "err", "\n", "}", "\n", "}", "\n", "return", "srvKeyspaces", ",", "nil", "\n", "}" ]
// GetSrvKeyspaceAllCells returns the SrvKeyspace for all cells
[ "GetSrvKeyspaceAllCells", "returns", "the", "SrvKeyspace", "for", "all", "cells" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/srv_keyspace.go#L609-L628
train
vitessio/vitess
go/vt/topo/srv_keyspace.go
OrderAndCheckPartitions
func OrderAndCheckPartitions(cell string, srvKeyspace *topodatapb.SrvKeyspace) error { // now check them all for _, partition := range srvKeyspace.Partitions { tabletType := partition.ServedType topoproto.ShardReferenceArray(partition.ShardReferences).Sort() // check the first Start is MinKey, the last End is MaxKey, // and the values in between match: End[i] == Start[i+1] first := partition.ShardReferences[0] if first.KeyRange != nil && len(first.KeyRange.Start) != 0 { return fmt.Errorf("keyspace partition for %v in cell %v does not start with min key", tabletType, cell) } last := partition.ShardReferences[len(partition.ShardReferences)-1] if last.KeyRange != nil && len(last.KeyRange.End) != 0 { return fmt.Errorf("keyspace partition for %v in cell %v does not end with max key", tabletType, cell) } for i := range partition.ShardReferences[0 : len(partition.ShardReferences)-1] { currShard := partition.ShardReferences[i] nextShard := partition.ShardReferences[i+1] currHasKeyRange := currShard.KeyRange != nil nextHasKeyRange := nextShard.KeyRange != nil if currHasKeyRange != nextHasKeyRange { return fmt.Errorf("shards with inconsistent KeyRanges for %v in cell %v. shards: %v, %v", tabletType, cell, currShard, nextShard) } if !currHasKeyRange { // this is the custom sharding case, all KeyRanges must be nil continue } if !bytes.Equal(currShard.KeyRange.End, nextShard.KeyRange.Start) { return fmt.Errorf("non-contiguous KeyRange values for %v in cell %v at shard %v to %v: %v != %v", tabletType, cell, i, i+1, hex.EncodeToString(currShard.KeyRange.End), hex.EncodeToString(nextShard.KeyRange.Start)) } } } return nil }
go
func OrderAndCheckPartitions(cell string, srvKeyspace *topodatapb.SrvKeyspace) error { // now check them all for _, partition := range srvKeyspace.Partitions { tabletType := partition.ServedType topoproto.ShardReferenceArray(partition.ShardReferences).Sort() // check the first Start is MinKey, the last End is MaxKey, // and the values in between match: End[i] == Start[i+1] first := partition.ShardReferences[0] if first.KeyRange != nil && len(first.KeyRange.Start) != 0 { return fmt.Errorf("keyspace partition for %v in cell %v does not start with min key", tabletType, cell) } last := partition.ShardReferences[len(partition.ShardReferences)-1] if last.KeyRange != nil && len(last.KeyRange.End) != 0 { return fmt.Errorf("keyspace partition for %v in cell %v does not end with max key", tabletType, cell) } for i := range partition.ShardReferences[0 : len(partition.ShardReferences)-1] { currShard := partition.ShardReferences[i] nextShard := partition.ShardReferences[i+1] currHasKeyRange := currShard.KeyRange != nil nextHasKeyRange := nextShard.KeyRange != nil if currHasKeyRange != nextHasKeyRange { return fmt.Errorf("shards with inconsistent KeyRanges for %v in cell %v. shards: %v, %v", tabletType, cell, currShard, nextShard) } if !currHasKeyRange { // this is the custom sharding case, all KeyRanges must be nil continue } if !bytes.Equal(currShard.KeyRange.End, nextShard.KeyRange.Start) { return fmt.Errorf("non-contiguous KeyRange values for %v in cell %v at shard %v to %v: %v != %v", tabletType, cell, i, i+1, hex.EncodeToString(currShard.KeyRange.End), hex.EncodeToString(nextShard.KeyRange.Start)) } } } return nil }
[ "func", "OrderAndCheckPartitions", "(", "cell", "string", ",", "srvKeyspace", "*", "topodatapb", ".", "SrvKeyspace", ")", "error", "{", "// now check them all", "for", "_", ",", "partition", ":=", "range", "srvKeyspace", ".", "Partitions", "{", "tabletType", ":=", "partition", ".", "ServedType", "\n", "topoproto", ".", "ShardReferenceArray", "(", "partition", ".", "ShardReferences", ")", ".", "Sort", "(", ")", "\n\n", "// check the first Start is MinKey, the last End is MaxKey,", "// and the values in between match: End[i] == Start[i+1]", "first", ":=", "partition", ".", "ShardReferences", "[", "0", "]", "\n", "if", "first", ".", "KeyRange", "!=", "nil", "&&", "len", "(", "first", ".", "KeyRange", ".", "Start", ")", "!=", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "tabletType", ",", "cell", ")", "\n", "}", "\n", "last", ":=", "partition", ".", "ShardReferences", "[", "len", "(", "partition", ".", "ShardReferences", ")", "-", "1", "]", "\n", "if", "last", ".", "KeyRange", "!=", "nil", "&&", "len", "(", "last", ".", "KeyRange", ".", "End", ")", "!=", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "tabletType", ",", "cell", ")", "\n", "}", "\n", "for", "i", ":=", "range", "partition", ".", "ShardReferences", "[", "0", ":", "len", "(", "partition", ".", "ShardReferences", ")", "-", "1", "]", "{", "currShard", ":=", "partition", ".", "ShardReferences", "[", "i", "]", "\n", "nextShard", ":=", "partition", ".", "ShardReferences", "[", "i", "+", "1", "]", "\n", "currHasKeyRange", ":=", "currShard", ".", "KeyRange", "!=", "nil", "\n", "nextHasKeyRange", ":=", "nextShard", ".", "KeyRange", "!=", "nil", "\n", "if", "currHasKeyRange", "!=", "nextHasKeyRange", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "tabletType", ",", "cell", ",", "currShard", ",", "nextShard", ")", "\n", "}", "\n", "if", "!", "currHasKeyRange", "{", "// this is the custom sharding case, all KeyRanges must be nil", "continue", "\n", "}", "\n", "if", "!", "bytes", ".", "Equal", "(", "currShard", ".", "KeyRange", ".", "End", ",", "nextShard", ".", "KeyRange", ".", "Start", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "tabletType", ",", "cell", ",", "i", ",", "i", "+", "1", ",", "hex", ".", "EncodeToString", "(", "currShard", ".", "KeyRange", ".", "End", ")", ",", "hex", ".", "EncodeToString", "(", "nextShard", ".", "KeyRange", ".", "Start", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// OrderAndCheckPartitions will re-order the partition list, and check // it's correct.
[ "OrderAndCheckPartitions", "will", "re", "-", "order", "the", "partition", "list", "and", "check", "it", "s", "correct", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/srv_keyspace.go#L651-L686
train
vitessio/vitess
go/vt/topo/srv_keyspace.go
ShardIsServing
func ShardIsServing(srvKeyspace *topodatapb.SrvKeyspace, shard *topodatapb.Shard) bool { for _, partition := range srvKeyspace.GetPartitions() { for _, shardReference := range partition.GetShardReferences() { if key.KeyRangeEqual(shardReference.GetKeyRange(), shard.GetKeyRange()) { return true } } } return false }
go
func ShardIsServing(srvKeyspace *topodatapb.SrvKeyspace, shard *topodatapb.Shard) bool { for _, partition := range srvKeyspace.GetPartitions() { for _, shardReference := range partition.GetShardReferences() { if key.KeyRangeEqual(shardReference.GetKeyRange(), shard.GetKeyRange()) { return true } } } return false }
[ "func", "ShardIsServing", "(", "srvKeyspace", "*", "topodatapb", ".", "SrvKeyspace", ",", "shard", "*", "topodatapb", ".", "Shard", ")", "bool", "{", "for", "_", ",", "partition", ":=", "range", "srvKeyspace", ".", "GetPartitions", "(", ")", "{", "for", "_", ",", "shardReference", ":=", "range", "partition", ".", "GetShardReferences", "(", ")", "{", "if", "key", ".", "KeyRangeEqual", "(", "shardReference", ".", "GetKeyRange", "(", ")", ",", "shard", ".", "GetKeyRange", "(", ")", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// ShardIsServing returns true if this shard is found in any of the partitions in the srvKeyspace
[ "ShardIsServing", "returns", "true", "if", "this", "shard", "is", "found", "in", "any", "of", "the", "partitions", "in", "the", "srvKeyspace" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/srv_keyspace.go#L689-L698
train
vitessio/vitess
go/vt/topo/cell_info.go
GetCellInfoNames
func (ts *Server) GetCellInfoNames(ctx context.Context) ([]string, error) { entries, err := ts.globalCell.ListDir(ctx, CellsPath, false /*full*/) switch { case IsErrType(err, NoNode): return nil, nil case err == nil: return DirEntriesToStringArray(entries), nil default: return nil, err } }
go
func (ts *Server) GetCellInfoNames(ctx context.Context) ([]string, error) { entries, err := ts.globalCell.ListDir(ctx, CellsPath, false /*full*/) switch { case IsErrType(err, NoNode): return nil, nil case err == nil: return DirEntriesToStringArray(entries), nil default: return nil, err } }
[ "func", "(", "ts", "*", "Server", ")", "GetCellInfoNames", "(", "ctx", "context", ".", "Context", ")", "(", "[", "]", "string", ",", "error", ")", "{", "entries", ",", "err", ":=", "ts", ".", "globalCell", ".", "ListDir", "(", "ctx", ",", "CellsPath", ",", "false", "/*full*/", ")", "\n", "switch", "{", "case", "IsErrType", "(", "err", ",", "NoNode", ")", ":", "return", "nil", ",", "nil", "\n", "case", "err", "==", "nil", ":", "return", "DirEntriesToStringArray", "(", "entries", ")", ",", "nil", "\n", "default", ":", "return", "nil", ",", "err", "\n", "}", "\n", "}" ]
// GetCellInfoNames returns the names of the existing cells. They are // sorted by name.
[ "GetCellInfoNames", "returns", "the", "names", "of", "the", "existing", "cells", ".", "They", "are", "sorted", "by", "name", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/cell_info.go#L47-L57
train
vitessio/vitess
go/vt/topo/cell_info.go
GetCellInfo
func (ts *Server) GetCellInfo(ctx context.Context, cell string, strongRead bool) (*topodatapb.CellInfo, error) { conn := ts.globalCell if !strongRead { conn = ts.globalReadOnlyCell } // Read the file. filePath := pathForCellInfo(cell) contents, _, err := conn.Get(ctx, filePath) if err != nil { return nil, err } // Unpack the contents. ci := &topodatapb.CellInfo{} if err := proto.Unmarshal(contents, ci); err != nil { return nil, err } return ci, nil }
go
func (ts *Server) GetCellInfo(ctx context.Context, cell string, strongRead bool) (*topodatapb.CellInfo, error) { conn := ts.globalCell if !strongRead { conn = ts.globalReadOnlyCell } // Read the file. filePath := pathForCellInfo(cell) contents, _, err := conn.Get(ctx, filePath) if err != nil { return nil, err } // Unpack the contents. ci := &topodatapb.CellInfo{} if err := proto.Unmarshal(contents, ci); err != nil { return nil, err } return ci, nil }
[ "func", "(", "ts", "*", "Server", ")", "GetCellInfo", "(", "ctx", "context", ".", "Context", ",", "cell", "string", ",", "strongRead", "bool", ")", "(", "*", "topodatapb", ".", "CellInfo", ",", "error", ")", "{", "conn", ":=", "ts", ".", "globalCell", "\n", "if", "!", "strongRead", "{", "conn", "=", "ts", ".", "globalReadOnlyCell", "\n", "}", "\n", "// Read the file.", "filePath", ":=", "pathForCellInfo", "(", "cell", ")", "\n", "contents", ",", "_", ",", "err", ":=", "conn", ".", "Get", "(", "ctx", ",", "filePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Unpack the contents.", "ci", ":=", "&", "topodatapb", ".", "CellInfo", "{", "}", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "contents", ",", "ci", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "ci", ",", "nil", "\n", "}" ]
// GetCellInfo reads a CellInfo from the global Conn.
[ "GetCellInfo", "reads", "a", "CellInfo", "from", "the", "global", "Conn", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/cell_info.go#L60-L78
train
vitessio/vitess
go/vt/topo/cell_info.go
CreateCellInfo
func (ts *Server) CreateCellInfo(ctx context.Context, cell string, ci *topodatapb.CellInfo) error { // Pack the content. contents, err := proto.Marshal(ci) if err != nil { return err } // Save it. filePath := pathForCellInfo(cell) _, err = ts.globalCell.Create(ctx, filePath, contents) return err }
go
func (ts *Server) CreateCellInfo(ctx context.Context, cell string, ci *topodatapb.CellInfo) error { // Pack the content. contents, err := proto.Marshal(ci) if err != nil { return err } // Save it. filePath := pathForCellInfo(cell) _, err = ts.globalCell.Create(ctx, filePath, contents) return err }
[ "func", "(", "ts", "*", "Server", ")", "CreateCellInfo", "(", "ctx", "context", ".", "Context", ",", "cell", "string", ",", "ci", "*", "topodatapb", ".", "CellInfo", ")", "error", "{", "// Pack the content.", "contents", ",", "err", ":=", "proto", ".", "Marshal", "(", "ci", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Save it.", "filePath", ":=", "pathForCellInfo", "(", "cell", ")", "\n", "_", ",", "err", "=", "ts", ".", "globalCell", ".", "Create", "(", "ctx", ",", "filePath", ",", "contents", ")", "\n", "return", "err", "\n", "}" ]
// CreateCellInfo creates a new CellInfo with the provided content.
[ "CreateCellInfo", "creates", "a", "new", "CellInfo", "with", "the", "provided", "content", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/cell_info.go#L81-L92
train
vitessio/vitess
go/vt/topo/cell_info.go
UpdateCellInfoFields
func (ts *Server) UpdateCellInfoFields(ctx context.Context, cell string, update func(*topodatapb.CellInfo) error) error { filePath := pathForCellInfo(cell) for { ci := &topodatapb.CellInfo{} // Read the file, unpack the contents. contents, version, err := ts.globalCell.Get(ctx, filePath) switch { case err == nil: if err := proto.Unmarshal(contents, ci); err != nil { return err } case IsErrType(err, NoNode): // Nothing to do. default: return err } // Call update method. if err = update(ci); err != nil { if IsErrType(err, NoUpdateNeeded) { return nil } return err } // Pack and save. contents, err = proto.Marshal(ci) if err != nil { return err } if _, err = ts.globalCell.Update(ctx, filePath, contents, version); !IsErrType(err, BadVersion) { // This includes the 'err=nil' case. return err } } }
go
func (ts *Server) UpdateCellInfoFields(ctx context.Context, cell string, update func(*topodatapb.CellInfo) error) error { filePath := pathForCellInfo(cell) for { ci := &topodatapb.CellInfo{} // Read the file, unpack the contents. contents, version, err := ts.globalCell.Get(ctx, filePath) switch { case err == nil: if err := proto.Unmarshal(contents, ci); err != nil { return err } case IsErrType(err, NoNode): // Nothing to do. default: return err } // Call update method. if err = update(ci); err != nil { if IsErrType(err, NoUpdateNeeded) { return nil } return err } // Pack and save. contents, err = proto.Marshal(ci) if err != nil { return err } if _, err = ts.globalCell.Update(ctx, filePath, contents, version); !IsErrType(err, BadVersion) { // This includes the 'err=nil' case. return err } } }
[ "func", "(", "ts", "*", "Server", ")", "UpdateCellInfoFields", "(", "ctx", "context", ".", "Context", ",", "cell", "string", ",", "update", "func", "(", "*", "topodatapb", ".", "CellInfo", ")", "error", ")", "error", "{", "filePath", ":=", "pathForCellInfo", "(", "cell", ")", "\n", "for", "{", "ci", ":=", "&", "topodatapb", ".", "CellInfo", "{", "}", "\n\n", "// Read the file, unpack the contents.", "contents", ",", "version", ",", "err", ":=", "ts", ".", "globalCell", ".", "Get", "(", "ctx", ",", "filePath", ")", "\n", "switch", "{", "case", "err", "==", "nil", ":", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "contents", ",", "ci", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "IsErrType", "(", "err", ",", "NoNode", ")", ":", "// Nothing to do.", "default", ":", "return", "err", "\n", "}", "\n\n", "// Call update method.", "if", "err", "=", "update", "(", "ci", ")", ";", "err", "!=", "nil", "{", "if", "IsErrType", "(", "err", ",", "NoUpdateNeeded", ")", "{", "return", "nil", "\n", "}", "\n", "return", "err", "\n", "}", "\n\n", "// Pack and save.", "contents", ",", "err", "=", "proto", ".", "Marshal", "(", "ci", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "_", ",", "err", "=", "ts", ".", "globalCell", ".", "Update", "(", "ctx", ",", "filePath", ",", "contents", ",", "version", ")", ";", "!", "IsErrType", "(", "err", ",", "BadVersion", ")", "{", "// This includes the 'err=nil' case.", "return", "err", "\n", "}", "\n", "}", "\n", "}" ]
// UpdateCellInfoFields is a high level helper method to read a CellInfo // object, update its fields, and then write it back. If the write fails due to // a version mismatch, it will re-read the record and retry the update. // If the update method returns ErrNoUpdateNeeded, nothing is written, // and nil is returned.
[ "UpdateCellInfoFields", "is", "a", "high", "level", "helper", "method", "to", "read", "a", "CellInfo", "object", "update", "its", "fields", "and", "then", "write", "it", "back", ".", "If", "the", "write", "fails", "due", "to", "a", "version", "mismatch", "it", "will", "re", "-", "read", "the", "record", "and", "retry", "the", "update", ".", "If", "the", "update", "method", "returns", "ErrNoUpdateNeeded", "nothing", "is", "written", "and", "nil", "is", "returned", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/cell_info.go#L99-L135
train
vitessio/vitess
go/vt/topo/cell_info.go
DeleteCellInfo
func (ts *Server) DeleteCellInfo(ctx context.Context, cell string) error { srvKeyspaces, err := ts.GetSrvKeyspaceNames(ctx, cell) switch { case err == nil: if len(srvKeyspaces) != 0 { return vterrors.Wrap(err, fmt.Sprintf("cell %v has serving keyspaces. Before deleting, delete keyspace with: DeleteKeyspace", cell)) } case IsErrType(err, NoNode): // Nothing to do. default: return vterrors.Wrap(err, "GetSrvKeyspaceNames() failed") } filePath := pathForCellInfo(cell) return ts.globalCell.Delete(ctx, filePath, nil) }
go
func (ts *Server) DeleteCellInfo(ctx context.Context, cell string) error { srvKeyspaces, err := ts.GetSrvKeyspaceNames(ctx, cell) switch { case err == nil: if len(srvKeyspaces) != 0 { return vterrors.Wrap(err, fmt.Sprintf("cell %v has serving keyspaces. Before deleting, delete keyspace with: DeleteKeyspace", cell)) } case IsErrType(err, NoNode): // Nothing to do. default: return vterrors.Wrap(err, "GetSrvKeyspaceNames() failed") } filePath := pathForCellInfo(cell) return ts.globalCell.Delete(ctx, filePath, nil) }
[ "func", "(", "ts", "*", "Server", ")", "DeleteCellInfo", "(", "ctx", "context", ".", "Context", ",", "cell", "string", ")", "error", "{", "srvKeyspaces", ",", "err", ":=", "ts", ".", "GetSrvKeyspaceNames", "(", "ctx", ",", "cell", ")", "\n", "switch", "{", "case", "err", "==", "nil", ":", "if", "len", "(", "srvKeyspaces", ")", "!=", "0", "{", "return", "vterrors", ".", "Wrap", "(", "err", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cell", ")", ")", "\n", "}", "\n", "case", "IsErrType", "(", "err", ",", "NoNode", ")", ":", "// Nothing to do.", "default", ":", "return", "vterrors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "filePath", ":=", "pathForCellInfo", "(", "cell", ")", "\n", "return", "ts", ".", "globalCell", ".", "Delete", "(", "ctx", ",", "filePath", ",", "nil", ")", "\n", "}" ]
// DeleteCellInfo deletes the specified CellInfo. // We first make sure no Shard record points to the cell.
[ "DeleteCellInfo", "deletes", "the", "specified", "CellInfo", ".", "We", "first", "make", "sure", "no", "Shard", "record", "points", "to", "the", "cell", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/cell_info.go#L139-L154
train
vitessio/vitess
go/vt/throttler/manager.go
MaxRates
func (m *managerImpl) MaxRates() map[string]int64 { m.mu.Lock() defer m.mu.Unlock() rates := make(map[string]int64, len(m.throttlers)) for name, t := range m.throttlers { rates[name] = t.MaxRate() } return rates }
go
func (m *managerImpl) MaxRates() map[string]int64 { m.mu.Lock() defer m.mu.Unlock() rates := make(map[string]int64, len(m.throttlers)) for name, t := range m.throttlers { rates[name] = t.MaxRate() } return rates }
[ "func", "(", "m", "*", "managerImpl", ")", "MaxRates", "(", ")", "map", "[", "string", "]", "int64", "{", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "rates", ":=", "make", "(", "map", "[", "string", "]", "int64", ",", "len", "(", "m", ".", "throttlers", ")", ")", "\n", "for", "name", ",", "t", ":=", "range", "m", ".", "throttlers", "{", "rates", "[", "name", "]", "=", "t", ".", "MaxRate", "(", ")", "\n", "}", "\n", "return", "rates", "\n", "}" ]
// MaxRates returns the max rate of all known throttlers.
[ "MaxRates", "returns", "the", "max", "rate", "of", "all", "known", "throttlers", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/manager.go#L99-L108
train
vitessio/vitess
go/vt/throttler/manager.go
SetMaxRate
func (m *managerImpl) SetMaxRate(rate int64) []string { m.mu.Lock() defer m.mu.Unlock() for _, t := range m.throttlers { t.SetMaxRate(rate) } return m.throttlerNamesLocked() }
go
func (m *managerImpl) SetMaxRate(rate int64) []string { m.mu.Lock() defer m.mu.Unlock() for _, t := range m.throttlers { t.SetMaxRate(rate) } return m.throttlerNamesLocked() }
[ "func", "(", "m", "*", "managerImpl", ")", "SetMaxRate", "(", "rate", "int64", ")", "[", "]", "string", "{", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "for", "_", ",", "t", ":=", "range", "m", ".", "throttlers", "{", "t", ".", "SetMaxRate", "(", "rate", ")", "\n", "}", "\n", "return", "m", ".", "throttlerNamesLocked", "(", ")", "\n", "}" ]
// SetMaxRate sets the max rate on all known throttlers.
[ "SetMaxRate", "sets", "the", "max", "rate", "on", "all", "known", "throttlers", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/manager.go#L111-L119
train
vitessio/vitess
go/vt/throttler/manager.go
GetConfiguration
func (m *managerImpl) GetConfiguration(throttlerName string) (map[string]*throttlerdatapb.Configuration, error) { m.mu.Lock() defer m.mu.Unlock() configurations := make(map[string]*throttlerdatapb.Configuration) if throttlerName != "" { t, ok := m.throttlers[throttlerName] if !ok { return nil, fmt.Errorf("throttler: %v does not exist", throttlerName) } configurations[throttlerName] = t.GetConfiguration() return configurations, nil } for name, t := range m.throttlers { configurations[name] = t.GetConfiguration() } return configurations, nil }
go
func (m *managerImpl) GetConfiguration(throttlerName string) (map[string]*throttlerdatapb.Configuration, error) { m.mu.Lock() defer m.mu.Unlock() configurations := make(map[string]*throttlerdatapb.Configuration) if throttlerName != "" { t, ok := m.throttlers[throttlerName] if !ok { return nil, fmt.Errorf("throttler: %v does not exist", throttlerName) } configurations[throttlerName] = t.GetConfiguration() return configurations, nil } for name, t := range m.throttlers { configurations[name] = t.GetConfiguration() } return configurations, nil }
[ "func", "(", "m", "*", "managerImpl", ")", "GetConfiguration", "(", "throttlerName", "string", ")", "(", "map", "[", "string", "]", "*", "throttlerdatapb", ".", "Configuration", ",", "error", ")", "{", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "configurations", ":=", "make", "(", "map", "[", "string", "]", "*", "throttlerdatapb", ".", "Configuration", ")", "\n\n", "if", "throttlerName", "!=", "\"", "\"", "{", "t", ",", "ok", ":=", "m", ".", "throttlers", "[", "throttlerName", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "throttlerName", ")", "\n", "}", "\n", "configurations", "[", "throttlerName", "]", "=", "t", ".", "GetConfiguration", "(", ")", "\n", "return", "configurations", ",", "nil", "\n", "}", "\n\n", "for", "name", ",", "t", ":=", "range", "m", ".", "throttlers", "{", "configurations", "[", "name", "]", "=", "t", ".", "GetConfiguration", "(", ")", "\n", "}", "\n", "return", "configurations", ",", "nil", "\n", "}" ]
// GetConfiguration implements the "Manager" interface.
[ "GetConfiguration", "implements", "the", "Manager", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/manager.go#L122-L141
train
vitessio/vitess
go/vt/throttler/manager.go
UpdateConfiguration
func (m *managerImpl) UpdateConfiguration(throttlerName string, configuration *throttlerdatapb.Configuration, copyZeroValues bool) ([]string, error) { m.mu.Lock() defer m.mu.Unlock() // Note: The calls to t.UpdateConfiguration() below return no error but the // called protobuf library functions may panic. This is fine because the // throttler RPC service has a panic handler which will catch this. if throttlerName != "" { t, ok := m.throttlers[throttlerName] if !ok { return nil, fmt.Errorf("throttler: %v does not exist", throttlerName) } if err := t.UpdateConfiguration(configuration, copyZeroValues); err != nil { return nil, fmt.Errorf("failed to update throttler: %v err: %v", throttlerName, err) } return []string{throttlerName}, nil } for name, t := range m.throttlers { if err := t.UpdateConfiguration(configuration, copyZeroValues); err != nil { return nil, fmt.Errorf("failed to update throttler: %v err: %v", name, err) } } return m.throttlerNamesLocked(), nil }
go
func (m *managerImpl) UpdateConfiguration(throttlerName string, configuration *throttlerdatapb.Configuration, copyZeroValues bool) ([]string, error) { m.mu.Lock() defer m.mu.Unlock() // Note: The calls to t.UpdateConfiguration() below return no error but the // called protobuf library functions may panic. This is fine because the // throttler RPC service has a panic handler which will catch this. if throttlerName != "" { t, ok := m.throttlers[throttlerName] if !ok { return nil, fmt.Errorf("throttler: %v does not exist", throttlerName) } if err := t.UpdateConfiguration(configuration, copyZeroValues); err != nil { return nil, fmt.Errorf("failed to update throttler: %v err: %v", throttlerName, err) } return []string{throttlerName}, nil } for name, t := range m.throttlers { if err := t.UpdateConfiguration(configuration, copyZeroValues); err != nil { return nil, fmt.Errorf("failed to update throttler: %v err: %v", name, err) } } return m.throttlerNamesLocked(), nil }
[ "func", "(", "m", "*", "managerImpl", ")", "UpdateConfiguration", "(", "throttlerName", "string", ",", "configuration", "*", "throttlerdatapb", ".", "Configuration", ",", "copyZeroValues", "bool", ")", "(", "[", "]", "string", ",", "error", ")", "{", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "// Note: The calls to t.UpdateConfiguration() below return no error but the", "// called protobuf library functions may panic. This is fine because the", "// throttler RPC service has a panic handler which will catch this.", "if", "throttlerName", "!=", "\"", "\"", "{", "t", ",", "ok", ":=", "m", ".", "throttlers", "[", "throttlerName", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "throttlerName", ")", "\n", "}", "\n", "if", "err", ":=", "t", ".", "UpdateConfiguration", "(", "configuration", ",", "copyZeroValues", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "throttlerName", ",", "err", ")", "\n", "}", "\n", "return", "[", "]", "string", "{", "throttlerName", "}", ",", "nil", "\n", "}", "\n\n", "for", "name", ",", "t", ":=", "range", "m", ".", "throttlers", "{", "if", "err", ":=", "t", ".", "UpdateConfiguration", "(", "configuration", ",", "copyZeroValues", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "m", ".", "throttlerNamesLocked", "(", ")", ",", "nil", "\n", "}" ]
// UpdateConfiguration implements the "Manager" interface.
[ "UpdateConfiguration", "implements", "the", "Manager", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/manager.go#L144-L169
train
vitessio/vitess
go/vt/throttler/manager.go
ResetConfiguration
func (m *managerImpl) ResetConfiguration(throttlerName string) ([]string, error) { m.mu.Lock() defer m.mu.Unlock() if throttlerName != "" { t, ok := m.throttlers[throttlerName] if !ok { return nil, fmt.Errorf("throttler: %v does not exist", throttlerName) } t.ResetConfiguration() return []string{throttlerName}, nil } for _, t := range m.throttlers { t.ResetConfiguration() } return m.throttlerNamesLocked(), nil }
go
func (m *managerImpl) ResetConfiguration(throttlerName string) ([]string, error) { m.mu.Lock() defer m.mu.Unlock() if throttlerName != "" { t, ok := m.throttlers[throttlerName] if !ok { return nil, fmt.Errorf("throttler: %v does not exist", throttlerName) } t.ResetConfiguration() return []string{throttlerName}, nil } for _, t := range m.throttlers { t.ResetConfiguration() } return m.throttlerNamesLocked(), nil }
[ "func", "(", "m", "*", "managerImpl", ")", "ResetConfiguration", "(", "throttlerName", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "throttlerName", "!=", "\"", "\"", "{", "t", ",", "ok", ":=", "m", ".", "throttlers", "[", "throttlerName", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "throttlerName", ")", "\n", "}", "\n", "t", ".", "ResetConfiguration", "(", ")", "\n", "return", "[", "]", "string", "{", "throttlerName", "}", ",", "nil", "\n", "}", "\n\n", "for", "_", ",", "t", ":=", "range", "m", ".", "throttlers", "{", "t", ".", "ResetConfiguration", "(", ")", "\n", "}", "\n", "return", "m", ".", "throttlerNamesLocked", "(", ")", ",", "nil", "\n", "}" ]
// ResetConfiguration implements the "Manager" interface.
[ "ResetConfiguration", "implements", "the", "Manager", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/manager.go#L172-L189
train
vitessio/vitess
go/vt/throttler/manager.go
Throttlers
func (m *managerImpl) Throttlers() []string { m.mu.Lock() defer m.mu.Unlock() return m.throttlerNamesLocked() }
go
func (m *managerImpl) Throttlers() []string { m.mu.Lock() defer m.mu.Unlock() return m.throttlerNamesLocked() }
[ "func", "(", "m", "*", "managerImpl", ")", "Throttlers", "(", ")", "[", "]", "string", "{", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "return", "m", ".", "throttlerNamesLocked", "(", ")", "\n", "}" ]
// Throttlers returns the sorted list of active throttlers.
[ "Throttlers", "returns", "the", "sorted", "list", "of", "active", "throttlers", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/manager.go#L192-L197
train
vitessio/vitess
go/vt/throttler/manager.go
Log
func (m *managerImpl) Log(throttlerName string) ([]result, error) { m.mu.Lock() defer m.mu.Unlock() t, ok := m.throttlers[throttlerName] if !ok { return nil, fmt.Errorf("throttler: %v does not exist", throttlerName) } return t.Log(), nil }
go
func (m *managerImpl) Log(throttlerName string) ([]result, error) { m.mu.Lock() defer m.mu.Unlock() t, ok := m.throttlers[throttlerName] if !ok { return nil, fmt.Errorf("throttler: %v does not exist", throttlerName) } return t.Log(), nil }
[ "func", "(", "m", "*", "managerImpl", ")", "Log", "(", "throttlerName", "string", ")", "(", "[", "]", "result", ",", "error", ")", "{", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "t", ",", "ok", ":=", "m", ".", "throttlers", "[", "throttlerName", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "throttlerName", ")", "\n", "}", "\n\n", "return", "t", ".", "Log", "(", ")", ",", "nil", "\n", "}" ]
// Log returns the most recent changes of the MaxReplicationLag module. // There will be one result for each processed replication lag record.
[ "Log", "returns", "the", "most", "recent", "changes", "of", "the", "MaxReplicationLag", "module", ".", "There", "will", "be", "one", "result", "for", "each", "processed", "replication", "lag", "record", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/manager.go#L210-L220
train
vitessio/vitess
go/vt/vtgate/vindexes/binarymd5.go
NewBinaryMD5
func NewBinaryMD5(name string, _ map[string]string) (Vindex, error) { return &BinaryMD5{name: name}, nil }
go
func NewBinaryMD5(name string, _ map[string]string) (Vindex, error) { return &BinaryMD5{name: name}, nil }
[ "func", "NewBinaryMD5", "(", "name", "string", ",", "_", "map", "[", "string", "]", "string", ")", "(", "Vindex", ",", "error", ")", "{", "return", "&", "BinaryMD5", "{", "name", ":", "name", "}", ",", "nil", "\n", "}" ]
// NewBinaryMD5 creates a new BinaryMD5.
[ "NewBinaryMD5", "creates", "a", "new", "BinaryMD5", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vindexes/binarymd5.go#L37-L39
train
vitessio/vitess
go/vt/vttablet/tabletserver/tx_prep_pool.go
NewTxPreparedPool
func NewTxPreparedPool(capacity int) *TxPreparedPool { if capacity < 0 { // If capacity is 0 all prepares will fail. capacity = 0 } return &TxPreparedPool{ conns: make(map[string]*TxConnection, capacity), reserved: make(map[string]error), capacity: capacity, } }
go
func NewTxPreparedPool(capacity int) *TxPreparedPool { if capacity < 0 { // If capacity is 0 all prepares will fail. capacity = 0 } return &TxPreparedPool{ conns: make(map[string]*TxConnection, capacity), reserved: make(map[string]error), capacity: capacity, } }
[ "func", "NewTxPreparedPool", "(", "capacity", "int", ")", "*", "TxPreparedPool", "{", "if", "capacity", "<", "0", "{", "// If capacity is 0 all prepares will fail.", "capacity", "=", "0", "\n", "}", "\n", "return", "&", "TxPreparedPool", "{", "conns", ":", "make", "(", "map", "[", "string", "]", "*", "TxConnection", ",", "capacity", ")", ",", "reserved", ":", "make", "(", "map", "[", "string", "]", "error", ")", ",", "capacity", ":", "capacity", ",", "}", "\n", "}" ]
// NewTxPreparedPool creates a new TxPreparedPool.
[ "NewTxPreparedPool", "creates", "a", "new", "TxPreparedPool", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_prep_pool.go#L41-L51
train
vitessio/vitess
go/vt/vttablet/tabletserver/tx_prep_pool.go
Put
func (pp *TxPreparedPool) Put(c *TxConnection, dtid string) error { pp.mu.Lock() defer pp.mu.Unlock() if _, ok := pp.reserved[dtid]; ok { return errors.New("duplicate DTID in Prepare: " + dtid) } if _, ok := pp.conns[dtid]; ok { return errors.New("duplicate DTID in Prepare: " + dtid) } if len(pp.conns) >= pp.capacity { return fmt.Errorf("prepared transactions exceeded limit: %d", pp.capacity) } pp.conns[dtid] = c return nil }
go
func (pp *TxPreparedPool) Put(c *TxConnection, dtid string) error { pp.mu.Lock() defer pp.mu.Unlock() if _, ok := pp.reserved[dtid]; ok { return errors.New("duplicate DTID in Prepare: " + dtid) } if _, ok := pp.conns[dtid]; ok { return errors.New("duplicate DTID in Prepare: " + dtid) } if len(pp.conns) >= pp.capacity { return fmt.Errorf("prepared transactions exceeded limit: %d", pp.capacity) } pp.conns[dtid] = c return nil }
[ "func", "(", "pp", "*", "TxPreparedPool", ")", "Put", "(", "c", "*", "TxConnection", ",", "dtid", "string", ")", "error", "{", "pp", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "pp", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "_", ",", "ok", ":=", "pp", ".", "reserved", "[", "dtid", "]", ";", "ok", "{", "return", "errors", ".", "New", "(", "\"", "\"", "+", "dtid", ")", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "pp", ".", "conns", "[", "dtid", "]", ";", "ok", "{", "return", "errors", ".", "New", "(", "\"", "\"", "+", "dtid", ")", "\n", "}", "\n", "if", "len", "(", "pp", ".", "conns", ")", ">=", "pp", ".", "capacity", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "pp", ".", "capacity", ")", "\n", "}", "\n", "pp", ".", "conns", "[", "dtid", "]", "=", "c", "\n", "return", "nil", "\n", "}" ]
// Put adds the connection to the pool. It returns an error // if the pool is full or on duplicate key.
[ "Put", "adds", "the", "connection", "to", "the", "pool", ".", "It", "returns", "an", "error", "if", "the", "pool", "is", "full", "or", "on", "duplicate", "key", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_prep_pool.go#L55-L69
train
vitessio/vitess
go/vt/vttablet/tabletserver/tx_prep_pool.go
FetchForRollback
func (pp *TxPreparedPool) FetchForRollback(dtid string) *TxConnection { pp.mu.Lock() defer pp.mu.Unlock() if _, ok := pp.reserved[dtid]; ok { delete(pp.reserved, dtid) return nil } c := pp.conns[dtid] delete(pp.conns, dtid) return c }
go
func (pp *TxPreparedPool) FetchForRollback(dtid string) *TxConnection { pp.mu.Lock() defer pp.mu.Unlock() if _, ok := pp.reserved[dtid]; ok { delete(pp.reserved, dtid) return nil } c := pp.conns[dtid] delete(pp.conns, dtid) return c }
[ "func", "(", "pp", "*", "TxPreparedPool", ")", "FetchForRollback", "(", "dtid", "string", ")", "*", "TxConnection", "{", "pp", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "pp", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "_", ",", "ok", ":=", "pp", ".", "reserved", "[", "dtid", "]", ";", "ok", "{", "delete", "(", "pp", ".", "reserved", ",", "dtid", ")", "\n", "return", "nil", "\n", "}", "\n", "c", ":=", "pp", ".", "conns", "[", "dtid", "]", "\n", "delete", "(", "pp", ".", "conns", ",", "dtid", ")", "\n", "return", "c", "\n", "}" ]
// FetchForRollback returns the connection and removes it from the pool. // If the connection is not found, it returns nil. If the dtid // is in the reserved list, it means that an operator is trying // to resolve a previously failed commit. So, it removes the entry // and returns nil.
[ "FetchForRollback", "returns", "the", "connection", "and", "removes", "it", "from", "the", "pool", ".", "If", "the", "connection", "is", "not", "found", "it", "returns", "nil", ".", "If", "the", "dtid", "is", "in", "the", "reserved", "list", "it", "means", "that", "an", "operator", "is", "trying", "to", "resolve", "a", "previously", "failed", "commit", ".", "So", "it", "removes", "the", "entry", "and", "returns", "nil", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_prep_pool.go#L76-L86
train
vitessio/vitess
go/vt/vttablet/tabletserver/tx_prep_pool.go
FetchForCommit
func (pp *TxPreparedPool) FetchForCommit(dtid string) (*TxConnection, error) { pp.mu.Lock() defer pp.mu.Unlock() if err, ok := pp.reserved[dtid]; ok { return nil, err } c, ok := pp.conns[dtid] if ok { delete(pp.conns, dtid) pp.reserved[dtid] = errPrepCommitting } return c, nil }
go
func (pp *TxPreparedPool) FetchForCommit(dtid string) (*TxConnection, error) { pp.mu.Lock() defer pp.mu.Unlock() if err, ok := pp.reserved[dtid]; ok { return nil, err } c, ok := pp.conns[dtid] if ok { delete(pp.conns, dtid) pp.reserved[dtid] = errPrepCommitting } return c, nil }
[ "func", "(", "pp", "*", "TxPreparedPool", ")", "FetchForCommit", "(", "dtid", "string", ")", "(", "*", "TxConnection", ",", "error", ")", "{", "pp", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "pp", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "err", ",", "ok", ":=", "pp", ".", "reserved", "[", "dtid", "]", ";", "ok", "{", "return", "nil", ",", "err", "\n", "}", "\n", "c", ",", "ok", ":=", "pp", ".", "conns", "[", "dtid", "]", "\n", "if", "ok", "{", "delete", "(", "pp", ".", "conns", ",", "dtid", ")", "\n", "pp", ".", "reserved", "[", "dtid", "]", "=", "errPrepCommitting", "\n", "}", "\n", "return", "c", ",", "nil", "\n", "}" ]
// FetchForCommit returns the connection for commit. Before returning, // it remembers the dtid in its reserved list as "committing". If // the dtid is already in the reserved list, it returns an error. // If the commit is successful, the dtid can be removed from the // reserved list by calling Forget. If the commit failed, SetFailed // must be called. This will inform future retries that the previous // commit failed.
[ "FetchForCommit", "returns", "the", "connection", "for", "commit", ".", "Before", "returning", "it", "remembers", "the", "dtid", "in", "its", "reserved", "list", "as", "committing", ".", "If", "the", "dtid", "is", "already", "in", "the", "reserved", "list", "it", "returns", "an", "error", ".", "If", "the", "commit", "is", "successful", "the", "dtid", "can", "be", "removed", "from", "the", "reserved", "list", "by", "calling", "Forget", ".", "If", "the", "commit", "failed", "SetFailed", "must", "be", "called", ".", "This", "will", "inform", "future", "retries", "that", "the", "previous", "commit", "failed", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_prep_pool.go#L95-L107
train
vitessio/vitess
go/vt/vttablet/tabletserver/tx_prep_pool.go
SetFailed
func (pp *TxPreparedPool) SetFailed(dtid string) { pp.mu.Lock() defer pp.mu.Unlock() pp.reserved[dtid] = errPrepFailed }
go
func (pp *TxPreparedPool) SetFailed(dtid string) { pp.mu.Lock() defer pp.mu.Unlock() pp.reserved[dtid] = errPrepFailed }
[ "func", "(", "pp", "*", "TxPreparedPool", ")", "SetFailed", "(", "dtid", "string", ")", "{", "pp", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "pp", ".", "mu", ".", "Unlock", "(", ")", "\n", "pp", ".", "reserved", "[", "dtid", "]", "=", "errPrepFailed", "\n", "}" ]
// SetFailed marks the reserved dtid as failed. // If there was no previous entry, one is created.
[ "SetFailed", "marks", "the", "reserved", "dtid", "as", "failed", ".", "If", "there", "was", "no", "previous", "entry", "one", "is", "created", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_prep_pool.go#L111-L115
train
vitessio/vitess
go/vt/vttablet/tabletserver/tx_prep_pool.go
Forget
func (pp *TxPreparedPool) Forget(dtid string) { pp.mu.Lock() defer pp.mu.Unlock() delete(pp.reserved, dtid) }
go
func (pp *TxPreparedPool) Forget(dtid string) { pp.mu.Lock() defer pp.mu.Unlock() delete(pp.reserved, dtid) }
[ "func", "(", "pp", "*", "TxPreparedPool", ")", "Forget", "(", "dtid", "string", ")", "{", "pp", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "pp", ".", "mu", ".", "Unlock", "(", ")", "\n", "delete", "(", "pp", ".", "reserved", ",", "dtid", ")", "\n", "}" ]
// Forget removes the dtid from the reserved list.
[ "Forget", "removes", "the", "dtid", "from", "the", "reserved", "list", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_prep_pool.go#L118-L122
train
vitessio/vitess
go/vt/vttablet/tabletserver/tx_prep_pool.go
FetchAll
func (pp *TxPreparedPool) FetchAll() []*TxConnection { pp.mu.Lock() defer pp.mu.Unlock() conns := make([]*TxConnection, 0, len(pp.conns)) for _, c := range pp.conns { conns = append(conns, c) } pp.conns = make(map[string]*TxConnection, pp.capacity) pp.reserved = make(map[string]error) return conns }
go
func (pp *TxPreparedPool) FetchAll() []*TxConnection { pp.mu.Lock() defer pp.mu.Unlock() conns := make([]*TxConnection, 0, len(pp.conns)) for _, c := range pp.conns { conns = append(conns, c) } pp.conns = make(map[string]*TxConnection, pp.capacity) pp.reserved = make(map[string]error) return conns }
[ "func", "(", "pp", "*", "TxPreparedPool", ")", "FetchAll", "(", ")", "[", "]", "*", "TxConnection", "{", "pp", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "pp", ".", "mu", ".", "Unlock", "(", ")", "\n", "conns", ":=", "make", "(", "[", "]", "*", "TxConnection", ",", "0", ",", "len", "(", "pp", ".", "conns", ")", ")", "\n", "for", "_", ",", "c", ":=", "range", "pp", ".", "conns", "{", "conns", "=", "append", "(", "conns", ",", "c", ")", "\n", "}", "\n", "pp", ".", "conns", "=", "make", "(", "map", "[", "string", "]", "*", "TxConnection", ",", "pp", ".", "capacity", ")", "\n", "pp", ".", "reserved", "=", "make", "(", "map", "[", "string", "]", "error", ")", "\n", "return", "conns", "\n", "}" ]
// FetchAll removes all connections and returns them as a list. // It also forgets all reserved dtids.
[ "FetchAll", "removes", "all", "connections", "and", "returns", "them", "as", "a", "list", ".", "It", "also", "forgets", "all", "reserved", "dtids", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tx_prep_pool.go#L126-L136
train
vitessio/vitess
go/vt/vttablet/tabletmanager/rpc_schema.go
GetSchema
func (agent *ActionAgent) GetSchema(ctx context.Context, tables, excludeTables []string, includeViews bool) (*tabletmanagerdatapb.SchemaDefinition, error) { return agent.MysqlDaemon.GetSchema(topoproto.TabletDbName(agent.Tablet()), tables, excludeTables, includeViews) }
go
func (agent *ActionAgent) GetSchema(ctx context.Context, tables, excludeTables []string, includeViews bool) (*tabletmanagerdatapb.SchemaDefinition, error) { return agent.MysqlDaemon.GetSchema(topoproto.TabletDbName(agent.Tablet()), tables, excludeTables, includeViews) }
[ "func", "(", "agent", "*", "ActionAgent", ")", "GetSchema", "(", "ctx", "context", ".", "Context", ",", "tables", ",", "excludeTables", "[", "]", "string", ",", "includeViews", "bool", ")", "(", "*", "tabletmanagerdatapb", ".", "SchemaDefinition", ",", "error", ")", "{", "return", "agent", ".", "MysqlDaemon", ".", "GetSchema", "(", "topoproto", ".", "TabletDbName", "(", "agent", ".", "Tablet", "(", ")", ")", ",", "tables", ",", "excludeTables", ",", "includeViews", ")", "\n", "}" ]
// GetSchema returns the schema.
[ "GetSchema", "returns", "the", "schema", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/rpc_schema.go#L33-L35
train
vitessio/vitess
go/vt/vttablet/tabletmanager/rpc_schema.go
ReloadSchema
func (agent *ActionAgent) ReloadSchema(ctx context.Context, waitPosition string) error { if agent.DBConfigs.IsZero() { // we skip this for test instances that can't connect to the DB anyway return nil } if waitPosition != "" { pos, err := mysql.DecodePosition(waitPosition) if err != nil { return vterrors.Wrapf(err, "ReloadSchema: can't parse wait position (%q)", waitPosition) } log.Infof("ReloadSchema: waiting for replication position: %v", waitPosition) if err := agent.MysqlDaemon.WaitMasterPos(ctx, pos); err != nil { return err } } log.Infof("ReloadSchema requested via RPC") return agent.QueryServiceControl.ReloadSchema(ctx) }
go
func (agent *ActionAgent) ReloadSchema(ctx context.Context, waitPosition string) error { if agent.DBConfigs.IsZero() { // we skip this for test instances that can't connect to the DB anyway return nil } if waitPosition != "" { pos, err := mysql.DecodePosition(waitPosition) if err != nil { return vterrors.Wrapf(err, "ReloadSchema: can't parse wait position (%q)", waitPosition) } log.Infof("ReloadSchema: waiting for replication position: %v", waitPosition) if err := agent.MysqlDaemon.WaitMasterPos(ctx, pos); err != nil { return err } } log.Infof("ReloadSchema requested via RPC") return agent.QueryServiceControl.ReloadSchema(ctx) }
[ "func", "(", "agent", "*", "ActionAgent", ")", "ReloadSchema", "(", "ctx", "context", ".", "Context", ",", "waitPosition", "string", ")", "error", "{", "if", "agent", ".", "DBConfigs", ".", "IsZero", "(", ")", "{", "// we skip this for test instances that can't connect to the DB anyway", "return", "nil", "\n", "}", "\n\n", "if", "waitPosition", "!=", "\"", "\"", "{", "pos", ",", "err", ":=", "mysql", ".", "DecodePosition", "(", "waitPosition", ")", "\n", "if", "err", "!=", "nil", "{", "return", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "waitPosition", ")", "\n", "}", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "waitPosition", ")", "\n", "if", "err", ":=", "agent", ".", "MysqlDaemon", ".", "WaitMasterPos", "(", "ctx", ",", "pos", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "log", ".", "Infof", "(", "\"", "\"", ")", "\n", "return", "agent", ".", "QueryServiceControl", ".", "ReloadSchema", "(", "ctx", ")", "\n", "}" ]
// ReloadSchema will reload the schema // This doesn't need the action mutex because periodic schema reloads happen // in the background anyway.
[ "ReloadSchema", "will", "reload", "the", "schema", "This", "doesn", "t", "need", "the", "action", "mutex", "because", "periodic", "schema", "reloads", "happen", "in", "the", "background", "anyway", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/rpc_schema.go#L40-L59
train
vitessio/vitess
go/vt/vttablet/tabletmanager/rpc_schema.go
PreflightSchema
func (agent *ActionAgent) PreflightSchema(ctx context.Context, changes []string) ([]*tabletmanagerdatapb.SchemaChangeResult, error) { if err := agent.lock(ctx); err != nil { return nil, err } defer agent.unlock() // get the db name from the tablet dbName := topoproto.TabletDbName(agent.Tablet()) // and preflight the change return agent.MysqlDaemon.PreflightSchemaChange(dbName, changes) }
go
func (agent *ActionAgent) PreflightSchema(ctx context.Context, changes []string) ([]*tabletmanagerdatapb.SchemaChangeResult, error) { if err := agent.lock(ctx); err != nil { return nil, err } defer agent.unlock() // get the db name from the tablet dbName := topoproto.TabletDbName(agent.Tablet()) // and preflight the change return agent.MysqlDaemon.PreflightSchemaChange(dbName, changes) }
[ "func", "(", "agent", "*", "ActionAgent", ")", "PreflightSchema", "(", "ctx", "context", ".", "Context", ",", "changes", "[", "]", "string", ")", "(", "[", "]", "*", "tabletmanagerdatapb", ".", "SchemaChangeResult", ",", "error", ")", "{", "if", "err", ":=", "agent", ".", "lock", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "agent", ".", "unlock", "(", ")", "\n\n", "// get the db name from the tablet", "dbName", ":=", "topoproto", ".", "TabletDbName", "(", "agent", ".", "Tablet", "(", ")", ")", "\n\n", "// and preflight the change", "return", "agent", ".", "MysqlDaemon", ".", "PreflightSchemaChange", "(", "dbName", ",", "changes", ")", "\n", "}" ]
// PreflightSchema will try out the schema changes in "changes".
[ "PreflightSchema", "will", "try", "out", "the", "schema", "changes", "in", "changes", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/rpc_schema.go#L62-L73
train
vitessio/vitess
go/vt/vttablet/tabletmanager/rpc_schema.go
ApplySchema
func (agent *ActionAgent) ApplySchema(ctx context.Context, change *tmutils.SchemaChange) (*tabletmanagerdatapb.SchemaChangeResult, error) { if err := agent.lock(ctx); err != nil { return nil, err } defer agent.unlock() // get the db name from the tablet dbName := topoproto.TabletDbName(agent.Tablet()) // apply the change scr, err := agent.MysqlDaemon.ApplySchemaChange(dbName, change) if err != nil { return nil, err } // and if it worked, reload the schema agent.ReloadSchema(ctx, "") return scr, nil }
go
func (agent *ActionAgent) ApplySchema(ctx context.Context, change *tmutils.SchemaChange) (*tabletmanagerdatapb.SchemaChangeResult, error) { if err := agent.lock(ctx); err != nil { return nil, err } defer agent.unlock() // get the db name from the tablet dbName := topoproto.TabletDbName(agent.Tablet()) // apply the change scr, err := agent.MysqlDaemon.ApplySchemaChange(dbName, change) if err != nil { return nil, err } // and if it worked, reload the schema agent.ReloadSchema(ctx, "") return scr, nil }
[ "func", "(", "agent", "*", "ActionAgent", ")", "ApplySchema", "(", "ctx", "context", ".", "Context", ",", "change", "*", "tmutils", ".", "SchemaChange", ")", "(", "*", "tabletmanagerdatapb", ".", "SchemaChangeResult", ",", "error", ")", "{", "if", "err", ":=", "agent", ".", "lock", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "agent", ".", "unlock", "(", ")", "\n\n", "// get the db name from the tablet", "dbName", ":=", "topoproto", ".", "TabletDbName", "(", "agent", ".", "Tablet", "(", ")", ")", "\n\n", "// apply the change", "scr", ",", "err", ":=", "agent", ".", "MysqlDaemon", ".", "ApplySchemaChange", "(", "dbName", ",", "change", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// and if it worked, reload the schema", "agent", ".", "ReloadSchema", "(", "ctx", ",", "\"", "\"", ")", "\n", "return", "scr", ",", "nil", "\n", "}" ]
// ApplySchema will apply a schema change
[ "ApplySchema", "will", "apply", "a", "schema", "change" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/rpc_schema.go#L76-L94
train
vitessio/vitess
go/vt/throttler/max_replication_lag_module.go
NewMaxReplicationLagModule
func NewMaxReplicationLagModule(config MaxReplicationLagModuleConfig, actualRatesHistory *aggregatedIntervalHistory, nowFunc func() time.Time) (*MaxReplicationLagModule, error) { if err := config.Verify(); err != nil { return nil, fmt.Errorf("invalid NewMaxReplicationLagModuleConfig: %v", err) } rate := int64(ReplicationLagModuleDisabled) if config.MaxReplicationLagSec != ReplicationLagModuleDisabled { rate = config.InitialRate } m := &MaxReplicationLagModule{ initialMaxReplicationLagSec: config.MaxReplicationLagSec, // Register "config" for a future config update. mutableConfig: config, applyMutableConfig: true, // Always start off with a non-zero rate because zero means all requests // get throttled. rate: sync2.NewAtomicInt64(rate), currentState: stateIncreaseRate, lastRateChange: nowFunc(), memory: newMemory(memoryGranularity, config.AgeBadRateAfter(), config.BadRateIncrease), lagRecords: make(chan replicationLagRecord, 10), // Prevent an immediate increase of the initial rate. nextAllowedChangeAfterInit: nowFunc().Add(config.MaxDurationBetweenIncreases()), actualRatesHistory: actualRatesHistory, replicaLagCache: newReplicationLagCache(1000), rdonlyLagCache: newReplicationLagCache(1000), results: newResultRing(1000), } // Enforce a config update. m.applyLatestConfig() return m, nil }
go
func NewMaxReplicationLagModule(config MaxReplicationLagModuleConfig, actualRatesHistory *aggregatedIntervalHistory, nowFunc func() time.Time) (*MaxReplicationLagModule, error) { if err := config.Verify(); err != nil { return nil, fmt.Errorf("invalid NewMaxReplicationLagModuleConfig: %v", err) } rate := int64(ReplicationLagModuleDisabled) if config.MaxReplicationLagSec != ReplicationLagModuleDisabled { rate = config.InitialRate } m := &MaxReplicationLagModule{ initialMaxReplicationLagSec: config.MaxReplicationLagSec, // Register "config" for a future config update. mutableConfig: config, applyMutableConfig: true, // Always start off with a non-zero rate because zero means all requests // get throttled. rate: sync2.NewAtomicInt64(rate), currentState: stateIncreaseRate, lastRateChange: nowFunc(), memory: newMemory(memoryGranularity, config.AgeBadRateAfter(), config.BadRateIncrease), lagRecords: make(chan replicationLagRecord, 10), // Prevent an immediate increase of the initial rate. nextAllowedChangeAfterInit: nowFunc().Add(config.MaxDurationBetweenIncreases()), actualRatesHistory: actualRatesHistory, replicaLagCache: newReplicationLagCache(1000), rdonlyLagCache: newReplicationLagCache(1000), results: newResultRing(1000), } // Enforce a config update. m.applyLatestConfig() return m, nil }
[ "func", "NewMaxReplicationLagModule", "(", "config", "MaxReplicationLagModuleConfig", ",", "actualRatesHistory", "*", "aggregatedIntervalHistory", ",", "nowFunc", "func", "(", ")", "time", ".", "Time", ")", "(", "*", "MaxReplicationLagModule", ",", "error", ")", "{", "if", "err", ":=", "config", ".", "Verify", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "rate", ":=", "int64", "(", "ReplicationLagModuleDisabled", ")", "\n", "if", "config", ".", "MaxReplicationLagSec", "!=", "ReplicationLagModuleDisabled", "{", "rate", "=", "config", ".", "InitialRate", "\n", "}", "\n\n", "m", ":=", "&", "MaxReplicationLagModule", "{", "initialMaxReplicationLagSec", ":", "config", ".", "MaxReplicationLagSec", ",", "// Register \"config\" for a future config update.", "mutableConfig", ":", "config", ",", "applyMutableConfig", ":", "true", ",", "// Always start off with a non-zero rate because zero means all requests", "// get throttled.", "rate", ":", "sync2", ".", "NewAtomicInt64", "(", "rate", ")", ",", "currentState", ":", "stateIncreaseRate", ",", "lastRateChange", ":", "nowFunc", "(", ")", ",", "memory", ":", "newMemory", "(", "memoryGranularity", ",", "config", ".", "AgeBadRateAfter", "(", ")", ",", "config", ".", "BadRateIncrease", ")", ",", "lagRecords", ":", "make", "(", "chan", "replicationLagRecord", ",", "10", ")", ",", "// Prevent an immediate increase of the initial rate.", "nextAllowedChangeAfterInit", ":", "nowFunc", "(", ")", ".", "Add", "(", "config", ".", "MaxDurationBetweenIncreases", "(", ")", ")", ",", "actualRatesHistory", ":", "actualRatesHistory", ",", "replicaLagCache", ":", "newReplicationLagCache", "(", "1000", ")", ",", "rdonlyLagCache", ":", "newReplicationLagCache", "(", "1000", ")", ",", "results", ":", "newResultRing", "(", "1000", ")", ",", "}", "\n\n", "// Enforce a config update.", "m", ".", "applyLatestConfig", "(", ")", "\n\n", "return", "m", ",", "nil", "\n", "}" ]
// NewMaxReplicationLagModule will create a new module instance and set the // initial max replication lag limit to maxReplicationLag.
[ "NewMaxReplicationLagModule", "will", "create", "a", "new", "module", "instance", "and", "set", "the", "initial", "max", "replication", "lag", "limit", "to", "maxReplicationLag", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/max_replication_lag_module.go#L128-L161
train
vitessio/vitess
go/vt/throttler/max_replication_lag_module.go
Start
func (m *MaxReplicationLagModule) Start(rateUpdateChan chan<- struct{}) { m.rateUpdateChan = rateUpdateChan m.wg.Add(1) go m.ProcessRecords() }
go
func (m *MaxReplicationLagModule) Start(rateUpdateChan chan<- struct{}) { m.rateUpdateChan = rateUpdateChan m.wg.Add(1) go m.ProcessRecords() }
[ "func", "(", "m", "*", "MaxReplicationLagModule", ")", "Start", "(", "rateUpdateChan", "chan", "<-", "struct", "{", "}", ")", "{", "m", ".", "rateUpdateChan", "=", "rateUpdateChan", "\n", "m", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "m", ".", "ProcessRecords", "(", ")", "\n", "}" ]
// Start launches a Go routine which reacts on replication lag records. // It implements the Module interface.
[ "Start", "launches", "a", "Go", "routine", "which", "reacts", "on", "replication", "lag", "records", ".", "It", "implements", "the", "Module", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/max_replication_lag_module.go#L165-L169
train
vitessio/vitess
go/vt/throttler/max_replication_lag_module.go
RecordReplicationLag
func (m *MaxReplicationLagModule) RecordReplicationLag(t time.Time, ts *discovery.TabletStats) { m.mutableConfigMu.Lock() if m.mutableConfig.MaxReplicationLagSec == ReplicationLagModuleDisabled { m.mutableConfigMu.Unlock() return } m.mutableConfigMu.Unlock() // Buffer data point for now to unblock the HealthCheck listener and process // it asynchronously in ProcessRecords(). m.lagRecords <- replicationLagRecord{t, *ts} }
go
func (m *MaxReplicationLagModule) RecordReplicationLag(t time.Time, ts *discovery.TabletStats) { m.mutableConfigMu.Lock() if m.mutableConfig.MaxReplicationLagSec == ReplicationLagModuleDisabled { m.mutableConfigMu.Unlock() return } m.mutableConfigMu.Unlock() // Buffer data point for now to unblock the HealthCheck listener and process // it asynchronously in ProcessRecords(). m.lagRecords <- replicationLagRecord{t, *ts} }
[ "func", "(", "m", "*", "MaxReplicationLagModule", ")", "RecordReplicationLag", "(", "t", "time", ".", "Time", ",", "ts", "*", "discovery", ".", "TabletStats", ")", "{", "m", ".", "mutableConfigMu", ".", "Lock", "(", ")", "\n", "if", "m", ".", "mutableConfig", ".", "MaxReplicationLagSec", "==", "ReplicationLagModuleDisabled", "{", "m", ".", "mutableConfigMu", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n", "m", ".", "mutableConfigMu", ".", "Unlock", "(", ")", "\n\n", "// Buffer data point for now to unblock the HealthCheck listener and process", "// it asynchronously in ProcessRecords().", "m", ".", "lagRecords", "<-", "replicationLagRecord", "{", "t", ",", "*", "ts", "}", "\n", "}" ]
// RecordReplicationLag records the current replication lag for processing.
[ "RecordReplicationLag", "records", "the", "current", "replication", "lag", "for", "processing", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/max_replication_lag_module.go#L243-L254
train
vitessio/vitess
go/vt/throttler/max_replication_lag_module.go
stateGreater
func stateGreater(a, b state) bool { switch a { case stateIncreaseRate: return false case stateDecreaseAndGuessRate: return b == stateIncreaseRate case stateEmergency: return b == stateIncreaseRate || b == stateDecreaseAndGuessRate default: panic(fmt.Sprintf("BUG: cannot compare states: %v and %v", a, b)) } }
go
func stateGreater(a, b state) bool { switch a { case stateIncreaseRate: return false case stateDecreaseAndGuessRate: return b == stateIncreaseRate case stateEmergency: return b == stateIncreaseRate || b == stateDecreaseAndGuessRate default: panic(fmt.Sprintf("BUG: cannot compare states: %v and %v", a, b)) } }
[ "func", "stateGreater", "(", "a", ",", "b", "state", ")", "bool", "{", "switch", "a", "{", "case", "stateIncreaseRate", ":", "return", "false", "\n", "case", "stateDecreaseAndGuessRate", ":", "return", "b", "==", "stateIncreaseRate", "\n", "case", "stateEmergency", ":", "return", "b", "==", "stateIncreaseRate", "||", "b", "==", "stateDecreaseAndGuessRate", "\n", "default", ":", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "a", ",", "b", ")", ")", "\n", "}", "\n", "}" ]
// stateGreater returns true if a > b i.e. the state "a" is more severe than // "b". For example, "decrease" > "increase" returns true.
[ "stateGreater", "returns", "true", "if", "a", ">", "b", "i", ".", "e", ".", "the", "state", "a", "is", "more", "severe", "than", "b", ".", "For", "example", "decrease", ">", "increase", "returns", "true", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/max_replication_lag_module.go#L428-L439
train
vitessio/vitess
go/vt/throttler/max_replication_lag_module.go
markCurrentRateAsBadOrGood
func (m *MaxReplicationLagModule) markCurrentRateAsBadOrGood(r *result, now time.Time, newState state, replicationLagChange replicationLagChange) { if m.lastRateChange.IsZero() { // Module was just started. We don't have any data points yet. r.GoodOrBad = ignoredRate r.MemorySkipReason = "rate was never changed before (initial start)" return } // Use the actual rate instead of the set rate. // (It might be lower because the system was slower or the throttler rate was // set by a different module and not us.) rate := m.actualRatesHistory.average(m.lastRateChange, now) if math.IsNaN(rate) { // NaN (0.0/0.0) occurs when no records were in the timespan. // Wait for more records. r.GoodOrBad = ignoredRate r.MemorySkipReason = "cannot determine actual rate: no records in [lastRateChange, now]" return } rateIsGood := false switch m.currentState { case stateIncreaseRate: switch newState { case stateIncreaseRate: rateIsGood = true case stateDecreaseAndGuessRate: rateIsGood = false case stateEmergency: rateIsGood = false } case stateDecreaseAndGuessRate: switch newState { case stateIncreaseRate: rateIsGood = true case stateDecreaseAndGuessRate: switch replicationLagChange { case unknown: return case less: rateIsGood = true case equal: // Replication lag kept constant. Impossible to judge if the rate is good or bad. return case greater: rateIsGood = false } case stateEmergency: rateIsGood = false } case stateEmergency: // Rate changes initiated during an "emergency" phase provide no meaningful data point. r.MemorySkipReason = "not marking a rate as good or bad while in the emergency state" m.memory.touchBadRateAge(now) return } r.CurrentRate = int64(rate) if rateIsGood { if err := m.memory.markGood(int64(rate)); err == nil { r.GoodOrBad = goodRate } else { r.MemorySkipReason = err.Error() } } else { if err := m.memory.markBad(int64(rate), now); err == nil { r.GoodOrBad = badRate } else { r.MemorySkipReason = err.Error() } } }
go
func (m *MaxReplicationLagModule) markCurrentRateAsBadOrGood(r *result, now time.Time, newState state, replicationLagChange replicationLagChange) { if m.lastRateChange.IsZero() { // Module was just started. We don't have any data points yet. r.GoodOrBad = ignoredRate r.MemorySkipReason = "rate was never changed before (initial start)" return } // Use the actual rate instead of the set rate. // (It might be lower because the system was slower or the throttler rate was // set by a different module and not us.) rate := m.actualRatesHistory.average(m.lastRateChange, now) if math.IsNaN(rate) { // NaN (0.0/0.0) occurs when no records were in the timespan. // Wait for more records. r.GoodOrBad = ignoredRate r.MemorySkipReason = "cannot determine actual rate: no records in [lastRateChange, now]" return } rateIsGood := false switch m.currentState { case stateIncreaseRate: switch newState { case stateIncreaseRate: rateIsGood = true case stateDecreaseAndGuessRate: rateIsGood = false case stateEmergency: rateIsGood = false } case stateDecreaseAndGuessRate: switch newState { case stateIncreaseRate: rateIsGood = true case stateDecreaseAndGuessRate: switch replicationLagChange { case unknown: return case less: rateIsGood = true case equal: // Replication lag kept constant. Impossible to judge if the rate is good or bad. return case greater: rateIsGood = false } case stateEmergency: rateIsGood = false } case stateEmergency: // Rate changes initiated during an "emergency" phase provide no meaningful data point. r.MemorySkipReason = "not marking a rate as good or bad while in the emergency state" m.memory.touchBadRateAge(now) return } r.CurrentRate = int64(rate) if rateIsGood { if err := m.memory.markGood(int64(rate)); err == nil { r.GoodOrBad = goodRate } else { r.MemorySkipReason = err.Error() } } else { if err := m.memory.markBad(int64(rate), now); err == nil { r.GoodOrBad = badRate } else { r.MemorySkipReason = err.Error() } } }
[ "func", "(", "m", "*", "MaxReplicationLagModule", ")", "markCurrentRateAsBadOrGood", "(", "r", "*", "result", ",", "now", "time", ".", "Time", ",", "newState", "state", ",", "replicationLagChange", "replicationLagChange", ")", "{", "if", "m", ".", "lastRateChange", ".", "IsZero", "(", ")", "{", "// Module was just started. We don't have any data points yet.", "r", ".", "GoodOrBad", "=", "ignoredRate", "\n", "r", ".", "MemorySkipReason", "=", "\"", "\"", "\n", "return", "\n", "}", "\n\n", "// Use the actual rate instead of the set rate.", "// (It might be lower because the system was slower or the throttler rate was", "// set by a different module and not us.)", "rate", ":=", "m", ".", "actualRatesHistory", ".", "average", "(", "m", ".", "lastRateChange", ",", "now", ")", "\n", "if", "math", ".", "IsNaN", "(", "rate", ")", "{", "// NaN (0.0/0.0) occurs when no records were in the timespan.", "// Wait for more records.", "r", ".", "GoodOrBad", "=", "ignoredRate", "\n", "r", ".", "MemorySkipReason", "=", "\"", "\"", "\n", "return", "\n", "}", "\n\n", "rateIsGood", ":=", "false", "\n\n", "switch", "m", ".", "currentState", "{", "case", "stateIncreaseRate", ":", "switch", "newState", "{", "case", "stateIncreaseRate", ":", "rateIsGood", "=", "true", "\n", "case", "stateDecreaseAndGuessRate", ":", "rateIsGood", "=", "false", "\n", "case", "stateEmergency", ":", "rateIsGood", "=", "false", "\n", "}", "\n", "case", "stateDecreaseAndGuessRate", ":", "switch", "newState", "{", "case", "stateIncreaseRate", ":", "rateIsGood", "=", "true", "\n", "case", "stateDecreaseAndGuessRate", ":", "switch", "replicationLagChange", "{", "case", "unknown", ":", "return", "\n", "case", "less", ":", "rateIsGood", "=", "true", "\n", "case", "equal", ":", "// Replication lag kept constant. Impossible to judge if the rate is good or bad.", "return", "\n", "case", "greater", ":", "rateIsGood", "=", "false", "\n", "}", "\n", "case", "stateEmergency", ":", "rateIsGood", "=", "false", "\n", "}", "\n", "case", "stateEmergency", ":", "// Rate changes initiated during an \"emergency\" phase provide no meaningful data point.", "r", ".", "MemorySkipReason", "=", "\"", "\"", "\n", "m", ".", "memory", ".", "touchBadRateAge", "(", "now", ")", "\n", "return", "\n", "}", "\n\n", "r", ".", "CurrentRate", "=", "int64", "(", "rate", ")", "\n", "if", "rateIsGood", "{", "if", "err", ":=", "m", ".", "memory", ".", "markGood", "(", "int64", "(", "rate", ")", ")", ";", "err", "==", "nil", "{", "r", ".", "GoodOrBad", "=", "goodRate", "\n", "}", "else", "{", "r", ".", "MemorySkipReason", "=", "err", ".", "Error", "(", ")", "\n", "}", "\n", "}", "else", "{", "if", "err", ":=", "m", ".", "memory", ".", "markBad", "(", "int64", "(", "rate", ")", ",", "now", ")", ";", "err", "==", "nil", "{", "r", ".", "GoodOrBad", "=", "badRate", "\n", "}", "else", "{", "r", ".", "MemorySkipReason", "=", "err", ".", "Error", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// markCurrentRateAsBadOrGood determines the actual rate between the last rate // change and "now" and determines if that rate was bad or good.
[ "markCurrentRateAsBadOrGood", "determines", "the", "actual", "rate", "between", "the", "last", "rate", "change", "and", "now", "and", "determines", "if", "that", "rate", "was", "bad", "or", "good", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/max_replication_lag_module.go#L722-L794
train
vitessio/vitess
go/vt/vttablet/grpctmserver/server.go
SetReadOnly
func (s *server) SetReadOnly(ctx context.Context, request *tabletmanagerdatapb.SetReadOnlyRequest) (response *tabletmanagerdatapb.SetReadOnlyResponse, err error) { defer s.agent.HandleRPCPanic(ctx, "SetReadOnly", request, response, true /*verbose*/, &err) ctx = callinfo.GRPCCallInfo(ctx) response = &tabletmanagerdatapb.SetReadOnlyResponse{} return response, s.agent.SetReadOnly(ctx, true) }
go
func (s *server) SetReadOnly(ctx context.Context, request *tabletmanagerdatapb.SetReadOnlyRequest) (response *tabletmanagerdatapb.SetReadOnlyResponse, err error) { defer s.agent.HandleRPCPanic(ctx, "SetReadOnly", request, response, true /*verbose*/, &err) ctx = callinfo.GRPCCallInfo(ctx) response = &tabletmanagerdatapb.SetReadOnlyResponse{} return response, s.agent.SetReadOnly(ctx, true) }
[ "func", "(", "s", "*", "server", ")", "SetReadOnly", "(", "ctx", "context", ".", "Context", ",", "request", "*", "tabletmanagerdatapb", ".", "SetReadOnlyRequest", ")", "(", "response", "*", "tabletmanagerdatapb", ".", "SetReadOnlyResponse", ",", "err", "error", ")", "{", "defer", "s", ".", "agent", ".", "HandleRPCPanic", "(", "ctx", ",", "\"", "\"", ",", "request", ",", "response", ",", "true", "/*verbose*/", ",", "&", "err", ")", "\n", "ctx", "=", "callinfo", ".", "GRPCCallInfo", "(", "ctx", ")", "\n", "response", "=", "&", "tabletmanagerdatapb", ".", "SetReadOnlyResponse", "{", "}", "\n", "return", "response", ",", "s", ".", "agent", ".", "SetReadOnly", "(", "ctx", ",", "true", ")", "\n", "}" ]
// // Various read-write methods //
[ "Various", "read", "-", "write", "methods" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/grpctmserver/server.go#L102-L107
train
vitessio/vitess
go/vt/vttablet/grpctmserver/server.go
SlaveStatus
func (s *server) SlaveStatus(ctx context.Context, request *tabletmanagerdatapb.SlaveStatusRequest) (response *tabletmanagerdatapb.SlaveStatusResponse, err error) { defer s.agent.HandleRPCPanic(ctx, "SlaveStatus", request, response, false /*verbose*/, &err) ctx = callinfo.GRPCCallInfo(ctx) response = &tabletmanagerdatapb.SlaveStatusResponse{} status, err := s.agent.SlaveStatus(ctx) if err == nil { response.Status = status } return response, err }
go
func (s *server) SlaveStatus(ctx context.Context, request *tabletmanagerdatapb.SlaveStatusRequest) (response *tabletmanagerdatapb.SlaveStatusResponse, err error) { defer s.agent.HandleRPCPanic(ctx, "SlaveStatus", request, response, false /*verbose*/, &err) ctx = callinfo.GRPCCallInfo(ctx) response = &tabletmanagerdatapb.SlaveStatusResponse{} status, err := s.agent.SlaveStatus(ctx) if err == nil { response.Status = status } return response, err }
[ "func", "(", "s", "*", "server", ")", "SlaveStatus", "(", "ctx", "context", ".", "Context", ",", "request", "*", "tabletmanagerdatapb", ".", "SlaveStatusRequest", ")", "(", "response", "*", "tabletmanagerdatapb", ".", "SlaveStatusResponse", ",", "err", "error", ")", "{", "defer", "s", ".", "agent", ".", "HandleRPCPanic", "(", "ctx", ",", "\"", "\"", ",", "request", ",", "response", ",", "false", "/*verbose*/", ",", "&", "err", ")", "\n", "ctx", "=", "callinfo", ".", "GRPCCallInfo", "(", "ctx", ")", "\n", "response", "=", "&", "tabletmanagerdatapb", ".", "SlaveStatusResponse", "{", "}", "\n", "status", ",", "err", ":=", "s", ".", "agent", ".", "SlaveStatus", "(", "ctx", ")", "\n", "if", "err", "==", "nil", "{", "response", ".", "Status", "=", "status", "\n", "}", "\n", "return", "response", ",", "err", "\n", "}" ]
// // Replication related methods //
[ "Replication", "related", "methods" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/grpctmserver/server.go#L237-L246
train
vitessio/vitess
go/vt/vttablet/grpctmserver/server.go
ResetReplication
func (s *server) ResetReplication(ctx context.Context, request *tabletmanagerdatapb.ResetReplicationRequest) (response *tabletmanagerdatapb.ResetReplicationResponse, err error) { defer s.agent.HandleRPCPanic(ctx, "ResetReplication", request, response, true /*verbose*/, &err) ctx = callinfo.GRPCCallInfo(ctx) response = &tabletmanagerdatapb.ResetReplicationResponse{} return response, s.agent.ResetReplication(ctx) }
go
func (s *server) ResetReplication(ctx context.Context, request *tabletmanagerdatapb.ResetReplicationRequest) (response *tabletmanagerdatapb.ResetReplicationResponse, err error) { defer s.agent.HandleRPCPanic(ctx, "ResetReplication", request, response, true /*verbose*/, &err) ctx = callinfo.GRPCCallInfo(ctx) response = &tabletmanagerdatapb.ResetReplicationResponse{} return response, s.agent.ResetReplication(ctx) }
[ "func", "(", "s", "*", "server", ")", "ResetReplication", "(", "ctx", "context", ".", "Context", ",", "request", "*", "tabletmanagerdatapb", ".", "ResetReplicationRequest", ")", "(", "response", "*", "tabletmanagerdatapb", ".", "ResetReplicationResponse", ",", "err", "error", ")", "{", "defer", "s", ".", "agent", ".", "HandleRPCPanic", "(", "ctx", ",", "\"", "\"", ",", "request", ",", "response", ",", "true", "/*verbose*/", ",", "&", "err", ")", "\n", "ctx", "=", "callinfo", ".", "GRPCCallInfo", "(", "ctx", ")", "\n", "response", "=", "&", "tabletmanagerdatapb", ".", "ResetReplicationResponse", "{", "}", "\n", "return", "response", ",", "s", ".", "agent", ".", "ResetReplication", "(", "ctx", ")", "\n", "}" ]
// // Reparenting related functions //
[ "Reparenting", "related", "functions" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/grpctmserver/server.go#L332-L337
train
vitessio/vitess
go/vt/wrangler/wrangler.go
New
func New(logger logutil.Logger, ts *topo.Server, tmc tmclient.TabletManagerClient) *Wrangler { return &Wrangler{ logger: logger, ts: ts, tmc: tmc, } }
go
func New(logger logutil.Logger, ts *topo.Server, tmc tmclient.TabletManagerClient) *Wrangler { return &Wrangler{ logger: logger, ts: ts, tmc: tmc, } }
[ "func", "New", "(", "logger", "logutil", ".", "Logger", ",", "ts", "*", "topo", ".", "Server", ",", "tmc", "tmclient", ".", "TabletManagerClient", ")", "*", "Wrangler", "{", "return", "&", "Wrangler", "{", "logger", ":", "logger", ",", "ts", ":", "ts", ",", "tmc", ":", "tmc", ",", "}", "\n", "}" ]
// New creates a new Wrangler object.
[ "New", "creates", "a", "new", "Wrangler", "object", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/wrangler.go#L48-L54
train
vitessio/vitess
go/vt/mysqlctl/cmd.go
CreateMysqldAndMycnf
func CreateMysqldAndMycnf(tabletUID uint32, mysqlSocket string, mysqlPort int32) (*Mysqld, *Mycnf, error) { mycnf := NewMycnf(tabletUID, mysqlPort) // Choose a random MySQL server-id, since this is a fresh data dir. // We don't want to use the tablet UID as the MySQL server-id, // because reusing server-ids is not safe. // // For example, if a tablet comes back with an empty data dir, it will restore // from backup and then connect to the master. But if this tablet has the same // server-id as before, and if this tablet was recently a master, then it can // lose data by skipping binlog events due to replicate-same-server-id=FALSE, // which is the default setting. if err := mycnf.RandomizeMysqlServerID(); err != nil { return nil, nil, fmt.Errorf("couldn't generate random MySQL server_id: %v", err) } if mysqlSocket != "" { mycnf.SocketFile = mysqlSocket } dbcfgs, err := dbconfigs.Init(mycnf.SocketFile) if err != nil { return nil, nil, fmt.Errorf("couldn't Init dbconfigs: %v", err) } return NewMysqld(dbcfgs), mycnf, nil }
go
func CreateMysqldAndMycnf(tabletUID uint32, mysqlSocket string, mysqlPort int32) (*Mysqld, *Mycnf, error) { mycnf := NewMycnf(tabletUID, mysqlPort) // Choose a random MySQL server-id, since this is a fresh data dir. // We don't want to use the tablet UID as the MySQL server-id, // because reusing server-ids is not safe. // // For example, if a tablet comes back with an empty data dir, it will restore // from backup and then connect to the master. But if this tablet has the same // server-id as before, and if this tablet was recently a master, then it can // lose data by skipping binlog events due to replicate-same-server-id=FALSE, // which is the default setting. if err := mycnf.RandomizeMysqlServerID(); err != nil { return nil, nil, fmt.Errorf("couldn't generate random MySQL server_id: %v", err) } if mysqlSocket != "" { mycnf.SocketFile = mysqlSocket } dbcfgs, err := dbconfigs.Init(mycnf.SocketFile) if err != nil { return nil, nil, fmt.Errorf("couldn't Init dbconfigs: %v", err) } return NewMysqld(dbcfgs), mycnf, nil }
[ "func", "CreateMysqldAndMycnf", "(", "tabletUID", "uint32", ",", "mysqlSocket", "string", ",", "mysqlPort", "int32", ")", "(", "*", "Mysqld", ",", "*", "Mycnf", ",", "error", ")", "{", "mycnf", ":=", "NewMycnf", "(", "tabletUID", ",", "mysqlPort", ")", "\n", "// Choose a random MySQL server-id, since this is a fresh data dir.", "// We don't want to use the tablet UID as the MySQL server-id,", "// because reusing server-ids is not safe.", "//", "// For example, if a tablet comes back with an empty data dir, it will restore", "// from backup and then connect to the master. But if this tablet has the same", "// server-id as before, and if this tablet was recently a master, then it can", "// lose data by skipping binlog events due to replicate-same-server-id=FALSE,", "// which is the default setting.", "if", "err", ":=", "mycnf", ".", "RandomizeMysqlServerID", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "mysqlSocket", "!=", "\"", "\"", "{", "mycnf", ".", "SocketFile", "=", "mysqlSocket", "\n", "}", "\n\n", "dbcfgs", ",", "err", ":=", "dbconfigs", ".", "Init", "(", "mycnf", ".", "SocketFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "NewMysqld", "(", "dbcfgs", ")", ",", "mycnf", ",", "nil", "\n", "}" ]
// CreateMysqldAndMycnf returns a Mysqld and a Mycnf object to use for working with a MySQL // installation that hasn't been set up yet.
[ "CreateMysqldAndMycnf", "returns", "a", "Mysqld", "and", "a", "Mycnf", "object", "to", "use", "for", "working", "with", "a", "MySQL", "installation", "that", "hasn", "t", "been", "set", "up", "yet", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/cmd.go#L31-L55
train
vitessio/vitess
go/vt/mysqlctl/cmd.go
OpenMysqldAndMycnf
func OpenMysqldAndMycnf(tabletUID uint32) (*Mysqld, *Mycnf, error) { // We pass a port of 0, this will be read and overwritten from the path on disk mycnf, err := ReadMycnf(NewMycnf(tabletUID, 0)) if err != nil { return nil, nil, fmt.Errorf("couldn't read my.cnf file: %v", err) } dbcfgs, err := dbconfigs.Init(mycnf.SocketFile) if err != nil { return nil, nil, fmt.Errorf("couldn't Init dbconfigs: %v", err) } return NewMysqld(dbcfgs), mycnf, nil }
go
func OpenMysqldAndMycnf(tabletUID uint32) (*Mysqld, *Mycnf, error) { // We pass a port of 0, this will be read and overwritten from the path on disk mycnf, err := ReadMycnf(NewMycnf(tabletUID, 0)) if err != nil { return nil, nil, fmt.Errorf("couldn't read my.cnf file: %v", err) } dbcfgs, err := dbconfigs.Init(mycnf.SocketFile) if err != nil { return nil, nil, fmt.Errorf("couldn't Init dbconfigs: %v", err) } return NewMysqld(dbcfgs), mycnf, nil }
[ "func", "OpenMysqldAndMycnf", "(", "tabletUID", "uint32", ")", "(", "*", "Mysqld", ",", "*", "Mycnf", ",", "error", ")", "{", "// We pass a port of 0, this will be read and overwritten from the path on disk", "mycnf", ",", "err", ":=", "ReadMycnf", "(", "NewMycnf", "(", "tabletUID", ",", "0", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "dbcfgs", ",", "err", ":=", "dbconfigs", ".", "Init", "(", "mycnf", ".", "SocketFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "NewMysqld", "(", "dbcfgs", ")", ",", "mycnf", ",", "nil", "\n", "}" ]
// OpenMysqldAndMycnf returns a Mysqld and a Mycnf object to use for working with a MySQL // installation that already exists. The Mycnf will be built based on the my.cnf file // of the MySQL instance.
[ "OpenMysqldAndMycnf", "returns", "a", "Mysqld", "and", "a", "Mycnf", "object", "to", "use", "for", "working", "with", "a", "MySQL", "installation", "that", "already", "exists", ".", "The", "Mycnf", "will", "be", "built", "based", "on", "the", "my", ".", "cnf", "file", "of", "the", "MySQL", "instance", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/cmd.go#L60-L73
train
vitessio/vitess
go/vt/callinfo/callinfo.go
NewContext
func NewContext(ctx context.Context, ci CallInfo) context.Context { return context.WithValue(ctx, callInfoKey, ci) }
go
func NewContext(ctx context.Context, ci CallInfo) context.Context { return context.WithValue(ctx, callInfoKey, ci) }
[ "func", "NewContext", "(", "ctx", "context", ".", "Context", ",", "ci", "CallInfo", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "ctx", ",", "callInfoKey", ",", "ci", ")", "\n", "}" ]
// NewContext adds the provided CallInfo to the context
[ "NewContext", "adds", "the", "provided", "CallInfo", "to", "the", "context" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/callinfo/callinfo.go#L48-L50
train
vitessio/vitess
go/vt/callinfo/callinfo.go
FromContext
func FromContext(ctx context.Context) (CallInfo, bool) { ci, ok := ctx.Value(callInfoKey).(CallInfo) return ci, ok }
go
func FromContext(ctx context.Context) (CallInfo, bool) { ci, ok := ctx.Value(callInfoKey).(CallInfo) return ci, ok }
[ "func", "FromContext", "(", "ctx", "context", ".", "Context", ")", "(", "CallInfo", ",", "bool", ")", "{", "ci", ",", "ok", ":=", "ctx", ".", "Value", "(", "callInfoKey", ")", ".", "(", "CallInfo", ")", "\n", "return", "ci", ",", "ok", "\n", "}" ]
// FromContext returns the CallInfo value stored in ctx, if any.
[ "FromContext", "returns", "the", "CallInfo", "value", "stored", "in", "ctx", "if", "any", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/callinfo/callinfo.go#L53-L56
train
vitessio/vitess
go/vt/vttablet/tabletserver/splitquery/split_params.go
getPrimaryKeyColumns
func getPrimaryKeyColumns(table *schema.Table) []*schema.TableColumn { result := make([]*schema.TableColumn, 0, len(table.PKColumns)) for _, pkColIndex := range table.PKColumns { result = append(result, &table.Columns[pkColIndex]) } return result }
go
func getPrimaryKeyColumns(table *schema.Table) []*schema.TableColumn { result := make([]*schema.TableColumn, 0, len(table.PKColumns)) for _, pkColIndex := range table.PKColumns { result = append(result, &table.Columns[pkColIndex]) } return result }
[ "func", "getPrimaryKeyColumns", "(", "table", "*", "schema", ".", "Table", ")", "[", "]", "*", "schema", ".", "TableColumn", "{", "result", ":=", "make", "(", "[", "]", "*", "schema", ".", "TableColumn", ",", "0", ",", "len", "(", "table", ".", "PKColumns", ")", ")", "\n", "for", "_", ",", "pkColIndex", ":=", "range", "table", ".", "PKColumns", "{", "result", "=", "append", "(", "result", ",", "&", "table", ".", "Columns", "[", "pkColIndex", "]", ")", "\n", "}", "\n", "return", "result", "\n", "}" ]
// getPrimaryKeyColumns returns the list of primary-key column names, in order, for the // given table.
[ "getPrimaryKeyColumns", "returns", "the", "list", "of", "primary", "-", "key", "column", "names", "in", "order", "for", "the", "given", "table", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/splitquery/split_params.go#L237-L243
train
vitessio/vitess
go/vt/vttablet/tabletserver/splitquery/split_params.go
areColumnsAPrefixOfAnIndex
func areColumnsAPrefixOfAnIndex(columns []*schema.TableColumn, table *schema.Table) bool { for _, index := range table.Indexes { if areColumnsAPrefixOfIndex(columns, index) { return true } } return false }
go
func areColumnsAPrefixOfAnIndex(columns []*schema.TableColumn, table *schema.Table) bool { for _, index := range table.Indexes { if areColumnsAPrefixOfIndex(columns, index) { return true } } return false }
[ "func", "areColumnsAPrefixOfAnIndex", "(", "columns", "[", "]", "*", "schema", ".", "TableColumn", ",", "table", "*", "schema", ".", "Table", ")", "bool", "{", "for", "_", ",", "index", ":=", "range", "table", ".", "Indexes", "{", "if", "areColumnsAPrefixOfIndex", "(", "columns", ",", "index", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// areColumnsAPrefixOfAnIndex returns true if 'columns' form a prefix of the columns that // make up some index in 'table'.
[ "areColumnsAPrefixOfAnIndex", "returns", "true", "if", "columns", "form", "a", "prefix", "of", "the", "columns", "that", "make", "up", "some", "index", "in", "table", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/splitquery/split_params.go#L247-L254
train
vitessio/vitess
go/vt/vttablet/tabletserver/splitquery/split_params.go
areColumnsAPrefixOfIndex
func areColumnsAPrefixOfIndex(potentialPrefix []*schema.TableColumn, index *schema.Index) bool { if len(potentialPrefix) > len(index.Columns) { return false } for i := range potentialPrefix { if !potentialPrefix[i].Name.Equal(index.Columns[i]) { return false } } return true }
go
func areColumnsAPrefixOfIndex(potentialPrefix []*schema.TableColumn, index *schema.Index) bool { if len(potentialPrefix) > len(index.Columns) { return false } for i := range potentialPrefix { if !potentialPrefix[i].Name.Equal(index.Columns[i]) { return false } } return true }
[ "func", "areColumnsAPrefixOfIndex", "(", "potentialPrefix", "[", "]", "*", "schema", ".", "TableColumn", ",", "index", "*", "schema", ".", "Index", ")", "bool", "{", "if", "len", "(", "potentialPrefix", ")", ">", "len", "(", "index", ".", "Columns", ")", "{", "return", "false", "\n", "}", "\n", "for", "i", ":=", "range", "potentialPrefix", "{", "if", "!", "potentialPrefix", "[", "i", "]", ".", "Name", ".", "Equal", "(", "index", ".", "Columns", "[", "i", "]", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// areColumnsAPrefixOfIndex returns true if 'potentialPrefix' forms a prefix of the columns // composing 'index'.
[ "areColumnsAPrefixOfIndex", "returns", "true", "if", "potentialPrefix", "forms", "a", "prefix", "of", "the", "columns", "composing", "index", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/splitquery/split_params.go#L258-L268
train
vitessio/vitess
go/vt/vttablet/tabletserver/splitquery/split_params.go
areSplitColumnsPrimaryKey
func (sp *SplitParams) areSplitColumnsPrimaryKey() bool { pkCols := getPrimaryKeyColumns(sp.splitTableSchema) if len(sp.splitColumns) != len(pkCols) { return false } // Compare the names of sp.splitColumns to the names of pkCols. for i := 0; i < len(sp.splitColumns); i++ { if !sp.splitColumns[i].Name.Equal(pkCols[i].Name) { return false } } return true }
go
func (sp *SplitParams) areSplitColumnsPrimaryKey() bool { pkCols := getPrimaryKeyColumns(sp.splitTableSchema) if len(sp.splitColumns) != len(pkCols) { return false } // Compare the names of sp.splitColumns to the names of pkCols. for i := 0; i < len(sp.splitColumns); i++ { if !sp.splitColumns[i].Name.Equal(pkCols[i].Name) { return false } } return true }
[ "func", "(", "sp", "*", "SplitParams", ")", "areSplitColumnsPrimaryKey", "(", ")", "bool", "{", "pkCols", ":=", "getPrimaryKeyColumns", "(", "sp", ".", "splitTableSchema", ")", "\n", "if", "len", "(", "sp", ".", "splitColumns", ")", "!=", "len", "(", "pkCols", ")", "{", "return", "false", "\n", "}", "\n", "// Compare the names of sp.splitColumns to the names of pkCols.", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "sp", ".", "splitColumns", ")", ";", "i", "++", "{", "if", "!", "sp", ".", "splitColumns", "[", "i", "]", ".", "Name", ".", "Equal", "(", "pkCols", "[", "i", "]", ".", "Name", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// areSplitColumnsPrimaryKey returns true if the splitColumns in 'splitParams' // are the primary key columns in order.
[ "areSplitColumnsPrimaryKey", "returns", "true", "if", "the", "splitColumns", "in", "splitParams", "are", "the", "primary", "key", "columns", "in", "order", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/splitquery/split_params.go#L272-L284
train