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/tabletmanager/rpc_server.go
HandleRPCPanic
func (agent *ActionAgent) HandleRPCPanic(ctx context.Context, name string, args, reply interface{}, verbose bool, err *error) { // panic handling if x := recover(); x != nil { log.Errorf("TabletManager.%v(%v) on %v panic: %v\n%s", name, args, topoproto.TabletAliasString(agent.TabletAlias), x, tb.Stack(4)) *err = fmt.Errorf("caught panic during %v: %v", name, x) return } // quick check for fast path if !verbose && *err == nil { return } // we gotta log something, get the source from := "" ci, ok := callinfo.FromContext(ctx) if ok { from = ci.Text() } if *err != nil { // error case log.Warningf("TabletManager.%v(%v)(on %v from %v) error: %v", name, args, topoproto.TabletAliasString(agent.TabletAlias), from, (*err).Error()) *err = vterrors.Wrapf(*err, "TabletManager.%v on %v error: %v", name, topoproto.TabletAliasString(agent.TabletAlias), (*err).Error()) } else { // success case log.Infof("TabletManager.%v(%v)(on %v from %v): %#v", name, args, topoproto.TabletAliasString(agent.TabletAlias), from, reply) } }
go
func (agent *ActionAgent) HandleRPCPanic(ctx context.Context, name string, args, reply interface{}, verbose bool, err *error) { // panic handling if x := recover(); x != nil { log.Errorf("TabletManager.%v(%v) on %v panic: %v\n%s", name, args, topoproto.TabletAliasString(agent.TabletAlias), x, tb.Stack(4)) *err = fmt.Errorf("caught panic during %v: %v", name, x) return } // quick check for fast path if !verbose && *err == nil { return } // we gotta log something, get the source from := "" ci, ok := callinfo.FromContext(ctx) if ok { from = ci.Text() } if *err != nil { // error case log.Warningf("TabletManager.%v(%v)(on %v from %v) error: %v", name, args, topoproto.TabletAliasString(agent.TabletAlias), from, (*err).Error()) *err = vterrors.Wrapf(*err, "TabletManager.%v on %v error: %v", name, topoproto.TabletAliasString(agent.TabletAlias), (*err).Error()) } else { // success case log.Infof("TabletManager.%v(%v)(on %v from %v): %#v", name, args, topoproto.TabletAliasString(agent.TabletAlias), from, reply) } }
[ "func", "(", "agent", "*", "ActionAgent", ")", "HandleRPCPanic", "(", "ctx", "context", ".", "Context", ",", "name", "string", ",", "args", ",", "reply", "interface", "{", "}", ",", "verbose", "bool", ",", "err", "*", "error", ")", "{", "// panic handling", "if", "x", ":=", "recover", "(", ")", ";", "x", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "name", ",", "args", ",", "topoproto", ".", "TabletAliasString", "(", "agent", ".", "TabletAlias", ")", ",", "x", ",", "tb", ".", "Stack", "(", "4", ")", ")", "\n", "*", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "x", ")", "\n", "return", "\n", "}", "\n\n", "// quick check for fast path", "if", "!", "verbose", "&&", "*", "err", "==", "nil", "{", "return", "\n", "}", "\n\n", "// we gotta log something, get the source", "from", ":=", "\"", "\"", "\n", "ci", ",", "ok", ":=", "callinfo", ".", "FromContext", "(", "ctx", ")", "\n", "if", "ok", "{", "from", "=", "ci", ".", "Text", "(", ")", "\n", "}", "\n\n", "if", "*", "err", "!=", "nil", "{", "// error case", "log", ".", "Warningf", "(", "\"", "\"", ",", "name", ",", "args", ",", "topoproto", ".", "TabletAliasString", "(", "agent", ".", "TabletAlias", ")", ",", "from", ",", "(", "*", "err", ")", ".", "Error", "(", ")", ")", "\n", "*", "err", "=", "vterrors", ".", "Wrapf", "(", "*", "err", ",", "\"", "\"", ",", "name", ",", "topoproto", ".", "TabletAliasString", "(", "agent", ".", "TabletAlias", ")", ",", "(", "*", "err", ")", ".", "Error", "(", ")", ")", "\n", "}", "else", "{", "// success case", "log", ".", "Infof", "(", "\"", "\"", ",", "name", ",", "args", ",", "topoproto", ".", "TabletAliasString", "(", "agent", ".", "TabletAlias", ")", ",", "from", ",", "reply", ")", "\n", "}", "\n", "}" ]
// HandleRPCPanic is part of the RPCAgent interface.
[ "HandleRPCPanic", "is", "part", "of", "the", "RPCAgent", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/rpc_server.go#L69-L97
train
vitessio/vitess
go/vt/discovery/tablet_stats_cache.go
NewTabletStatsCache
func NewTabletStatsCache(hc HealthCheck, ts *topo.Server, cell string) *TabletStatsCache { return newTabletStatsCache(hc, ts, cell, true /* setListener */) }
go
func NewTabletStatsCache(hc HealthCheck, ts *topo.Server, cell string) *TabletStatsCache { return newTabletStatsCache(hc, ts, cell, true /* setListener */) }
[ "func", "NewTabletStatsCache", "(", "hc", "HealthCheck", ",", "ts", "*", "topo", ".", "Server", ",", "cell", "string", ")", "*", "TabletStatsCache", "{", "return", "newTabletStatsCache", "(", "hc", ",", "ts", ",", "cell", ",", "true", "/* setListener */", ")", "\n", "}" ]
// NewTabletStatsCache creates a TabletStatsCache, and registers // it as HealthCheckStatsListener of the provided healthcheck. // Note we do the registration in this code to guarantee we call // SetListener with sendDownEvents=true, as we need these events // to maintain the integrity of our cache.
[ "NewTabletStatsCache", "creates", "a", "TabletStatsCache", "and", "registers", "it", "as", "HealthCheckStatsListener", "of", "the", "provided", "healthcheck", ".", "Note", "we", "do", "the", "registration", "in", "this", "code", "to", "guarantee", "we", "call", "SetListener", "with", "sendDownEvents", "=", "true", "as", "we", "need", "these", "events", "to", "maintain", "the", "integrity", "of", "our", "cache", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/tablet_stats_cache.go#L117-L119
train
vitessio/vitess
go/vt/discovery/tablet_stats_cache.go
getEntry
func (tc *TabletStatsCache) getEntry(keyspace, shard string, tabletType topodatapb.TabletType) *tabletStatsCacheEntry { tc.mu.RLock() defer tc.mu.RUnlock() if s, ok := tc.entries[keyspace]; ok { if t, ok := s[shard]; ok { if e, ok := t[tabletType]; ok { return e } } } return nil }
go
func (tc *TabletStatsCache) getEntry(keyspace, shard string, tabletType topodatapb.TabletType) *tabletStatsCacheEntry { tc.mu.RLock() defer tc.mu.RUnlock() if s, ok := tc.entries[keyspace]; ok { if t, ok := s[shard]; ok { if e, ok := t[tabletType]; ok { return e } } } return nil }
[ "func", "(", "tc", "*", "TabletStatsCache", ")", "getEntry", "(", "keyspace", ",", "shard", "string", ",", "tabletType", "topodatapb", ".", "TabletType", ")", "*", "tabletStatsCacheEntry", "{", "tc", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "tc", ".", "mu", ".", "RUnlock", "(", ")", "\n\n", "if", "s", ",", "ok", ":=", "tc", ".", "entries", "[", "keyspace", "]", ";", "ok", "{", "if", "t", ",", "ok", ":=", "s", "[", "shard", "]", ";", "ok", "{", "if", "e", ",", "ok", ":=", "t", "[", "tabletType", "]", ";", "ok", "{", "return", "e", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// getEntry returns an existing tabletStatsCacheEntry in the cache, or nil // if the entry does not exist. It only takes a Read lock on mu.
[ "getEntry", "returns", "an", "existing", "tabletStatsCacheEntry", "in", "the", "cache", "or", "nil", "if", "the", "entry", "does", "not", "exist", ".", "It", "only", "takes", "a", "Read", "lock", "on", "mu", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/tablet_stats_cache.go#L152-L164
train
vitessio/vitess
go/vt/discovery/tablet_stats_cache.go
getOrCreateEntry
func (tc *TabletStatsCache) getOrCreateEntry(target *querypb.Target) *tabletStatsCacheEntry { // Fast path (most common path too): Read-lock, return the entry. if e := tc.getEntry(target.Keyspace, target.Shard, target.TabletType); e != nil { return e } // Slow path: Lock, will probably have to add the entry at some level. tc.mu.Lock() defer tc.mu.Unlock() s, ok := tc.entries[target.Keyspace] if !ok { s = make(map[string]map[topodatapb.TabletType]*tabletStatsCacheEntry) tc.entries[target.Keyspace] = s } t, ok := s[target.Shard] if !ok { t = make(map[topodatapb.TabletType]*tabletStatsCacheEntry) s[target.Shard] = t } e, ok := t[target.TabletType] if !ok { e = &tabletStatsCacheEntry{ all: make(map[string]*TabletStats), aggregates: make(map[string]*querypb.AggregateStats), } t[target.TabletType] = e } return e }
go
func (tc *TabletStatsCache) getOrCreateEntry(target *querypb.Target) *tabletStatsCacheEntry { // Fast path (most common path too): Read-lock, return the entry. if e := tc.getEntry(target.Keyspace, target.Shard, target.TabletType); e != nil { return e } // Slow path: Lock, will probably have to add the entry at some level. tc.mu.Lock() defer tc.mu.Unlock() s, ok := tc.entries[target.Keyspace] if !ok { s = make(map[string]map[topodatapb.TabletType]*tabletStatsCacheEntry) tc.entries[target.Keyspace] = s } t, ok := s[target.Shard] if !ok { t = make(map[topodatapb.TabletType]*tabletStatsCacheEntry) s[target.Shard] = t } e, ok := t[target.TabletType] if !ok { e = &tabletStatsCacheEntry{ all: make(map[string]*TabletStats), aggregates: make(map[string]*querypb.AggregateStats), } t[target.TabletType] = e } return e }
[ "func", "(", "tc", "*", "TabletStatsCache", ")", "getOrCreateEntry", "(", "target", "*", "querypb", ".", "Target", ")", "*", "tabletStatsCacheEntry", "{", "// Fast path (most common path too): Read-lock, return the entry.", "if", "e", ":=", "tc", ".", "getEntry", "(", "target", ".", "Keyspace", ",", "target", ".", "Shard", ",", "target", ".", "TabletType", ")", ";", "e", "!=", "nil", "{", "return", "e", "\n", "}", "\n\n", "// Slow path: Lock, will probably have to add the entry at some level.", "tc", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "tc", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "s", ",", "ok", ":=", "tc", ".", "entries", "[", "target", ".", "Keyspace", "]", "\n", "if", "!", "ok", "{", "s", "=", "make", "(", "map", "[", "string", "]", "map", "[", "topodatapb", ".", "TabletType", "]", "*", "tabletStatsCacheEntry", ")", "\n", "tc", ".", "entries", "[", "target", ".", "Keyspace", "]", "=", "s", "\n", "}", "\n", "t", ",", "ok", ":=", "s", "[", "target", ".", "Shard", "]", "\n", "if", "!", "ok", "{", "t", "=", "make", "(", "map", "[", "topodatapb", ".", "TabletType", "]", "*", "tabletStatsCacheEntry", ")", "\n", "s", "[", "target", ".", "Shard", "]", "=", "t", "\n", "}", "\n", "e", ",", "ok", ":=", "t", "[", "target", ".", "TabletType", "]", "\n", "if", "!", "ok", "{", "e", "=", "&", "tabletStatsCacheEntry", "{", "all", ":", "make", "(", "map", "[", "string", "]", "*", "TabletStats", ")", ",", "aggregates", ":", "make", "(", "map", "[", "string", "]", "*", "querypb", ".", "AggregateStats", ")", ",", "}", "\n", "t", "[", "target", ".", "TabletType", "]", "=", "e", "\n", "}", "\n", "return", "e", "\n", "}" ]
// getOrCreateEntry returns an existing tabletStatsCacheEntry from the cache, // or creates it if it doesn't exist.
[ "getOrCreateEntry", "returns", "an", "existing", "tabletStatsCacheEntry", "from", "the", "cache", "or", "creates", "it", "if", "it", "doesn", "t", "exist", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/tablet_stats_cache.go#L168-L197
train
vitessio/vitess
go/vt/discovery/tablet_stats_cache.go
makeAggregateMap
func (tc *TabletStatsCache) makeAggregateMap(stats []*TabletStats) map[string]*querypb.AggregateStats { result := make(map[string]*querypb.AggregateStats) for _, ts := range stats { alias := tc.getAliasByCell(ts.Tablet.Alias.Cell) agg, ok := result[alias] if !ok { agg = &querypb.AggregateStats{ SecondsBehindMasterMin: math.MaxUint32, } result[alias] = agg } if ts.Serving && ts.LastError == nil { agg.HealthyTabletCount++ if ts.Stats.SecondsBehindMaster < agg.SecondsBehindMasterMin { agg.SecondsBehindMasterMin = ts.Stats.SecondsBehindMaster } if ts.Stats.SecondsBehindMaster > agg.SecondsBehindMasterMax { agg.SecondsBehindMasterMax = ts.Stats.SecondsBehindMaster } } else { agg.UnhealthyTabletCount++ } } return result }
go
func (tc *TabletStatsCache) makeAggregateMap(stats []*TabletStats) map[string]*querypb.AggregateStats { result := make(map[string]*querypb.AggregateStats) for _, ts := range stats { alias := tc.getAliasByCell(ts.Tablet.Alias.Cell) agg, ok := result[alias] if !ok { agg = &querypb.AggregateStats{ SecondsBehindMasterMin: math.MaxUint32, } result[alias] = agg } if ts.Serving && ts.LastError == nil { agg.HealthyTabletCount++ if ts.Stats.SecondsBehindMaster < agg.SecondsBehindMasterMin { agg.SecondsBehindMasterMin = ts.Stats.SecondsBehindMaster } if ts.Stats.SecondsBehindMaster > agg.SecondsBehindMasterMax { agg.SecondsBehindMasterMax = ts.Stats.SecondsBehindMaster } } else { agg.UnhealthyTabletCount++ } } return result }
[ "func", "(", "tc", "*", "TabletStatsCache", ")", "makeAggregateMap", "(", "stats", "[", "]", "*", "TabletStats", ")", "map", "[", "string", "]", "*", "querypb", ".", "AggregateStats", "{", "result", ":=", "make", "(", "map", "[", "string", "]", "*", "querypb", ".", "AggregateStats", ")", "\n", "for", "_", ",", "ts", ":=", "range", "stats", "{", "alias", ":=", "tc", ".", "getAliasByCell", "(", "ts", ".", "Tablet", ".", "Alias", ".", "Cell", ")", "\n", "agg", ",", "ok", ":=", "result", "[", "alias", "]", "\n", "if", "!", "ok", "{", "agg", "=", "&", "querypb", ".", "AggregateStats", "{", "SecondsBehindMasterMin", ":", "math", ".", "MaxUint32", ",", "}", "\n", "result", "[", "alias", "]", "=", "agg", "\n", "}", "\n\n", "if", "ts", ".", "Serving", "&&", "ts", ".", "LastError", "==", "nil", "{", "agg", ".", "HealthyTabletCount", "++", "\n", "if", "ts", ".", "Stats", ".", "SecondsBehindMaster", "<", "agg", ".", "SecondsBehindMasterMin", "{", "agg", ".", "SecondsBehindMasterMin", "=", "ts", ".", "Stats", ".", "SecondsBehindMaster", "\n", "}", "\n", "if", "ts", ".", "Stats", ".", "SecondsBehindMaster", ">", "agg", ".", "SecondsBehindMasterMax", "{", "agg", ".", "SecondsBehindMasterMax", "=", "ts", ".", "Stats", ".", "SecondsBehindMaster", "\n", "}", "\n", "}", "else", "{", "agg", ".", "UnhealthyTabletCount", "++", "\n", "}", "\n", "}", "\n", "return", "result", "\n", "}" ]
// makeAggregateMap takes a list of TabletStats and builds a per-alias // AggregateStats map.
[ "makeAggregateMap", "takes", "a", "list", "of", "TabletStats", "and", "builds", "a", "per", "-", "alias", "AggregateStats", "map", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/tablet_stats_cache.go#L285-L310
train
vitessio/vitess
go/vt/discovery/tablet_stats_cache.go
updateAggregateMap
func (tc *TabletStatsCache) updateAggregateMap(keyspace, shard string, tabletType topodatapb.TabletType, e *tabletStatsCacheEntry, stats []*TabletStats) { // Save the new value e.aggregates = tc.makeAggregateMap(stats) }
go
func (tc *TabletStatsCache) updateAggregateMap(keyspace, shard string, tabletType topodatapb.TabletType, e *tabletStatsCacheEntry, stats []*TabletStats) { // Save the new value e.aggregates = tc.makeAggregateMap(stats) }
[ "func", "(", "tc", "*", "TabletStatsCache", ")", "updateAggregateMap", "(", "keyspace", ",", "shard", "string", ",", "tabletType", "topodatapb", ".", "TabletType", ",", "e", "*", "tabletStatsCacheEntry", ",", "stats", "[", "]", "*", "TabletStats", ")", "{", "// Save the new value", "e", ".", "aggregates", "=", "tc", ".", "makeAggregateMap", "(", "stats", ")", "\n", "}" ]
// updateAggregateMap will update the aggregate map for the // tabletStatsCacheEntry. It may broadcast the changes too if we have listeners. // e.mu needs to be locked.
[ "updateAggregateMap", "will", "update", "the", "aggregate", "map", "for", "the", "tabletStatsCacheEntry", ".", "It", "may", "broadcast", "the", "changes", "too", "if", "we", "have", "listeners", ".", "e", ".", "mu", "needs", "to", "be", "locked", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/tablet_stats_cache.go#L315-L318
train
vitessio/vitess
go/vt/discovery/tablet_stats_cache.go
GetTabletStats
func (tc *TabletStatsCache) GetTabletStats(keyspace, shard string, tabletType topodatapb.TabletType) []TabletStats { e := tc.getEntry(keyspace, shard, tabletType) if e == nil { return nil } e.mu.RLock() defer e.mu.RUnlock() result := make([]TabletStats, 0, len(e.all)) for _, s := range e.all { result = append(result, *s) } return result }
go
func (tc *TabletStatsCache) GetTabletStats(keyspace, shard string, tabletType topodatapb.TabletType) []TabletStats { e := tc.getEntry(keyspace, shard, tabletType) if e == nil { return nil } e.mu.RLock() defer e.mu.RUnlock() result := make([]TabletStats, 0, len(e.all)) for _, s := range e.all { result = append(result, *s) } return result }
[ "func", "(", "tc", "*", "TabletStatsCache", ")", "GetTabletStats", "(", "keyspace", ",", "shard", "string", ",", "tabletType", "topodatapb", ".", "TabletType", ")", "[", "]", "TabletStats", "{", "e", ":=", "tc", ".", "getEntry", "(", "keyspace", ",", "shard", ",", "tabletType", ")", "\n", "if", "e", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "e", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "e", ".", "mu", ".", "RUnlock", "(", ")", "\n", "result", ":=", "make", "(", "[", "]", "TabletStats", ",", "0", ",", "len", "(", "e", ".", "all", ")", ")", "\n", "for", "_", ",", "s", ":=", "range", "e", ".", "all", "{", "result", "=", "append", "(", "result", ",", "*", "s", ")", "\n", "}", "\n", "return", "result", "\n", "}" ]
// GetTabletStats returns the full list of available targets. // The returned array is owned by the caller.
[ "GetTabletStats", "returns", "the", "full", "list", "of", "available", "targets", ".", "The", "returned", "array", "is", "owned", "by", "the", "caller", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/tablet_stats_cache.go#L322-L335
train
vitessio/vitess
go/vt/discovery/tablet_stats_cache.go
GetHealthyTabletStats
func (tc *TabletStatsCache) GetHealthyTabletStats(keyspace, shard string, tabletType topodatapb.TabletType) []TabletStats { e := tc.getEntry(keyspace, shard, tabletType) if e == nil { return nil } e.mu.RLock() defer e.mu.RUnlock() result := make([]TabletStats, len(e.healthy)) for i, ts := range e.healthy { result[i] = *ts } return result }
go
func (tc *TabletStatsCache) GetHealthyTabletStats(keyspace, shard string, tabletType topodatapb.TabletType) []TabletStats { e := tc.getEntry(keyspace, shard, tabletType) if e == nil { return nil } e.mu.RLock() defer e.mu.RUnlock() result := make([]TabletStats, len(e.healthy)) for i, ts := range e.healthy { result[i] = *ts } return result }
[ "func", "(", "tc", "*", "TabletStatsCache", ")", "GetHealthyTabletStats", "(", "keyspace", ",", "shard", "string", ",", "tabletType", "topodatapb", ".", "TabletType", ")", "[", "]", "TabletStats", "{", "e", ":=", "tc", ".", "getEntry", "(", "keyspace", ",", "shard", ",", "tabletType", ")", "\n", "if", "e", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "e", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "e", ".", "mu", ".", "RUnlock", "(", ")", "\n", "result", ":=", "make", "(", "[", "]", "TabletStats", ",", "len", "(", "e", ".", "healthy", ")", ")", "\n", "for", "i", ",", "ts", ":=", "range", "e", ".", "healthy", "{", "result", "[", "i", "]", "=", "*", "ts", "\n", "}", "\n", "return", "result", "\n", "}" ]
// GetHealthyTabletStats returns only the healthy targets. // The returned array is owned by the caller. // For TabletType_MASTER, this will only return at most one entry, // the most recent tablet of type master.
[ "GetHealthyTabletStats", "returns", "only", "the", "healthy", "targets", ".", "The", "returned", "array", "is", "owned", "by", "the", "caller", ".", "For", "TabletType_MASTER", "this", "will", "only", "return", "at", "most", "one", "entry", "the", "most", "recent", "tablet", "of", "type", "master", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/tablet_stats_cache.go#L341-L354
train
vitessio/vitess
go/vt/discovery/tablet_stats_cache.go
GetAggregateStats
func (tc *TabletStatsCache) GetAggregateStats(target *querypb.Target) (*querypb.AggregateStats, error) { e := tc.getEntry(target.Keyspace, target.Shard, target.TabletType) if e == nil { return nil, topo.NewError(topo.NoNode, topotools.TargetIdent(target)) } e.mu.RLock() defer e.mu.RUnlock() if target.TabletType == topodatapb.TabletType_MASTER { if len(e.aggregates) == 0 { return nil, topo.NewError(topo.NoNode, topotools.TargetIdent(target)) } for _, agg := range e.aggregates { return agg, nil } } targetAlias := tc.getAliasByCell(target.Cell) agg, ok := e.aggregates[targetAlias] if !ok { return nil, topo.NewError(topo.NoNode, topotools.TargetIdent(target)) } return agg, nil }
go
func (tc *TabletStatsCache) GetAggregateStats(target *querypb.Target) (*querypb.AggregateStats, error) { e := tc.getEntry(target.Keyspace, target.Shard, target.TabletType) if e == nil { return nil, topo.NewError(topo.NoNode, topotools.TargetIdent(target)) } e.mu.RLock() defer e.mu.RUnlock() if target.TabletType == topodatapb.TabletType_MASTER { if len(e.aggregates) == 0 { return nil, topo.NewError(topo.NoNode, topotools.TargetIdent(target)) } for _, agg := range e.aggregates { return agg, nil } } targetAlias := tc.getAliasByCell(target.Cell) agg, ok := e.aggregates[targetAlias] if !ok { return nil, topo.NewError(topo.NoNode, topotools.TargetIdent(target)) } return agg, nil }
[ "func", "(", "tc", "*", "TabletStatsCache", ")", "GetAggregateStats", "(", "target", "*", "querypb", ".", "Target", ")", "(", "*", "querypb", ".", "AggregateStats", ",", "error", ")", "{", "e", ":=", "tc", ".", "getEntry", "(", "target", ".", "Keyspace", ",", "target", ".", "Shard", ",", "target", ".", "TabletType", ")", "\n", "if", "e", "==", "nil", "{", "return", "nil", ",", "topo", ".", "NewError", "(", "topo", ".", "NoNode", ",", "topotools", ".", "TargetIdent", "(", "target", ")", ")", "\n", "}", "\n\n", "e", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "e", ".", "mu", ".", "RUnlock", "(", ")", "\n", "if", "target", ".", "TabletType", "==", "topodatapb", ".", "TabletType_MASTER", "{", "if", "len", "(", "e", ".", "aggregates", ")", "==", "0", "{", "return", "nil", ",", "topo", ".", "NewError", "(", "topo", ".", "NoNode", ",", "topotools", ".", "TargetIdent", "(", "target", ")", ")", "\n", "}", "\n", "for", "_", ",", "agg", ":=", "range", "e", ".", "aggregates", "{", "return", "agg", ",", "nil", "\n", "}", "\n", "}", "\n", "targetAlias", ":=", "tc", ".", "getAliasByCell", "(", "target", ".", "Cell", ")", "\n", "agg", ",", "ok", ":=", "e", ".", "aggregates", "[", "targetAlias", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "topo", ".", "NewError", "(", "topo", ".", "NoNode", ",", "topotools", ".", "TargetIdent", "(", "target", ")", ")", "\n", "}", "\n", "return", "agg", ",", "nil", "\n", "}" ]
// GetAggregateStats is part of the TargetStatsListener interface.
[ "GetAggregateStats", "is", "part", "of", "the", "TargetStatsListener", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/tablet_stats_cache.go#L365-L387
train
vitessio/vitess
go/vt/discovery/tablet_stats_cache.go
GetMasterCell
func (tc *TabletStatsCache) GetMasterCell(keyspace, shard string) (cell string, err error) { e := tc.getEntry(keyspace, shard, topodatapb.TabletType_MASTER) if e == nil { return "", topo.NewError(topo.NoNode, topotools.TargetIdent(&querypb.Target{ Keyspace: keyspace, Shard: shard, TabletType: topodatapb.TabletType_MASTER, })) } e.mu.RLock() defer e.mu.RUnlock() for cell := range e.aggregates { return cell, nil } return "", topo.NewError(topo.NoNode, topotools.TargetIdent(&querypb.Target{ Keyspace: keyspace, Shard: shard, TabletType: topodatapb.TabletType_MASTER, })) }
go
func (tc *TabletStatsCache) GetMasterCell(keyspace, shard string) (cell string, err error) { e := tc.getEntry(keyspace, shard, topodatapb.TabletType_MASTER) if e == nil { return "", topo.NewError(topo.NoNode, topotools.TargetIdent(&querypb.Target{ Keyspace: keyspace, Shard: shard, TabletType: topodatapb.TabletType_MASTER, })) } e.mu.RLock() defer e.mu.RUnlock() for cell := range e.aggregates { return cell, nil } return "", topo.NewError(topo.NoNode, topotools.TargetIdent(&querypb.Target{ Keyspace: keyspace, Shard: shard, TabletType: topodatapb.TabletType_MASTER, })) }
[ "func", "(", "tc", "*", "TabletStatsCache", ")", "GetMasterCell", "(", "keyspace", ",", "shard", "string", ")", "(", "cell", "string", ",", "err", "error", ")", "{", "e", ":=", "tc", ".", "getEntry", "(", "keyspace", ",", "shard", ",", "topodatapb", ".", "TabletType_MASTER", ")", "\n", "if", "e", "==", "nil", "{", "return", "\"", "\"", ",", "topo", ".", "NewError", "(", "topo", ".", "NoNode", ",", "topotools", ".", "TargetIdent", "(", "&", "querypb", ".", "Target", "{", "Keyspace", ":", "keyspace", ",", "Shard", ":", "shard", ",", "TabletType", ":", "topodatapb", ".", "TabletType_MASTER", ",", "}", ")", ")", "\n", "}", "\n\n", "e", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "e", ".", "mu", ".", "RUnlock", "(", ")", "\n", "for", "cell", ":=", "range", "e", ".", "aggregates", "{", "return", "cell", ",", "nil", "\n", "}", "\n", "return", "\"", "\"", ",", "topo", ".", "NewError", "(", "topo", ".", "NoNode", ",", "topotools", ".", "TargetIdent", "(", "&", "querypb", ".", "Target", "{", "Keyspace", ":", "keyspace", ",", "Shard", ":", "shard", ",", "TabletType", ":", "topodatapb", ".", "TabletType_MASTER", ",", "}", ")", ")", "\n", "}" ]
// GetMasterCell is part of the TargetStatsListener interface.
[ "GetMasterCell", "is", "part", "of", "the", "TargetStatsListener", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/tablet_stats_cache.go#L390-L410
train
vitessio/vitess
go/vt/key/destination.go
DestinationsString
func DestinationsString(destinations []Destination) string { var buffer bytes.Buffer buffer.WriteString("Destinations:") for i, d := range destinations { if i > 0 { buffer.WriteByte(',') } buffer.WriteString(d.String()) } return buffer.String() }
go
func DestinationsString(destinations []Destination) string { var buffer bytes.Buffer buffer.WriteString("Destinations:") for i, d := range destinations { if i > 0 { buffer.WriteByte(',') } buffer.WriteString(d.String()) } return buffer.String() }
[ "func", "DestinationsString", "(", "destinations", "[", "]", "Destination", ")", "string", "{", "var", "buffer", "bytes", ".", "Buffer", "\n", "buffer", ".", "WriteString", "(", "\"", "\"", ")", "\n", "for", "i", ",", "d", ":=", "range", "destinations", "{", "if", "i", ">", "0", "{", "buffer", ".", "WriteByte", "(", "','", ")", "\n", "}", "\n", "buffer", ".", "WriteString", "(", "d", ".", "String", "(", ")", ")", "\n", "}", "\n", "return", "buffer", ".", "String", "(", ")", "\n", "}" ]
// DestinationsString returns a printed version of the destination array.
[ "DestinationsString", "returns", "a", "printed", "version", "of", "the", "destination", "array", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/key/destination.go#L57-L67
train
vitessio/vitess
go/vt/key/destination.go
GetShardForKeyspaceID
func GetShardForKeyspaceID(allShards []*topodatapb.ShardReference, keyspaceID []byte) (string, error) { if len(allShards) == 0 { return "", vterrors.Errorf(vtrpcpb.Code_UNAVAILABLE, "no shard in keyspace") } for _, shardReference := range allShards { if KeyRangeContains(shardReference.KeyRange, keyspaceID) { return shardReference.Name, nil } } return "", vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "KeyspaceId %v didn't match any shards %+v", hex.EncodeToString(keyspaceID), allShards) }
go
func GetShardForKeyspaceID(allShards []*topodatapb.ShardReference, keyspaceID []byte) (string, error) { if len(allShards) == 0 { return "", vterrors.Errorf(vtrpcpb.Code_UNAVAILABLE, "no shard in keyspace") } for _, shardReference := range allShards { if KeyRangeContains(shardReference.KeyRange, keyspaceID) { return shardReference.Name, nil } } return "", vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "KeyspaceId %v didn't match any shards %+v", hex.EncodeToString(keyspaceID), allShards) }
[ "func", "GetShardForKeyspaceID", "(", "allShards", "[", "]", "*", "topodatapb", ".", "ShardReference", ",", "keyspaceID", "[", "]", "byte", ")", "(", "string", ",", "error", ")", "{", "if", "len", "(", "allShards", ")", "==", "0", "{", "return", "\"", "\"", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_UNAVAILABLE", ",", "\"", "\"", ")", "\n", "}", "\n\n", "for", "_", ",", "shardReference", ":=", "range", "allShards", "{", "if", "KeyRangeContains", "(", "shardReference", ".", "KeyRange", ",", "keyspaceID", ")", "{", "return", "shardReference", ".", "Name", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "hex", ".", "EncodeToString", "(", "keyspaceID", ")", ",", "allShards", ")", "\n", "}" ]
// GetShardForKeyspaceID finds the right shard for a keyspace id.
[ "GetShardForKeyspaceID", "finds", "the", "right", "shard", "for", "a", "keyspace", "id", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/key/destination.go#L322-L333
train
vitessio/vitess
go/memcache/memcache.go
Connect
func Connect(address string, timeout time.Duration) (conn *Connection, err error) { var network string if strings.Contains(address, "/") { network = "unix" } else { network = "tcp" } var nc net.Conn nc, err = net.DialTimeout(network, address, timeout) if err != nil { return nil, err } return &Connection{ conn: nc, buffered: bufio.ReadWriter{ Reader: bufio.NewReader(nc), Writer: bufio.NewWriter(nc), }, timeout: timeout, }, nil }
go
func Connect(address string, timeout time.Duration) (conn *Connection, err error) { var network string if strings.Contains(address, "/") { network = "unix" } else { network = "tcp" } var nc net.Conn nc, err = net.DialTimeout(network, address, timeout) if err != nil { return nil, err } return &Connection{ conn: nc, buffered: bufio.ReadWriter{ Reader: bufio.NewReader(nc), Writer: bufio.NewWriter(nc), }, timeout: timeout, }, nil }
[ "func", "Connect", "(", "address", "string", ",", "timeout", "time", ".", "Duration", ")", "(", "conn", "*", "Connection", ",", "err", "error", ")", "{", "var", "network", "string", "\n", "if", "strings", ".", "Contains", "(", "address", ",", "\"", "\"", ")", "{", "network", "=", "\"", "\"", "\n", "}", "else", "{", "network", "=", "\"", "\"", "\n", "}", "\n", "var", "nc", "net", ".", "Conn", "\n", "nc", ",", "err", "=", "net", ".", "DialTimeout", "(", "network", ",", "address", ",", "timeout", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Connection", "{", "conn", ":", "nc", ",", "buffered", ":", "bufio", ".", "ReadWriter", "{", "Reader", ":", "bufio", ".", "NewReader", "(", "nc", ")", ",", "Writer", ":", "bufio", ".", "NewWriter", "(", "nc", ")", ",", "}", ",", "timeout", ":", "timeout", ",", "}", ",", "nil", "\n", "}" ]
// Connect connects a memcache process.
[ "Connect", "connects", "a", "memcache", "process", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/memcache/memcache.go#L40-L60
train
vitessio/vitess
go/memcache/memcache.go
Get
func (mc *Connection) Get(keys ...string) (results []cacheservice.Result, err error) { defer handleError(&err) results = mc.get("get", keys) return }
go
func (mc *Connection) Get(keys ...string) (results []cacheservice.Result, err error) { defer handleError(&err) results = mc.get("get", keys) return }
[ "func", "(", "mc", "*", "Connection", ")", "Get", "(", "keys", "...", "string", ")", "(", "results", "[", "]", "cacheservice", ".", "Result", ",", "err", "error", ")", "{", "defer", "handleError", "(", "&", "err", ")", "\n", "results", "=", "mc", ".", "get", "(", "\"", "\"", ",", "keys", ")", "\n", "return", "\n", "}" ]
// Get returns cached data for given keys.
[ "Get", "returns", "cached", "data", "for", "given", "keys", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/memcache/memcache.go#L68-L72
train
vitessio/vitess
go/memcache/memcache.go
Set
func (mc *Connection) Set(key string, flags uint16, timeout uint64, value []byte) (stored bool, err error) { defer handleError(&err) return mc.store("set", key, flags, timeout, value, 0), nil }
go
func (mc *Connection) Set(key string, flags uint16, timeout uint64, value []byte) (stored bool, err error) { defer handleError(&err) return mc.store("set", key, flags, timeout, value, 0), nil }
[ "func", "(", "mc", "*", "Connection", ")", "Set", "(", "key", "string", ",", "flags", "uint16", ",", "timeout", "uint64", ",", "value", "[", "]", "byte", ")", "(", "stored", "bool", ",", "err", "error", ")", "{", "defer", "handleError", "(", "&", "err", ")", "\n", "return", "mc", ".", "store", "(", "\"", "\"", ",", "key", ",", "flags", ",", "timeout", ",", "value", ",", "0", ")", ",", "nil", "\n", "}" ]
// Set sets the value with specified cache key.
[ "Set", "sets", "the", "value", "with", "specified", "cache", "key", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/memcache/memcache.go#L84-L87
train
vitessio/vitess
go/memcache/memcache.go
Delete
func (mc *Connection) Delete(key string) (deleted bool, err error) { defer handleError(&err) mc.setDeadline() // delete <key> [<time>] [noreply]\r\n mc.writestrings("delete ", key, "\r\n") reply := mc.readline() if strings.Contains(reply, "ERROR") { panic(NewError("Server error")) } return strings.HasPrefix(reply, "DELETED"), nil }
go
func (mc *Connection) Delete(key string) (deleted bool, err error) { defer handleError(&err) mc.setDeadline() // delete <key> [<time>] [noreply]\r\n mc.writestrings("delete ", key, "\r\n") reply := mc.readline() if strings.Contains(reply, "ERROR") { panic(NewError("Server error")) } return strings.HasPrefix(reply, "DELETED"), nil }
[ "func", "(", "mc", "*", "Connection", ")", "Delete", "(", "key", "string", ")", "(", "deleted", "bool", ",", "err", "error", ")", "{", "defer", "handleError", "(", "&", "err", ")", "\n", "mc", ".", "setDeadline", "(", ")", "\n", "// delete <key> [<time>] [noreply]\\r\\n", "mc", ".", "writestrings", "(", "\"", "\"", ",", "key", ",", "\"", "\\r", "\\n", "\"", ")", "\n", "reply", ":=", "mc", ".", "readline", "(", ")", "\n", "if", "strings", ".", "Contains", "(", "reply", ",", "\"", "\"", ")", "{", "panic", "(", "NewError", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "strings", ".", "HasPrefix", "(", "reply", ",", "\"", "\"", ")", ",", "nil", "\n", "}" ]
// Delete deletes the value for the specified cache key.
[ "Delete", "deletes", "the", "value", "for", "the", "specified", "cache", "key", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/memcache/memcache.go#L121-L131
train
vitessio/vitess
go/memcache/memcache.go
FlushAll
func (mc *Connection) FlushAll() (err error) { defer handleError(&err) mc.setDeadline() // flush_all [delay] [noreply]\r\n mc.writestrings("flush_all\r\n") response := mc.readline() if !strings.Contains(response, "OK") { panic(NewError(fmt.Sprintf("Error in FlushAll %v", response))) } return nil }
go
func (mc *Connection) FlushAll() (err error) { defer handleError(&err) mc.setDeadline() // flush_all [delay] [noreply]\r\n mc.writestrings("flush_all\r\n") response := mc.readline() if !strings.Contains(response, "OK") { panic(NewError(fmt.Sprintf("Error in FlushAll %v", response))) } return nil }
[ "func", "(", "mc", "*", "Connection", ")", "FlushAll", "(", ")", "(", "err", "error", ")", "{", "defer", "handleError", "(", "&", "err", ")", "\n", "mc", ".", "setDeadline", "(", ")", "\n", "// flush_all [delay] [noreply]\\r\\n", "mc", ".", "writestrings", "(", "\"", "\\r", "\\n", "\"", ")", "\n", "response", ":=", "mc", ".", "readline", "(", ")", "\n", "if", "!", "strings", ".", "Contains", "(", "response", ",", "\"", "\"", ")", "{", "panic", "(", "NewError", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "response", ")", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// FlushAll purges the entire cache.
[ "FlushAll", "purges", "the", "entire", "cache", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/memcache/memcache.go#L134-L144
train
vitessio/vitess
go/memcache/memcache.go
Stats
func (mc *Connection) Stats(argument string) (result []byte, err error) { defer handleError(&err) mc.setDeadline() if argument == "" { mc.writestrings("stats\r\n") } else { mc.writestrings("stats ", argument, "\r\n") } mc.flush() for { l := mc.readline() if strings.HasPrefix(l, "END") { break } if strings.Contains(l, "ERROR") { return nil, NewError(l) } result = append(result, l...) result = append(result, '\n') } return result, err }
go
func (mc *Connection) Stats(argument string) (result []byte, err error) { defer handleError(&err) mc.setDeadline() if argument == "" { mc.writestrings("stats\r\n") } else { mc.writestrings("stats ", argument, "\r\n") } mc.flush() for { l := mc.readline() if strings.HasPrefix(l, "END") { break } if strings.Contains(l, "ERROR") { return nil, NewError(l) } result = append(result, l...) result = append(result, '\n') } return result, err }
[ "func", "(", "mc", "*", "Connection", ")", "Stats", "(", "argument", "string", ")", "(", "result", "[", "]", "byte", ",", "err", "error", ")", "{", "defer", "handleError", "(", "&", "err", ")", "\n", "mc", ".", "setDeadline", "(", ")", "\n", "if", "argument", "==", "\"", "\"", "{", "mc", ".", "writestrings", "(", "\"", "\\r", "\\n", "\"", ")", "\n", "}", "else", "{", "mc", ".", "writestrings", "(", "\"", "\"", ",", "argument", ",", "\"", "\\r", "\\n", "\"", ")", "\n", "}", "\n", "mc", ".", "flush", "(", ")", "\n", "for", "{", "l", ":=", "mc", ".", "readline", "(", ")", "\n", "if", "strings", ".", "HasPrefix", "(", "l", ",", "\"", "\"", ")", "{", "break", "\n", "}", "\n", "if", "strings", ".", "Contains", "(", "l", ",", "\"", "\"", ")", "{", "return", "nil", ",", "NewError", "(", "l", ")", "\n", "}", "\n", "result", "=", "append", "(", "result", ",", "l", "...", ")", "\n", "result", "=", "append", "(", "result", ",", "'\\n'", ")", "\n", "}", "\n", "return", "result", ",", "err", "\n", "}" ]
// Stats returns a list of basic stats.
[ "Stats", "returns", "a", "list", "of", "basic", "stats", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/memcache/memcache.go#L147-L168
train
vitessio/vitess
go/vt/topo/etcd2topo/lock.go
newUniqueEphemeralKV
func (s *Server) newUniqueEphemeralKV(ctx context.Context, cli *clientv3.Client, leaseID clientv3.LeaseID, nodePath string, contents string) (string, int64, error) { // Use the lease ID as the file name, so it's guaranteed unique. newKey := fmt.Sprintf("%v/%v", nodePath, leaseID) // Only create a new file if it doesn't exist already // (version = 0), to avoid two processes using the // same file name. Since we use the lease ID, this should never happen. txnresp, err := cli.Txn(ctx). If(clientv3.Compare(clientv3.Version(newKey), "=", 0)). Then(clientv3.OpPut(newKey, contents, clientv3.WithLease(leaseID))). Commit() if err != nil { if err == context.Canceled || err == context.DeadlineExceeded { // Our context was canceled as we were sending // a creation request. We don't know if it // succeeded or not. In any case, let's try to // delete the node, so we don't leave an orphan // node behind for *leaseTTL time. cli.Delete(context.Background(), newKey) } return "", 0, convertError(err, newKey) } if !txnresp.Succeeded { // The key already exists, that should not happen. return "", 0, ErrBadResponse } // The key was created. return newKey, txnresp.Header.Revision, nil }
go
func (s *Server) newUniqueEphemeralKV(ctx context.Context, cli *clientv3.Client, leaseID clientv3.LeaseID, nodePath string, contents string) (string, int64, error) { // Use the lease ID as the file name, so it's guaranteed unique. newKey := fmt.Sprintf("%v/%v", nodePath, leaseID) // Only create a new file if it doesn't exist already // (version = 0), to avoid two processes using the // same file name. Since we use the lease ID, this should never happen. txnresp, err := cli.Txn(ctx). If(clientv3.Compare(clientv3.Version(newKey), "=", 0)). Then(clientv3.OpPut(newKey, contents, clientv3.WithLease(leaseID))). Commit() if err != nil { if err == context.Canceled || err == context.DeadlineExceeded { // Our context was canceled as we were sending // a creation request. We don't know if it // succeeded or not. In any case, let's try to // delete the node, so we don't leave an orphan // node behind for *leaseTTL time. cli.Delete(context.Background(), newKey) } return "", 0, convertError(err, newKey) } if !txnresp.Succeeded { // The key already exists, that should not happen. return "", 0, ErrBadResponse } // The key was created. return newKey, txnresp.Header.Revision, nil }
[ "func", "(", "s", "*", "Server", ")", "newUniqueEphemeralKV", "(", "ctx", "context", ".", "Context", ",", "cli", "*", "clientv3", ".", "Client", ",", "leaseID", "clientv3", ".", "LeaseID", ",", "nodePath", "string", ",", "contents", "string", ")", "(", "string", ",", "int64", ",", "error", ")", "{", "// Use the lease ID as the file name, so it's guaranteed unique.", "newKey", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "nodePath", ",", "leaseID", ")", "\n\n", "// Only create a new file if it doesn't exist already", "// (version = 0), to avoid two processes using the", "// same file name. Since we use the lease ID, this should never happen.", "txnresp", ",", "err", ":=", "cli", ".", "Txn", "(", "ctx", ")", ".", "If", "(", "clientv3", ".", "Compare", "(", "clientv3", ".", "Version", "(", "newKey", ")", ",", "\"", "\"", ",", "0", ")", ")", ".", "Then", "(", "clientv3", ".", "OpPut", "(", "newKey", ",", "contents", ",", "clientv3", ".", "WithLease", "(", "leaseID", ")", ")", ")", ".", "Commit", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "context", ".", "Canceled", "||", "err", "==", "context", ".", "DeadlineExceeded", "{", "// Our context was canceled as we were sending", "// a creation request. We don't know if it", "// succeeded or not. In any case, let's try to", "// delete the node, so we don't leave an orphan", "// node behind for *leaseTTL time.", "cli", ".", "Delete", "(", "context", ".", "Background", "(", ")", ",", "newKey", ")", "\n", "}", "\n", "return", "\"", "\"", ",", "0", ",", "convertError", "(", "err", ",", "newKey", ")", "\n", "}", "\n", "if", "!", "txnresp", ".", "Succeeded", "{", "// The key already exists, that should not happen.", "return", "\"", "\"", ",", "0", ",", "ErrBadResponse", "\n", "}", "\n", "// The key was created.", "return", "newKey", ",", "txnresp", ".", "Header", ".", "Revision", ",", "nil", "\n", "}" ]
// newUniqueEphemeralKV creates a new file in the provided directory. // It is linked to the Lease. // Errors returned are converted to topo errors.
[ "newUniqueEphemeralKV", "creates", "a", "new", "file", "in", "the", "provided", "directory", ".", "It", "is", "linked", "to", "the", "Lease", ".", "Errors", "returned", "are", "converted", "to", "topo", "errors", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/etcd2topo/lock.go#L41-L69
train
vitessio/vitess
go/vt/topo/etcd2topo/lock.go
waitOnLastRev
func (s *Server) waitOnLastRev(ctx context.Context, cli *clientv3.Client, nodePath string, revision int64) (bool, error) { // Get the keys that are blocking us, if any. opts := append(clientv3.WithLastRev(), clientv3.WithMaxModRev(revision-1)) lastKey, err := cli.Get(ctx, nodePath+"/", opts...) if err != nil { return false, convertError(err, nodePath) } if len(lastKey.Kvs) == 0 { // No older key, we're done waiting. return true, nil } // Wait for release on blocking key. Cancel the watch when we // exit this function. key := string(lastKey.Kvs[0].Key) ctx, cancel := context.WithCancel(ctx) defer cancel() wc := cli.Watch(ctx, key, clientv3.WithRev(revision)) if wc == nil { return false, vterrors.Errorf(vtrpc.Code_INTERNAL, "Watch failed") } select { case <-ctx.Done(): return false, convertError(ctx.Err(), nodePath) case wresp := <-wc: for _, ev := range wresp.Events { if ev.Type == mvccpb.DELETE { // There might still be older keys, // but not this one. return false, nil } } } // The Watch stopped, we're not sure if there are more items. return false, nil }
go
func (s *Server) waitOnLastRev(ctx context.Context, cli *clientv3.Client, nodePath string, revision int64) (bool, error) { // Get the keys that are blocking us, if any. opts := append(clientv3.WithLastRev(), clientv3.WithMaxModRev(revision-1)) lastKey, err := cli.Get(ctx, nodePath+"/", opts...) if err != nil { return false, convertError(err, nodePath) } if len(lastKey.Kvs) == 0 { // No older key, we're done waiting. return true, nil } // Wait for release on blocking key. Cancel the watch when we // exit this function. key := string(lastKey.Kvs[0].Key) ctx, cancel := context.WithCancel(ctx) defer cancel() wc := cli.Watch(ctx, key, clientv3.WithRev(revision)) if wc == nil { return false, vterrors.Errorf(vtrpc.Code_INTERNAL, "Watch failed") } select { case <-ctx.Done(): return false, convertError(ctx.Err(), nodePath) case wresp := <-wc: for _, ev := range wresp.Events { if ev.Type == mvccpb.DELETE { // There might still be older keys, // but not this one. return false, nil } } } // The Watch stopped, we're not sure if there are more items. return false, nil }
[ "func", "(", "s", "*", "Server", ")", "waitOnLastRev", "(", "ctx", "context", ".", "Context", ",", "cli", "*", "clientv3", ".", "Client", ",", "nodePath", "string", ",", "revision", "int64", ")", "(", "bool", ",", "error", ")", "{", "// Get the keys that are blocking us, if any.", "opts", ":=", "append", "(", "clientv3", ".", "WithLastRev", "(", ")", ",", "clientv3", ".", "WithMaxModRev", "(", "revision", "-", "1", ")", ")", "\n", "lastKey", ",", "err", ":=", "cli", ".", "Get", "(", "ctx", ",", "nodePath", "+", "\"", "\"", ",", "opts", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "convertError", "(", "err", ",", "nodePath", ")", "\n", "}", "\n", "if", "len", "(", "lastKey", ".", "Kvs", ")", "==", "0", "{", "// No older key, we're done waiting.", "return", "true", ",", "nil", "\n", "}", "\n\n", "// Wait for release on blocking key. Cancel the watch when we", "// exit this function.", "key", ":=", "string", "(", "lastKey", ".", "Kvs", "[", "0", "]", ".", "Key", ")", "\n", "ctx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "ctx", ")", "\n", "defer", "cancel", "(", ")", "\n", "wc", ":=", "cli", ".", "Watch", "(", "ctx", ",", "key", ",", "clientv3", ".", "WithRev", "(", "revision", ")", ")", "\n", "if", "wc", "==", "nil", "{", "return", "false", ",", "vterrors", ".", "Errorf", "(", "vtrpc", ".", "Code_INTERNAL", ",", "\"", "\"", ")", "\n", "}", "\n\n", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "false", ",", "convertError", "(", "ctx", ".", "Err", "(", ")", ",", "nodePath", ")", "\n", "case", "wresp", ":=", "<-", "wc", ":", "for", "_", ",", "ev", ":=", "range", "wresp", ".", "Events", "{", "if", "ev", ".", "Type", "==", "mvccpb", ".", "DELETE", "{", "// There might still be older keys,", "// but not this one.", "return", "false", ",", "nil", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// The Watch stopped, we're not sure if there are more items.", "return", "false", ",", "nil", "\n", "}" ]
// waitOnLastRev waits on all revisions of the files in the provided // directory that have revisions smaller than the provided revision. // It returns true only if there is no more other older files.
[ "waitOnLastRev", "waits", "on", "all", "revisions", "of", "the", "files", "in", "the", "provided", "directory", "that", "have", "revisions", "smaller", "than", "the", "provided", "revision", ".", "It", "returns", "true", "only", "if", "there", "is", "no", "more", "other", "older", "files", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/etcd2topo/lock.go#L74-L111
train
vitessio/vitess
go/vt/topo/etcd2topo/lock.go
Check
func (ld *etcdLockDescriptor) Check(ctx context.Context) error { _, err := ld.s.cli.KeepAliveOnce(ctx, ld.leaseID) if err != nil { return convertError(err, "lease") } return nil }
go
func (ld *etcdLockDescriptor) Check(ctx context.Context) error { _, err := ld.s.cli.KeepAliveOnce(ctx, ld.leaseID) if err != nil { return convertError(err, "lease") } return nil }
[ "func", "(", "ld", "*", "etcdLockDescriptor", ")", "Check", "(", "ctx", "context", ".", "Context", ")", "error", "{", "_", ",", "err", ":=", "ld", ".", "s", ".", "cli", ".", "KeepAliveOnce", "(", "ctx", ",", "ld", ".", "leaseID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "convertError", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Check is part of the topo.LockDescriptor interface. // We use KeepAliveOnce to make sure the lease is still active and well.
[ "Check", "is", "part", "of", "the", "topo", ".", "LockDescriptor", "interface", ".", "We", "use", "KeepAliveOnce", "to", "make", "sure", "the", "lease", "is", "still", "active", "and", "well", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/etcd2topo/lock.go#L183-L189
train
vitessio/vitess
go/vt/grpcclient/client_auth_static.go
GetRequestMetadata
func (c *StaticAuthClientCreds) GetRequestMetadata(context.Context, ...string) (map[string]string, error) { return map[string]string{ "username": c.Username, "password": c.Password, }, nil }
go
func (c *StaticAuthClientCreds) GetRequestMetadata(context.Context, ...string) (map[string]string, error) { return map[string]string{ "username": c.Username, "password": c.Password, }, nil }
[ "func", "(", "c", "*", "StaticAuthClientCreds", ")", "GetRequestMetadata", "(", "context", ".", "Context", ",", "...", "string", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "return", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "c", ".", "Username", ",", "\"", "\"", ":", "c", ".", "Password", ",", "}", ",", "nil", "\n", "}" ]
// GetRequestMetadata gets the request metadata as a map from StaticAuthClientCreds
[ "GetRequestMetadata", "gets", "the", "request", "metadata", "as", "a", "map", "from", "StaticAuthClientCreds" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/grpcclient/client_auth_static.go#L43-L48
train
vitessio/vitess
go/vt/grpcclient/client_auth_static.go
AppendStaticAuth
func AppendStaticAuth(opts []grpc.DialOption) ([]grpc.DialOption, error) { if *credsFile == "" { return opts, nil } data, err := ioutil.ReadFile(*credsFile) if err != nil { return nil, err } clientCreds := &StaticAuthClientCreds{} err = json.Unmarshal(data, clientCreds) if err != nil { return nil, err } creds := grpc.WithPerRPCCredentials(clientCreds) opts = append(opts, creds) return opts, nil }
go
func AppendStaticAuth(opts []grpc.DialOption) ([]grpc.DialOption, error) { if *credsFile == "" { return opts, nil } data, err := ioutil.ReadFile(*credsFile) if err != nil { return nil, err } clientCreds := &StaticAuthClientCreds{} err = json.Unmarshal(data, clientCreds) if err != nil { return nil, err } creds := grpc.WithPerRPCCredentials(clientCreds) opts = append(opts, creds) return opts, nil }
[ "func", "AppendStaticAuth", "(", "opts", "[", "]", "grpc", ".", "DialOption", ")", "(", "[", "]", "grpc", ".", "DialOption", ",", "error", ")", "{", "if", "*", "credsFile", "==", "\"", "\"", "{", "return", "opts", ",", "nil", "\n", "}", "\n", "data", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "*", "credsFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "clientCreds", ":=", "&", "StaticAuthClientCreds", "{", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "clientCreds", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "creds", ":=", "grpc", ".", "WithPerRPCCredentials", "(", "clientCreds", ")", "\n", "opts", "=", "append", "(", "opts", ",", "creds", ")", "\n", "return", "opts", ",", "nil", "\n", "}" ]
// AppendStaticAuth optionally appends static auth credentials if provided.
[ "AppendStaticAuth", "optionally", "appends", "static", "auth", "credentials", "if", "provided", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/grpcclient/client_auth_static.go#L58-L74
train
vitessio/vitess
go/vt/throttler/aggregated_interval_history.go
average
func (h *aggregatedIntervalHistory) average(from, to time.Time) float64 { sum := 0.0 for i := 0; i < h.threadCount; i++ { sum += h.historyPerThread[i].average(from, to) } return sum }
go
func (h *aggregatedIntervalHistory) average(from, to time.Time) float64 { sum := 0.0 for i := 0; i < h.threadCount; i++ { sum += h.historyPerThread[i].average(from, to) } return sum }
[ "func", "(", "h", "*", "aggregatedIntervalHistory", ")", "average", "(", "from", ",", "to", "time", ".", "Time", ")", "float64", "{", "sum", ":=", "0.0", "\n", "for", "i", ":=", "0", ";", "i", "<", "h", ".", "threadCount", ";", "i", "++", "{", "sum", "+=", "h", ".", "historyPerThread", "[", "i", "]", ".", "average", "(", "from", ",", "to", ")", "\n", "}", "\n", "return", "sum", "\n", "}" ]
// average aggregates the average of all intervalHistory instances.
[ "average", "aggregates", "the", "average", "of", "all", "intervalHistory", "instances", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/aggregated_interval_history.go#L47-L53
train
vitessio/vitess
go/vt/wrangler/shard.go
updateShardMaster
func (wr *Wrangler) updateShardMaster(ctx context.Context, si *topo.ShardInfo, tabletAlias *topodatapb.TabletAlias, tabletType topodatapb.TabletType, allowMasterOverride bool) error { // See if we need to update the Shard: // - add the tablet's cell to the shard's Cells if needed // - change the master if needed shardUpdateRequired := false if tabletType == topodatapb.TabletType_MASTER && !topoproto.TabletAliasEqual(si.MasterAlias, tabletAlias) { shardUpdateRequired = true } if !shardUpdateRequired { return nil } // run the update _, err := wr.ts.UpdateShardFields(ctx, si.Keyspace(), si.ShardName(), func(s *topo.ShardInfo) error { wasUpdated := false if tabletType == topodatapb.TabletType_MASTER && !topoproto.TabletAliasEqual(s.MasterAlias, tabletAlias) { if !topoproto.TabletAliasIsZero(s.MasterAlias) && !allowMasterOverride { return fmt.Errorf("creating this tablet would override old master %v in shard %v/%v", topoproto.TabletAliasString(s.MasterAlias), si.Keyspace(), si.ShardName()) } s.MasterAlias = tabletAlias wasUpdated = true } if !wasUpdated { return topo.NewError(topo.NoUpdateNeeded, si.Keyspace()+"/"+si.ShardName()) } return nil }) return err }
go
func (wr *Wrangler) updateShardMaster(ctx context.Context, si *topo.ShardInfo, tabletAlias *topodatapb.TabletAlias, tabletType topodatapb.TabletType, allowMasterOverride bool) error { // See if we need to update the Shard: // - add the tablet's cell to the shard's Cells if needed // - change the master if needed shardUpdateRequired := false if tabletType == topodatapb.TabletType_MASTER && !topoproto.TabletAliasEqual(si.MasterAlias, tabletAlias) { shardUpdateRequired = true } if !shardUpdateRequired { return nil } // run the update _, err := wr.ts.UpdateShardFields(ctx, si.Keyspace(), si.ShardName(), func(s *topo.ShardInfo) error { wasUpdated := false if tabletType == topodatapb.TabletType_MASTER && !topoproto.TabletAliasEqual(s.MasterAlias, tabletAlias) { if !topoproto.TabletAliasIsZero(s.MasterAlias) && !allowMasterOverride { return fmt.Errorf("creating this tablet would override old master %v in shard %v/%v", topoproto.TabletAliasString(s.MasterAlias), si.Keyspace(), si.ShardName()) } s.MasterAlias = tabletAlias wasUpdated = true } if !wasUpdated { return topo.NewError(topo.NoUpdateNeeded, si.Keyspace()+"/"+si.ShardName()) } return nil }) return err }
[ "func", "(", "wr", "*", "Wrangler", ")", "updateShardMaster", "(", "ctx", "context", ".", "Context", ",", "si", "*", "topo", ".", "ShardInfo", ",", "tabletAlias", "*", "topodatapb", ".", "TabletAlias", ",", "tabletType", "topodatapb", ".", "TabletType", ",", "allowMasterOverride", "bool", ")", "error", "{", "// See if we need to update the Shard:", "// - add the tablet's cell to the shard's Cells if needed", "// - change the master if needed", "shardUpdateRequired", ":=", "false", "\n", "if", "tabletType", "==", "topodatapb", ".", "TabletType_MASTER", "&&", "!", "topoproto", ".", "TabletAliasEqual", "(", "si", ".", "MasterAlias", ",", "tabletAlias", ")", "{", "shardUpdateRequired", "=", "true", "\n", "}", "\n", "if", "!", "shardUpdateRequired", "{", "return", "nil", "\n", "}", "\n\n", "// run the update", "_", ",", "err", ":=", "wr", ".", "ts", ".", "UpdateShardFields", "(", "ctx", ",", "si", ".", "Keyspace", "(", ")", ",", "si", ".", "ShardName", "(", ")", ",", "func", "(", "s", "*", "topo", ".", "ShardInfo", ")", "error", "{", "wasUpdated", ":=", "false", "\n\n", "if", "tabletType", "==", "topodatapb", ".", "TabletType_MASTER", "&&", "!", "topoproto", ".", "TabletAliasEqual", "(", "s", ".", "MasterAlias", ",", "tabletAlias", ")", "{", "if", "!", "topoproto", ".", "TabletAliasIsZero", "(", "s", ".", "MasterAlias", ")", "&&", "!", "allowMasterOverride", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "topoproto", ".", "TabletAliasString", "(", "s", ".", "MasterAlias", ")", ",", "si", ".", "Keyspace", "(", ")", ",", "si", ".", "ShardName", "(", ")", ")", "\n", "}", "\n", "s", ".", "MasterAlias", "=", "tabletAlias", "\n", "wasUpdated", "=", "true", "\n", "}", "\n\n", "if", "!", "wasUpdated", "{", "return", "topo", ".", "NewError", "(", "topo", ".", "NoUpdateNeeded", ",", "si", ".", "Keyspace", "(", ")", "+", "\"", "\"", "+", "si", ".", "ShardName", "(", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "return", "err", "\n", "}" ]
// shard related methods for Wrangler // updateShardCellsAndMaster will update the 'Cells' and possibly // MasterAlias records for the shard, if needed.
[ "shard", "related", "methods", "for", "Wrangler", "updateShardCellsAndMaster", "will", "update", "the", "Cells", "and", "possibly", "MasterAlias", "records", "for", "the", "shard", "if", "needed", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/shard.go#L33-L63
train
vitessio/vitess
go/vt/wrangler/shard.go
SetShardIsMasterServing
func (wr *Wrangler) SetShardIsMasterServing(ctx context.Context, keyspace, shard string, isMasterServing bool) (err error) { // lock the keyspace to not conflict with resharding operations ctx, unlock, lockErr := wr.ts.LockKeyspace(ctx, keyspace, fmt.Sprintf("SetShardIsMasterServing(%v,%v,%v)", keyspace, shard, isMasterServing)) if lockErr != nil { return lockErr } defer unlock(&err) // and update the shard _, err = wr.ts.UpdateShardFields(ctx, keyspace, shard, func(si *topo.ShardInfo) error { si.IsMasterServing = isMasterServing return nil }) return err }
go
func (wr *Wrangler) SetShardIsMasterServing(ctx context.Context, keyspace, shard string, isMasterServing bool) (err error) { // lock the keyspace to not conflict with resharding operations ctx, unlock, lockErr := wr.ts.LockKeyspace(ctx, keyspace, fmt.Sprintf("SetShardIsMasterServing(%v,%v,%v)", keyspace, shard, isMasterServing)) if lockErr != nil { return lockErr } defer unlock(&err) // and update the shard _, err = wr.ts.UpdateShardFields(ctx, keyspace, shard, func(si *topo.ShardInfo) error { si.IsMasterServing = isMasterServing return nil }) return err }
[ "func", "(", "wr", "*", "Wrangler", ")", "SetShardIsMasterServing", "(", "ctx", "context", ".", "Context", ",", "keyspace", ",", "shard", "string", ",", "isMasterServing", "bool", ")", "(", "err", "error", ")", "{", "// lock the keyspace to not conflict with resharding operations", "ctx", ",", "unlock", ",", "lockErr", ":=", "wr", ".", "ts", ".", "LockKeyspace", "(", "ctx", ",", "keyspace", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "keyspace", ",", "shard", ",", "isMasterServing", ")", ")", "\n", "if", "lockErr", "!=", "nil", "{", "return", "lockErr", "\n", "}", "\n", "defer", "unlock", "(", "&", "err", ")", "\n\n", "// and update the shard", "_", ",", "err", "=", "wr", ".", "ts", ".", "UpdateShardFields", "(", "ctx", ",", "keyspace", ",", "shard", ",", "func", "(", "si", "*", "topo", ".", "ShardInfo", ")", "error", "{", "si", ".", "IsMasterServing", "=", "isMasterServing", "\n", "return", "nil", "\n", "}", ")", "\n", "return", "err", "\n", "}" ]
// SetShardIsMasterServing changes the IsMasterServing parameter of a shard. // It does not rebuild any serving graph or do any consistency check. // This is an emergency manual operation.
[ "SetShardIsMasterServing", "changes", "the", "IsMasterServing", "parameter", "of", "a", "shard", ".", "It", "does", "not", "rebuild", "any", "serving", "graph", "or", "do", "any", "consistency", "check", ".", "This", "is", "an", "emergency", "manual", "operation", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/shard.go#L68-L82
train
vitessio/vitess
go/vt/wrangler/shard.go
SetShardTabletControl
func (wr *Wrangler) SetShardTabletControl(ctx context.Context, keyspace, shard string, tabletType topodatapb.TabletType, cells []string, remove bool, blacklistedTables []string) (err error) { // lock the keyspace ctx, unlock, lockErr := wr.ts.LockKeyspace(ctx, keyspace, "SetShardTabletControl") if lockErr != nil { return lockErr } defer unlock(&err) // update the shard _, err = wr.ts.UpdateShardFields(ctx, keyspace, shard, func(si *topo.ShardInfo) error { // we are setting / removing the blacklisted tables only return si.UpdateSourceBlacklistedTables(ctx, tabletType, cells, remove, blacklistedTables) }) return err }
go
func (wr *Wrangler) SetShardTabletControl(ctx context.Context, keyspace, shard string, tabletType topodatapb.TabletType, cells []string, remove bool, blacklistedTables []string) (err error) { // lock the keyspace ctx, unlock, lockErr := wr.ts.LockKeyspace(ctx, keyspace, "SetShardTabletControl") if lockErr != nil { return lockErr } defer unlock(&err) // update the shard _, err = wr.ts.UpdateShardFields(ctx, keyspace, shard, func(si *topo.ShardInfo) error { // we are setting / removing the blacklisted tables only return si.UpdateSourceBlacklistedTables(ctx, tabletType, cells, remove, blacklistedTables) }) return err }
[ "func", "(", "wr", "*", "Wrangler", ")", "SetShardTabletControl", "(", "ctx", "context", ".", "Context", ",", "keyspace", ",", "shard", "string", ",", "tabletType", "topodatapb", ".", "TabletType", ",", "cells", "[", "]", "string", ",", "remove", "bool", ",", "blacklistedTables", "[", "]", "string", ")", "(", "err", "error", ")", "{", "// lock the keyspace", "ctx", ",", "unlock", ",", "lockErr", ":=", "wr", ".", "ts", ".", "LockKeyspace", "(", "ctx", ",", "keyspace", ",", "\"", "\"", ")", "\n", "if", "lockErr", "!=", "nil", "{", "return", "lockErr", "\n", "}", "\n", "defer", "unlock", "(", "&", "err", ")", "\n\n", "// update the shard", "_", ",", "err", "=", "wr", ".", "ts", ".", "UpdateShardFields", "(", "ctx", ",", "keyspace", ",", "shard", ",", "func", "(", "si", "*", "topo", ".", "ShardInfo", ")", "error", "{", "// we are setting / removing the blacklisted tables only", "return", "si", ".", "UpdateSourceBlacklistedTables", "(", "ctx", ",", "tabletType", ",", "cells", ",", "remove", ",", "blacklistedTables", ")", "\n", "}", ")", "\n", "return", "err", "\n", "}" ]
// SetShardTabletControl changes the TabletControl records // for a shard. It does not rebuild any serving graph or do // cross-shard consistency check. // - sets black listed tables in tablet control record // // This takes the keyspace lock as to not interfere with resharding operations.
[ "SetShardTabletControl", "changes", "the", "TabletControl", "records", "for", "a", "shard", ".", "It", "does", "not", "rebuild", "any", "serving", "graph", "or", "do", "cross", "-", "shard", "consistency", "check", ".", "-", "sets", "black", "listed", "tables", "in", "tablet", "control", "record", "This", "takes", "the", "keyspace", "lock", "as", "to", "not", "interfere", "with", "resharding", "operations", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/shard.go#L90-L104
train
vitessio/vitess
go/vt/wrangler/shard.go
UpdateSrvKeyspacePartitions
func (wr *Wrangler) UpdateSrvKeyspacePartitions(ctx context.Context, keyspace, shard string, tabletType topodatapb.TabletType, cells []string, remove bool) (err error) { // lock the keyspace ctx, unlock, lockErr := wr.ts.LockKeyspace(ctx, keyspace, "UpdateSrvKeyspacePartitions") if lockErr != nil { return lockErr } defer unlock(&err) si, err := wr.ts.GetShard(ctx, keyspace, shard) if err != nil { return err } if remove { return wr.ts.DeleteSrvKeyspacePartitions(ctx, keyspace, []*topo.ShardInfo{si}, tabletType, cells) } return wr.ts.AddSrvKeyspacePartitions(ctx, keyspace, []*topo.ShardInfo{si}, tabletType, cells) }
go
func (wr *Wrangler) UpdateSrvKeyspacePartitions(ctx context.Context, keyspace, shard string, tabletType topodatapb.TabletType, cells []string, remove bool) (err error) { // lock the keyspace ctx, unlock, lockErr := wr.ts.LockKeyspace(ctx, keyspace, "UpdateSrvKeyspacePartitions") if lockErr != nil { return lockErr } defer unlock(&err) si, err := wr.ts.GetShard(ctx, keyspace, shard) if err != nil { return err } if remove { return wr.ts.DeleteSrvKeyspacePartitions(ctx, keyspace, []*topo.ShardInfo{si}, tabletType, cells) } return wr.ts.AddSrvKeyspacePartitions(ctx, keyspace, []*topo.ShardInfo{si}, tabletType, cells) }
[ "func", "(", "wr", "*", "Wrangler", ")", "UpdateSrvKeyspacePartitions", "(", "ctx", "context", ".", "Context", ",", "keyspace", ",", "shard", "string", ",", "tabletType", "topodatapb", ".", "TabletType", ",", "cells", "[", "]", "string", ",", "remove", "bool", ")", "(", "err", "error", ")", "{", "// lock the keyspace", "ctx", ",", "unlock", ",", "lockErr", ":=", "wr", ".", "ts", ".", "LockKeyspace", "(", "ctx", ",", "keyspace", ",", "\"", "\"", ")", "\n", "if", "lockErr", "!=", "nil", "{", "return", "lockErr", "\n", "}", "\n", "defer", "unlock", "(", "&", "err", ")", "\n\n", "si", ",", "err", ":=", "wr", ".", "ts", ".", "GetShard", "(", "ctx", ",", "keyspace", ",", "shard", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "remove", "{", "return", "wr", ".", "ts", ".", "DeleteSrvKeyspacePartitions", "(", "ctx", ",", "keyspace", ",", "[", "]", "*", "topo", ".", "ShardInfo", "{", "si", "}", ",", "tabletType", ",", "cells", ")", "\n", "}", "\n", "return", "wr", ".", "ts", ".", "AddSrvKeyspacePartitions", "(", "ctx", ",", "keyspace", ",", "[", "]", "*", "topo", ".", "ShardInfo", "{", "si", "}", ",", "tabletType", ",", "cells", ")", "\n", "}" ]
// UpdateSrvKeyspacePartitions changes the SrvKeyspaceGraph // for a shard. It updates serving graph // // This takes the keyspace lock as to not interfere with resharding operations.
[ "UpdateSrvKeyspacePartitions", "changes", "the", "SrvKeyspaceGraph", "for", "a", "shard", ".", "It", "updates", "serving", "graph", "This", "takes", "the", "keyspace", "lock", "as", "to", "not", "interfere", "with", "resharding", "operations", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/shard.go#L130-L147
train
vitessio/vitess
go/vt/wrangler/shard.go
SourceShardDelete
func (wr *Wrangler) SourceShardDelete(ctx context.Context, keyspace, shard string, uid uint32) (err error) { // lock the keyspace ctx, unlock, lockErr := wr.ts.LockKeyspace(ctx, keyspace, fmt.Sprintf("SourceShardDelete(%v)", uid)) if lockErr != nil { return lockErr } defer unlock(&err) // remove the source shard _, err = wr.ts.UpdateShardFields(ctx, keyspace, shard, func(si *topo.ShardInfo) error { var newSourceShards []*topodatapb.Shard_SourceShard for _, ss := range si.SourceShards { if ss.Uid != uid { newSourceShards = append(newSourceShards, ss) } } if len(newSourceShards) == len(si.SourceShards) { return fmt.Errorf("no SourceShard with uid %v", uid) } si.SourceShards = newSourceShards return nil }) return err }
go
func (wr *Wrangler) SourceShardDelete(ctx context.Context, keyspace, shard string, uid uint32) (err error) { // lock the keyspace ctx, unlock, lockErr := wr.ts.LockKeyspace(ctx, keyspace, fmt.Sprintf("SourceShardDelete(%v)", uid)) if lockErr != nil { return lockErr } defer unlock(&err) // remove the source shard _, err = wr.ts.UpdateShardFields(ctx, keyspace, shard, func(si *topo.ShardInfo) error { var newSourceShards []*topodatapb.Shard_SourceShard for _, ss := range si.SourceShards { if ss.Uid != uid { newSourceShards = append(newSourceShards, ss) } } if len(newSourceShards) == len(si.SourceShards) { return fmt.Errorf("no SourceShard with uid %v", uid) } si.SourceShards = newSourceShards return nil }) return err }
[ "func", "(", "wr", "*", "Wrangler", ")", "SourceShardDelete", "(", "ctx", "context", ".", "Context", ",", "keyspace", ",", "shard", "string", ",", "uid", "uint32", ")", "(", "err", "error", ")", "{", "// lock the keyspace", "ctx", ",", "unlock", ",", "lockErr", ":=", "wr", ".", "ts", ".", "LockKeyspace", "(", "ctx", ",", "keyspace", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "uid", ")", ")", "\n", "if", "lockErr", "!=", "nil", "{", "return", "lockErr", "\n", "}", "\n", "defer", "unlock", "(", "&", "err", ")", "\n\n", "// remove the source shard", "_", ",", "err", "=", "wr", ".", "ts", ".", "UpdateShardFields", "(", "ctx", ",", "keyspace", ",", "shard", ",", "func", "(", "si", "*", "topo", ".", "ShardInfo", ")", "error", "{", "var", "newSourceShards", "[", "]", "*", "topodatapb", ".", "Shard_SourceShard", "\n", "for", "_", ",", "ss", ":=", "range", "si", ".", "SourceShards", "{", "if", "ss", ".", "Uid", "!=", "uid", "{", "newSourceShards", "=", "append", "(", "newSourceShards", ",", "ss", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "newSourceShards", ")", "==", "len", "(", "si", ".", "SourceShards", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "uid", ")", "\n", "}", "\n", "si", ".", "SourceShards", "=", "newSourceShards", "\n", "return", "nil", "\n", "}", ")", "\n", "return", "err", "\n", "}" ]
// SourceShardDelete will delete a SourceShard inside a shard, by index. // // This takes the keyspace lock as not to interfere with resharding operations.
[ "SourceShardDelete", "will", "delete", "a", "SourceShard", "inside", "a", "shard", "by", "index", ".", "This", "takes", "the", "keyspace", "lock", "as", "not", "to", "interfere", "with", "resharding", "operations", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/shard.go#L346-L369
train
vitessio/vitess
go/vt/wrangler/shard.go
SourceShardAdd
func (wr *Wrangler) SourceShardAdd(ctx context.Context, keyspace, shard string, uid uint32, skeyspace, sshard string, keyRange *topodatapb.KeyRange, tables []string) (err error) { // lock the keyspace ctx, unlock, lockErr := wr.ts.LockKeyspace(ctx, keyspace, fmt.Sprintf("SourceShardAdd(%v)", uid)) if lockErr != nil { return lockErr } defer unlock(&err) // and update the shard _, err = wr.ts.UpdateShardFields(ctx, keyspace, shard, func(si *topo.ShardInfo) error { // check the uid is not used already for _, ss := range si.SourceShards { if ss.Uid == uid { return fmt.Errorf("uid %v is already in use", uid) } } si.SourceShards = append(si.SourceShards, &topodatapb.Shard_SourceShard{ Uid: uid, Keyspace: skeyspace, Shard: sshard, KeyRange: keyRange, Tables: tables, }) return nil }) return err }
go
func (wr *Wrangler) SourceShardAdd(ctx context.Context, keyspace, shard string, uid uint32, skeyspace, sshard string, keyRange *topodatapb.KeyRange, tables []string) (err error) { // lock the keyspace ctx, unlock, lockErr := wr.ts.LockKeyspace(ctx, keyspace, fmt.Sprintf("SourceShardAdd(%v)", uid)) if lockErr != nil { return lockErr } defer unlock(&err) // and update the shard _, err = wr.ts.UpdateShardFields(ctx, keyspace, shard, func(si *topo.ShardInfo) error { // check the uid is not used already for _, ss := range si.SourceShards { if ss.Uid == uid { return fmt.Errorf("uid %v is already in use", uid) } } si.SourceShards = append(si.SourceShards, &topodatapb.Shard_SourceShard{ Uid: uid, Keyspace: skeyspace, Shard: sshard, KeyRange: keyRange, Tables: tables, }) return nil }) return err }
[ "func", "(", "wr", "*", "Wrangler", ")", "SourceShardAdd", "(", "ctx", "context", ".", "Context", ",", "keyspace", ",", "shard", "string", ",", "uid", "uint32", ",", "skeyspace", ",", "sshard", "string", ",", "keyRange", "*", "topodatapb", ".", "KeyRange", ",", "tables", "[", "]", "string", ")", "(", "err", "error", ")", "{", "// lock the keyspace", "ctx", ",", "unlock", ",", "lockErr", ":=", "wr", ".", "ts", ".", "LockKeyspace", "(", "ctx", ",", "keyspace", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "uid", ")", ")", "\n", "if", "lockErr", "!=", "nil", "{", "return", "lockErr", "\n", "}", "\n", "defer", "unlock", "(", "&", "err", ")", "\n\n", "// and update the shard", "_", ",", "err", "=", "wr", ".", "ts", ".", "UpdateShardFields", "(", "ctx", ",", "keyspace", ",", "shard", ",", "func", "(", "si", "*", "topo", ".", "ShardInfo", ")", "error", "{", "// check the uid is not used already", "for", "_", ",", "ss", ":=", "range", "si", ".", "SourceShards", "{", "if", "ss", ".", "Uid", "==", "uid", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "uid", ")", "\n", "}", "\n", "}", "\n\n", "si", ".", "SourceShards", "=", "append", "(", "si", ".", "SourceShards", ",", "&", "topodatapb", ".", "Shard_SourceShard", "{", "Uid", ":", "uid", ",", "Keyspace", ":", "skeyspace", ",", "Shard", ":", "sshard", ",", "KeyRange", ":", "keyRange", ",", "Tables", ":", "tables", ",", "}", ")", "\n", "return", "nil", "\n", "}", ")", "\n", "return", "err", "\n", "}" ]
// SourceShardAdd will add a new SourceShard inside a shard.
[ "SourceShardAdd", "will", "add", "a", "new", "SourceShard", "inside", "a", "shard", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/shard.go#L372-L399
train
vitessio/vitess
go/vt/schemamanager/schemamanager.go
Run
func Run(ctx context.Context, controller Controller, executor Executor) error { if err := controller.Open(ctx); err != nil { log.Errorf("failed to open data sourcer: %v", err) return err } defer controller.Close() sqls, err := controller.Read(ctx) if err != nil { log.Errorf("failed to read data from data sourcer: %v", err) controller.OnReadFail(ctx, err) return err } controller.OnReadSuccess(ctx) if len(sqls) == 0 { return nil } keyspace := controller.Keyspace() if err := executor.Open(ctx, keyspace); err != nil { log.Errorf("failed to open executor: %v", err) return err } defer executor.Close() if err := executor.Validate(ctx, sqls); err != nil { log.Errorf("validation fail: %v", err) controller.OnValidationFail(ctx, err) return err } if err := controller.OnValidationSuccess(ctx); err != nil { return err } result := executor.Execute(ctx, sqls) if err := controller.OnExecutorComplete(ctx, result); err != nil { return err } if result.ExecutorErr != "" || len(result.FailedShards) > 0 { out, _ := json.MarshalIndent(result, "", " ") return fmt.Errorf("schema change failed, ExecuteResult: %v", string(out)) } return nil }
go
func Run(ctx context.Context, controller Controller, executor Executor) error { if err := controller.Open(ctx); err != nil { log.Errorf("failed to open data sourcer: %v", err) return err } defer controller.Close() sqls, err := controller.Read(ctx) if err != nil { log.Errorf("failed to read data from data sourcer: %v", err) controller.OnReadFail(ctx, err) return err } controller.OnReadSuccess(ctx) if len(sqls) == 0 { return nil } keyspace := controller.Keyspace() if err := executor.Open(ctx, keyspace); err != nil { log.Errorf("failed to open executor: %v", err) return err } defer executor.Close() if err := executor.Validate(ctx, sqls); err != nil { log.Errorf("validation fail: %v", err) controller.OnValidationFail(ctx, err) return err } if err := controller.OnValidationSuccess(ctx); err != nil { return err } result := executor.Execute(ctx, sqls) if err := controller.OnExecutorComplete(ctx, result); err != nil { return err } if result.ExecutorErr != "" || len(result.FailedShards) > 0 { out, _ := json.MarshalIndent(result, "", " ") return fmt.Errorf("schema change failed, ExecuteResult: %v", string(out)) } return nil }
[ "func", "Run", "(", "ctx", "context", ".", "Context", ",", "controller", "Controller", ",", "executor", "Executor", ")", "error", "{", "if", "err", ":=", "controller", ".", "Open", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "defer", "controller", ".", "Close", "(", ")", "\n", "sqls", ",", "err", ":=", "controller", ".", "Read", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "controller", ".", "OnReadFail", "(", "ctx", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "controller", ".", "OnReadSuccess", "(", "ctx", ")", "\n", "if", "len", "(", "sqls", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "keyspace", ":=", "controller", ".", "Keyspace", "(", ")", "\n", "if", "err", ":=", "executor", ".", "Open", "(", "ctx", ",", "keyspace", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "defer", "executor", ".", "Close", "(", ")", "\n", "if", "err", ":=", "executor", ".", "Validate", "(", "ctx", ",", "sqls", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "controller", ".", "OnValidationFail", "(", "ctx", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "controller", ".", "OnValidationSuccess", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "result", ":=", "executor", ".", "Execute", "(", "ctx", ",", "sqls", ")", "\n\n", "if", "err", ":=", "controller", ".", "OnExecutorComplete", "(", "ctx", ",", "result", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "result", ".", "ExecutorErr", "!=", "\"", "\"", "||", "len", "(", "result", ".", "FailedShards", ")", ">", "0", "{", "out", ",", "_", ":=", "json", ".", "MarshalIndent", "(", "result", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "string", "(", "out", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Run applies schema changes on Vitess through VtGate.
[ "Run", "applies", "schema", "changes", "on", "Vitess", "through", "VtGate", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemamanager.go#L96-L138
train
vitessio/vitess
go/vt/schemamanager/schemamanager.go
RegisterControllerFactory
func RegisterControllerFactory(name string, factory ControllerFactory) { if _, ok := controllerFactories[name]; ok { panic(fmt.Sprintf("register a registered key: %s", name)) } controllerFactories[name] = factory }
go
func RegisterControllerFactory(name string, factory ControllerFactory) { if _, ok := controllerFactories[name]; ok { panic(fmt.Sprintf("register a registered key: %s", name)) } controllerFactories[name] = factory }
[ "func", "RegisterControllerFactory", "(", "name", "string", ",", "factory", "ControllerFactory", ")", "{", "if", "_", ",", "ok", ":=", "controllerFactories", "[", "name", "]", ";", "ok", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ")", ")", "\n", "}", "\n", "controllerFactories", "[", "name", "]", "=", "factory", "\n", "}" ]
// RegisterControllerFactory register a control factory.
[ "RegisterControllerFactory", "register", "a", "control", "factory", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemamanager.go#L141-L146
train
vitessio/vitess
go/vt/schemamanager/schemamanager.go
GetControllerFactory
func GetControllerFactory(name string) (ControllerFactory, error) { factory, ok := controllerFactories[name] if !ok { return nil, fmt.Errorf("there is no data sourcer factory with name: %s", name) } return factory, nil }
go
func GetControllerFactory(name string) (ControllerFactory, error) { factory, ok := controllerFactories[name] if !ok { return nil, fmt.Errorf("there is no data sourcer factory with name: %s", name) } return factory, nil }
[ "func", "GetControllerFactory", "(", "name", "string", ")", "(", "ControllerFactory", ",", "error", ")", "{", "factory", ",", "ok", ":=", "controllerFactories", "[", "name", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "return", "factory", ",", "nil", "\n", "}" ]
// GetControllerFactory gets a ControllerFactory.
[ "GetControllerFactory", "gets", "a", "ControllerFactory", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemamanager.go#L149-L155
train
vitessio/vitess
go/vt/vttablet/queryservice/wrapped.go
canRetry
func canRetry(ctx context.Context, err error) bool { if err == nil { return false } select { case <-ctx.Done(): return false default: } switch vterrors.Code(err) { case vtrpcpb.Code_UNAVAILABLE, vtrpcpb.Code_FAILED_PRECONDITION: return true } return false }
go
func canRetry(ctx context.Context, err error) bool { if err == nil { return false } select { case <-ctx.Done(): return false default: } switch vterrors.Code(err) { case vtrpcpb.Code_UNAVAILABLE, vtrpcpb.Code_FAILED_PRECONDITION: return true } return false }
[ "func", "canRetry", "(", "ctx", "context", ".", "Context", ",", "err", "error", ")", "bool", "{", "if", "err", "==", "nil", "{", "return", "false", "\n", "}", "\n\n", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "false", "\n", "default", ":", "}", "\n\n", "switch", "vterrors", ".", "Code", "(", "err", ")", "{", "case", "vtrpcpb", ".", "Code_UNAVAILABLE", ",", "vtrpcpb", ".", "Code_FAILED_PRECONDITION", ":", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// canRetry returns true if the error is retryable on a different vttablet. // Nil error or a canceled context make it return // false. Otherwise, the error code determines the outcome.
[ "canRetry", "returns", "true", "if", "the", "error", "is", "retryable", "on", "a", "different", "vttablet", ".", "Nil", "error", "or", "a", "canceled", "context", "make", "it", "return", "false", ".", "Otherwise", "the", "error", "code", "determines", "the", "outcome", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/queryservice/wrapped.go#L61-L77
train
vitessio/vitess
go/vt/vtgate/resolver.go
StreamExecute
func (res *Resolver) StreamExecute( ctx context.Context, sql string, bindVars map[string]*querypb.BindVariable, keyspace string, tabletType topodatapb.TabletType, destination key.Destination, options *querypb.ExecuteOptions, callback func(*sqltypes.Result) error, ) error { rss, err := res.resolver.ResolveDestination(ctx, keyspace, tabletType, destination) if err != nil { return err } err = res.scatterConn.StreamExecute( ctx, sql, bindVars, rss, tabletType, options, callback) return err }
go
func (res *Resolver) StreamExecute( ctx context.Context, sql string, bindVars map[string]*querypb.BindVariable, keyspace string, tabletType topodatapb.TabletType, destination key.Destination, options *querypb.ExecuteOptions, callback func(*sqltypes.Result) error, ) error { rss, err := res.resolver.ResolveDestination(ctx, keyspace, tabletType, destination) if err != nil { return err } err = res.scatterConn.StreamExecute( ctx, sql, bindVars, rss, tabletType, options, callback) return err }
[ "func", "(", "res", "*", "Resolver", ")", "StreamExecute", "(", "ctx", "context", ".", "Context", ",", "sql", "string", ",", "bindVars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "keyspace", "string", ",", "tabletType", "topodatapb", ".", "TabletType", ",", "destination", "key", ".", "Destination", ",", "options", "*", "querypb", ".", "ExecuteOptions", ",", "callback", "func", "(", "*", "sqltypes", ".", "Result", ")", "error", ",", ")", "error", "{", "rss", ",", "err", ":=", "res", ".", "resolver", ".", "ResolveDestination", "(", "ctx", ",", "keyspace", ",", "tabletType", ",", "destination", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "res", ".", "scatterConn", ".", "StreamExecute", "(", "ctx", ",", "sql", ",", "bindVars", ",", "rss", ",", "tabletType", ",", "options", ",", "callback", ")", "\n", "return", "err", "\n", "}" ]
// StreamExecute executes a streaming query on shards resolved by given func. // This function currently temporarily enforces the restriction of executing on // one shard since it cannot merge-sort the results to guarantee ordering of // response which is needed for checkpointing. // Note we guarantee the callback will not be called concurrently // by mutiple go routines.
[ "StreamExecute", "executes", "a", "streaming", "query", "on", "shards", "resolved", "by", "given", "func", ".", "This", "function", "currently", "temporarily", "enforces", "the", "restriction", "of", "executing", "on", "one", "shard", "since", "it", "cannot", "merge", "-", "sort", "the", "results", "to", "guarantee", "ordering", "of", "response", "which", "is", "needed", "for", "checkpointing", ".", "Note", "we", "guarantee", "the", "callback", "will", "not", "be", "called", "concurrently", "by", "mutiple", "go", "routines", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/resolver.go#L241-L264
train
vitessio/vitess
go/vt/vtgate/resolver.go
MessageAckKeyspaceIds
func (res *Resolver) MessageAckKeyspaceIds(ctx context.Context, keyspace, name string, idKeyspaceIDs []*vtgatepb.IdKeyspaceId) (int64, error) { ids := make([]*querypb.Value, len(idKeyspaceIDs)) ksids := make([]key.Destination, len(idKeyspaceIDs)) for i, iki := range idKeyspaceIDs { ids[i] = iki.Id ksids[i] = key.DestinationKeyspaceID(iki.KeyspaceId) } rss, values, err := res.resolver.ResolveDestinations(ctx, keyspace, topodatapb.TabletType_MASTER, ids, ksids) if err != nil { return 0, err } return res.scatterConn.MessageAck(ctx, rss, values, name) }
go
func (res *Resolver) MessageAckKeyspaceIds(ctx context.Context, keyspace, name string, idKeyspaceIDs []*vtgatepb.IdKeyspaceId) (int64, error) { ids := make([]*querypb.Value, len(idKeyspaceIDs)) ksids := make([]key.Destination, len(idKeyspaceIDs)) for i, iki := range idKeyspaceIDs { ids[i] = iki.Id ksids[i] = key.DestinationKeyspaceID(iki.KeyspaceId) } rss, values, err := res.resolver.ResolveDestinations(ctx, keyspace, topodatapb.TabletType_MASTER, ids, ksids) if err != nil { return 0, err } return res.scatterConn.MessageAck(ctx, rss, values, name) }
[ "func", "(", "res", "*", "Resolver", ")", "MessageAckKeyspaceIds", "(", "ctx", "context", ".", "Context", ",", "keyspace", ",", "name", "string", ",", "idKeyspaceIDs", "[", "]", "*", "vtgatepb", ".", "IdKeyspaceId", ")", "(", "int64", ",", "error", ")", "{", "ids", ":=", "make", "(", "[", "]", "*", "querypb", ".", "Value", ",", "len", "(", "idKeyspaceIDs", ")", ")", "\n", "ksids", ":=", "make", "(", "[", "]", "key", ".", "Destination", ",", "len", "(", "idKeyspaceIDs", ")", ")", "\n", "for", "i", ",", "iki", ":=", "range", "idKeyspaceIDs", "{", "ids", "[", "i", "]", "=", "iki", ".", "Id", "\n", "ksids", "[", "i", "]", "=", "key", ".", "DestinationKeyspaceID", "(", "iki", ".", "KeyspaceId", ")", "\n", "}", "\n\n", "rss", ",", "values", ",", "err", ":=", "res", ".", "resolver", ".", "ResolveDestinations", "(", "ctx", ",", "keyspace", ",", "topodatapb", ".", "TabletType_MASTER", ",", "ids", ",", "ksids", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "return", "res", ".", "scatterConn", ".", "MessageAck", "(", "ctx", ",", "rss", ",", "values", ",", "name", ")", "\n", "}" ]
// MessageAckKeyspaceIds routes message acks based on the associated keyspace ids.
[ "MessageAckKeyspaceIds", "routes", "message", "acks", "based", "on", "the", "associated", "keyspace", "ids", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/resolver.go#L287-L301
train
vitessio/vitess
go/vt/vtgate/resolver.go
StrsEquals
func StrsEquals(a, b []string) bool { if len(a) != len(b) { return false } sort.Strings(a) sort.Strings(b) for i, v := range a { if v != b[i] { return false } } return true }
go
func StrsEquals(a, b []string) bool { if len(a) != len(b) { return false } sort.Strings(a) sort.Strings(b) for i, v := range a { if v != b[i] { return false } } return true }
[ "func", "StrsEquals", "(", "a", ",", "b", "[", "]", "string", ")", "bool", "{", "if", "len", "(", "a", ")", "!=", "len", "(", "b", ")", "{", "return", "false", "\n", "}", "\n", "sort", ".", "Strings", "(", "a", ")", "\n", "sort", ".", "Strings", "(", "b", ")", "\n", "for", "i", ",", "v", ":=", "range", "a", "{", "if", "v", "!=", "b", "[", "i", "]", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// StrsEquals compares contents of two string slices.
[ "StrsEquals", "compares", "contents", "of", "two", "string", "slices", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/resolver.go#L348-L360
train
vitessio/vitess
go/vt/vtgate/resolver.go
buildEntityIds
func buildEntityIds(values [][]*querypb.Value, qSQL, entityColName string, qBindVars map[string]*querypb.BindVariable) ([]string, []map[string]*querypb.BindVariable) { sqls := make([]string, len(values)) bindVars := make([]map[string]*querypb.BindVariable, len(values)) for i, val := range values { var b bytes.Buffer b.Write([]byte(entityColName)) bindVariables := make(map[string]*querypb.BindVariable) for k, v := range qBindVars { bindVariables[k] = v } bvName := fmt.Sprintf("%v_entity_ids", entityColName) bindVariables[bvName] = &querypb.BindVariable{ Type: querypb.Type_TUPLE, Values: val, } b.Write(inOperator) b.Write(sqlListIdentifier) b.Write([]byte(bvName)) sqls[i] = insertSQLClause(qSQL, b.String()) bindVars[i] = bindVariables } return sqls, bindVars }
go
func buildEntityIds(values [][]*querypb.Value, qSQL, entityColName string, qBindVars map[string]*querypb.BindVariable) ([]string, []map[string]*querypb.BindVariable) { sqls := make([]string, len(values)) bindVars := make([]map[string]*querypb.BindVariable, len(values)) for i, val := range values { var b bytes.Buffer b.Write([]byte(entityColName)) bindVariables := make(map[string]*querypb.BindVariable) for k, v := range qBindVars { bindVariables[k] = v } bvName := fmt.Sprintf("%v_entity_ids", entityColName) bindVariables[bvName] = &querypb.BindVariable{ Type: querypb.Type_TUPLE, Values: val, } b.Write(inOperator) b.Write(sqlListIdentifier) b.Write([]byte(bvName)) sqls[i] = insertSQLClause(qSQL, b.String()) bindVars[i] = bindVariables } return sqls, bindVars }
[ "func", "buildEntityIds", "(", "values", "[", "]", "[", "]", "*", "querypb", ".", "Value", ",", "qSQL", ",", "entityColName", "string", ",", "qBindVars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "(", "[", "]", "string", ",", "[", "]", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "{", "sqls", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "values", ")", ")", "\n", "bindVars", ":=", "make", "(", "[", "]", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "len", "(", "values", ")", ")", "\n", "for", "i", ",", "val", ":=", "range", "values", "{", "var", "b", "bytes", ".", "Buffer", "\n", "b", ".", "Write", "(", "[", "]", "byte", "(", "entityColName", ")", ")", "\n", "bindVariables", ":=", "make", "(", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "\n", "for", "k", ",", "v", ":=", "range", "qBindVars", "{", "bindVariables", "[", "k", "]", "=", "v", "\n", "}", "\n", "bvName", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "entityColName", ")", "\n", "bindVariables", "[", "bvName", "]", "=", "&", "querypb", ".", "BindVariable", "{", "Type", ":", "querypb", ".", "Type_TUPLE", ",", "Values", ":", "val", ",", "}", "\n", "b", ".", "Write", "(", "inOperator", ")", "\n", "b", ".", "Write", "(", "sqlListIdentifier", ")", "\n", "b", ".", "Write", "(", "[", "]", "byte", "(", "bvName", ")", ")", "\n", "sqls", "[", "i", "]", "=", "insertSQLClause", "(", "qSQL", ",", "b", ".", "String", "(", ")", ")", "\n", "bindVars", "[", "i", "]", "=", "bindVariables", "\n", "}", "\n", "return", "sqls", ",", "bindVars", "\n", "}" ]
// buildEntityIds populates SQL and BindVariables.
[ "buildEntityIds", "populates", "SQL", "and", "BindVariables", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/resolver.go#L363-L385
train
vitessio/vitess
go/vt/vtgate/vindexes/lookup_internal.go
Lookup
func (lkp *lookupInternal) Lookup(vcursor VCursor, ids []sqltypes.Value) ([]*sqltypes.Result, error) { results := make([]*sqltypes.Result, 0, len(ids)) for _, id := range ids { bindVars := map[string]*querypb.BindVariable{ lkp.FromColumns[0]: sqltypes.ValueBindVariable(id), } var err error var result *sqltypes.Result if lkp.Autocommit { result, err = vcursor.ExecuteAutocommit("VindexLookup", lkp.sel, bindVars, false /* isDML */) } else { result, err = vcursor.Execute("VindexLookup", lkp.sel, bindVars, false /* isDML */) } if err != nil { return nil, fmt.Errorf("lookup.Map: %v", err) } results = append(results, result) } return results, nil }
go
func (lkp *lookupInternal) Lookup(vcursor VCursor, ids []sqltypes.Value) ([]*sqltypes.Result, error) { results := make([]*sqltypes.Result, 0, len(ids)) for _, id := range ids { bindVars := map[string]*querypb.BindVariable{ lkp.FromColumns[0]: sqltypes.ValueBindVariable(id), } var err error var result *sqltypes.Result if lkp.Autocommit { result, err = vcursor.ExecuteAutocommit("VindexLookup", lkp.sel, bindVars, false /* isDML */) } else { result, err = vcursor.Execute("VindexLookup", lkp.sel, bindVars, false /* isDML */) } if err != nil { return nil, fmt.Errorf("lookup.Map: %v", err) } results = append(results, result) } return results, nil }
[ "func", "(", "lkp", "*", "lookupInternal", ")", "Lookup", "(", "vcursor", "VCursor", ",", "ids", "[", "]", "sqltypes", ".", "Value", ")", "(", "[", "]", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "results", ":=", "make", "(", "[", "]", "*", "sqltypes", ".", "Result", ",", "0", ",", "len", "(", "ids", ")", ")", "\n", "for", "_", ",", "id", ":=", "range", "ids", "{", "bindVars", ":=", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", "{", "lkp", ".", "FromColumns", "[", "0", "]", ":", "sqltypes", ".", "ValueBindVariable", "(", "id", ")", ",", "}", "\n", "var", "err", "error", "\n", "var", "result", "*", "sqltypes", ".", "Result", "\n", "if", "lkp", ".", "Autocommit", "{", "result", ",", "err", "=", "vcursor", ".", "ExecuteAutocommit", "(", "\"", "\"", ",", "lkp", ".", "sel", ",", "bindVars", ",", "false", "/* isDML */", ")", "\n", "}", "else", "{", "result", ",", "err", "=", "vcursor", ".", "Execute", "(", "\"", "\"", ",", "lkp", ".", "sel", ",", "bindVars", ",", "false", "/* isDML */", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "results", "=", "append", "(", "results", ",", "result", ")", "\n", "}", "\n", "return", "results", ",", "nil", "\n", "}" ]
// Lookup performs a lookup for the ids.
[ "Lookup", "performs", "a", "lookup", "for", "the", "ids", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vindexes/lookup_internal.go#L62-L81
train
vitessio/vitess
go/vt/vtgate/vindexes/lookup_internal.go
Verify
func (lkp *lookupInternal) Verify(vcursor VCursor, ids, values []sqltypes.Value) ([]bool, error) { out := make([]bool, len(ids)) for i, id := range ids { bindVars := map[string]*querypb.BindVariable{ lkp.FromColumns[0]: sqltypes.ValueBindVariable(id), lkp.To: sqltypes.ValueBindVariable(values[i]), } var err error var result *sqltypes.Result if lkp.Autocommit { result, err = vcursor.ExecuteAutocommit("VindexVerify", lkp.ver, bindVars, true /* isDML */) } else { result, err = vcursor.Execute("VindexVerify", lkp.ver, bindVars, true /* isDML */) } if err != nil { return nil, fmt.Errorf("lookup.Verify: %v", err) } out[i] = (len(result.Rows) != 0) } return out, nil }
go
func (lkp *lookupInternal) Verify(vcursor VCursor, ids, values []sqltypes.Value) ([]bool, error) { out := make([]bool, len(ids)) for i, id := range ids { bindVars := map[string]*querypb.BindVariable{ lkp.FromColumns[0]: sqltypes.ValueBindVariable(id), lkp.To: sqltypes.ValueBindVariable(values[i]), } var err error var result *sqltypes.Result if lkp.Autocommit { result, err = vcursor.ExecuteAutocommit("VindexVerify", lkp.ver, bindVars, true /* isDML */) } else { result, err = vcursor.Execute("VindexVerify", lkp.ver, bindVars, true /* isDML */) } if err != nil { return nil, fmt.Errorf("lookup.Verify: %v", err) } out[i] = (len(result.Rows) != 0) } return out, nil }
[ "func", "(", "lkp", "*", "lookupInternal", ")", "Verify", "(", "vcursor", "VCursor", ",", "ids", ",", "values", "[", "]", "sqltypes", ".", "Value", ")", "(", "[", "]", "bool", ",", "error", ")", "{", "out", ":=", "make", "(", "[", "]", "bool", ",", "len", "(", "ids", ")", ")", "\n", "for", "i", ",", "id", ":=", "range", "ids", "{", "bindVars", ":=", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", "{", "lkp", ".", "FromColumns", "[", "0", "]", ":", "sqltypes", ".", "ValueBindVariable", "(", "id", ")", ",", "lkp", ".", "To", ":", "sqltypes", ".", "ValueBindVariable", "(", "values", "[", "i", "]", ")", ",", "}", "\n", "var", "err", "error", "\n", "var", "result", "*", "sqltypes", ".", "Result", "\n", "if", "lkp", ".", "Autocommit", "{", "result", ",", "err", "=", "vcursor", ".", "ExecuteAutocommit", "(", "\"", "\"", ",", "lkp", ".", "ver", ",", "bindVars", ",", "true", "/* isDML */", ")", "\n", "}", "else", "{", "result", ",", "err", "=", "vcursor", ".", "Execute", "(", "\"", "\"", ",", "lkp", ".", "ver", ",", "bindVars", ",", "true", "/* isDML */", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "out", "[", "i", "]", "=", "(", "len", "(", "result", ".", "Rows", ")", "!=", "0", ")", "\n", "}", "\n", "return", "out", ",", "nil", "\n", "}" ]
// Verify returns true if ids map to values.
[ "Verify", "returns", "true", "if", "ids", "map", "to", "values", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vindexes/lookup_internal.go#L84-L104
train
vitessio/vitess
go/vt/vtgate/vindexes/lookup_internal.go
Update
func (lkp *lookupInternal) Update(vcursor VCursor, oldValues []sqltypes.Value, ksid sqltypes.Value, newValues []sqltypes.Value) error { if err := lkp.Delete(vcursor, [][]sqltypes.Value{oldValues}, ksid); err != nil { return err } return lkp.Create(vcursor, [][]sqltypes.Value{newValues}, []sqltypes.Value{ksid}, false /* ignoreMode */) }
go
func (lkp *lookupInternal) Update(vcursor VCursor, oldValues []sqltypes.Value, ksid sqltypes.Value, newValues []sqltypes.Value) error { if err := lkp.Delete(vcursor, [][]sqltypes.Value{oldValues}, ksid); err != nil { return err } return lkp.Create(vcursor, [][]sqltypes.Value{newValues}, []sqltypes.Value{ksid}, false /* ignoreMode */) }
[ "func", "(", "lkp", "*", "lookupInternal", ")", "Update", "(", "vcursor", "VCursor", ",", "oldValues", "[", "]", "sqltypes", ".", "Value", ",", "ksid", "sqltypes", ".", "Value", ",", "newValues", "[", "]", "sqltypes", ".", "Value", ")", "error", "{", "if", "err", ":=", "lkp", ".", "Delete", "(", "vcursor", ",", "[", "]", "[", "]", "sqltypes", ".", "Value", "{", "oldValues", "}", ",", "ksid", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "lkp", ".", "Create", "(", "vcursor", ",", "[", "]", "[", "]", "sqltypes", ".", "Value", "{", "newValues", "}", ",", "[", "]", "sqltypes", ".", "Value", "{", "ksid", "}", ",", "false", "/* ignoreMode */", ")", "\n", "}" ]
// Update implements the update functionality.
[ "Update", "implements", "the", "update", "functionality", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vindexes/lookup_internal.go#L217-L222
train
vitessio/vitess
go/vt/health/health.go
Report
func (fc FunctionReporter) Report(isSlaveType, shouldQueryServiceBeRunning bool) (time.Duration, error) { return fc(isSlaveType, shouldQueryServiceBeRunning) }
go
func (fc FunctionReporter) Report(isSlaveType, shouldQueryServiceBeRunning bool) (time.Duration, error) { return fc(isSlaveType, shouldQueryServiceBeRunning) }
[ "func", "(", "fc", "FunctionReporter", ")", "Report", "(", "isSlaveType", ",", "shouldQueryServiceBeRunning", "bool", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "return", "fc", "(", "isSlaveType", ",", "shouldQueryServiceBeRunning", ")", "\n", "}" ]
// Report implements Reporter.Report
[ "Report", "implements", "Reporter", ".", "Report" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/health/health.go#L64-L66
train
vitessio/vitess
go/vt/health/health.go
Register
func (ag *Aggregator) Register(name string, rep Reporter) { ag.mu.Lock() defer ag.mu.Unlock() if _, ok := ag.reporters[name]; ok { panic("reporter named " + name + " is already registered") } ag.reporters[name] = rep }
go
func (ag *Aggregator) Register(name string, rep Reporter) { ag.mu.Lock() defer ag.mu.Unlock() if _, ok := ag.reporters[name]; ok { panic("reporter named " + name + " is already registered") } ag.reporters[name] = rep }
[ "func", "(", "ag", "*", "Aggregator", ")", "Register", "(", "name", "string", ",", "rep", "Reporter", ")", "{", "ag", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "ag", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "_", ",", "ok", ":=", "ag", ".", "reporters", "[", "name", "]", ";", "ok", "{", "panic", "(", "\"", "\"", "+", "name", "+", "\"", "\"", ")", "\n", "}", "\n", "ag", ".", "reporters", "[", "name", "]", "=", "rep", "\n", "}" ]
// Register registers rep with ag.
[ "Register", "registers", "rep", "with", "ag", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/health/health.go#L138-L145
train
vitessio/vitess
go/vt/health/health.go
RegisterSimpleCheck
func (ag *Aggregator) RegisterSimpleCheck(name string, check func() error) { ag.Register(name, simpleReporter{html: template.HTML(name), check: check}) }
go
func (ag *Aggregator) RegisterSimpleCheck(name string, check func() error) { ag.Register(name, simpleReporter{html: template.HTML(name), check: check}) }
[ "func", "(", "ag", "*", "Aggregator", ")", "RegisterSimpleCheck", "(", "name", "string", ",", "check", "func", "(", ")", "error", ")", "{", "ag", ".", "Register", "(", "name", ",", "simpleReporter", "{", "html", ":", "template", ".", "HTML", "(", "name", ")", ",", "check", ":", "check", "}", ")", "\n", "}" ]
// RegisterSimpleCheck registers a simple health check function.
[ "RegisterSimpleCheck", "registers", "a", "simple", "health", "check", "function", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/health/health.go#L148-L150
train
vitessio/vitess
go/vt/health/health.go
HTMLName
func (ag *Aggregator) HTMLName() template.HTML { ag.mu.Lock() defer ag.mu.Unlock() result := make([]string, 0, len(ag.reporters)) for _, rep := range ag.reporters { result = append(result, string(rep.HTMLName())) } sort.Strings(result) return template.HTML(strings.Join(result, "&nbsp; + &nbsp;")) }
go
func (ag *Aggregator) HTMLName() template.HTML { ag.mu.Lock() defer ag.mu.Unlock() result := make([]string, 0, len(ag.reporters)) for _, rep := range ag.reporters { result = append(result, string(rep.HTMLName())) } sort.Strings(result) return template.HTML(strings.Join(result, "&nbsp; + &nbsp;")) }
[ "func", "(", "ag", "*", "Aggregator", ")", "HTMLName", "(", ")", "template", ".", "HTML", "{", "ag", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "ag", ".", "mu", ".", "Unlock", "(", ")", "\n", "result", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "ag", ".", "reporters", ")", ")", "\n", "for", "_", ",", "rep", ":=", "range", "ag", ".", "reporters", "{", "result", "=", "append", "(", "result", ",", "string", "(", "rep", ".", "HTMLName", "(", ")", ")", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "result", ")", "\n", "return", "template", ".", "HTML", "(", "strings", ".", "Join", "(", "result", ",", "\"", "\"", ")", ")", "\n", "}" ]
// HTMLName returns an aggregate name for all the reporters
[ "HTMLName", "returns", "an", "aggregate", "name", "for", "all", "the", "reporters" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/health/health.go#L153-L162
train
vitessio/vitess
go/vt/schemamanager/local_controller.go
Open
func (controller *LocalController) Open(ctx context.Context) error { // find all keyspace directories. fileInfos, err := ioutil.ReadDir(controller.schemaChangeDir) if err != nil { return err } for _, fileinfo := range fileInfos { if !fileinfo.IsDir() { continue } dirpath := path.Join(controller.schemaChangeDir, fileinfo.Name()) schemaChanges, err := ioutil.ReadDir(path.Join(dirpath, "input")) if err != nil { log.Warningf("there is no input dir in %s", dirpath) continue } // found a schema change if len(schemaChanges) > 0 { controller.keyspace = fileinfo.Name() controller.sqlFilename = schemaChanges[0].Name() controller.sqlPath = path.Join(dirpath, "input", schemaChanges[0].Name()) currentTime := time.Now() datePart := fmt.Sprintf( "%d/%d/%d", currentTime.Year(), currentTime.Month(), currentTime.Day()) controller.errorDir = path.Join(dirpath, "error", datePart) controller.completeDir = path.Join(dirpath, "complete", datePart) controller.logDir = path.Join(dirpath, "log", datePart) // the remaining schema changes will be picked by the next runs break } } return nil }
go
func (controller *LocalController) Open(ctx context.Context) error { // find all keyspace directories. fileInfos, err := ioutil.ReadDir(controller.schemaChangeDir) if err != nil { return err } for _, fileinfo := range fileInfos { if !fileinfo.IsDir() { continue } dirpath := path.Join(controller.schemaChangeDir, fileinfo.Name()) schemaChanges, err := ioutil.ReadDir(path.Join(dirpath, "input")) if err != nil { log.Warningf("there is no input dir in %s", dirpath) continue } // found a schema change if len(schemaChanges) > 0 { controller.keyspace = fileinfo.Name() controller.sqlFilename = schemaChanges[0].Name() controller.sqlPath = path.Join(dirpath, "input", schemaChanges[0].Name()) currentTime := time.Now() datePart := fmt.Sprintf( "%d/%d/%d", currentTime.Year(), currentTime.Month(), currentTime.Day()) controller.errorDir = path.Join(dirpath, "error", datePart) controller.completeDir = path.Join(dirpath, "complete", datePart) controller.logDir = path.Join(dirpath, "log", datePart) // the remaining schema changes will be picked by the next runs break } } return nil }
[ "func", "(", "controller", "*", "LocalController", ")", "Open", "(", "ctx", "context", ".", "Context", ")", "error", "{", "// find all keyspace directories.", "fileInfos", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "controller", ".", "schemaChangeDir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "fileinfo", ":=", "range", "fileInfos", "{", "if", "!", "fileinfo", ".", "IsDir", "(", ")", "{", "continue", "\n", "}", "\n", "dirpath", ":=", "path", ".", "Join", "(", "controller", ".", "schemaChangeDir", ",", "fileinfo", ".", "Name", "(", ")", ")", "\n", "schemaChanges", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "path", ".", "Join", "(", "dirpath", ",", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "dirpath", ")", "\n", "continue", "\n", "}", "\n", "// found a schema change", "if", "len", "(", "schemaChanges", ")", ">", "0", "{", "controller", ".", "keyspace", "=", "fileinfo", ".", "Name", "(", ")", "\n", "controller", ".", "sqlFilename", "=", "schemaChanges", "[", "0", "]", ".", "Name", "(", ")", "\n", "controller", ".", "sqlPath", "=", "path", ".", "Join", "(", "dirpath", ",", "\"", "\"", ",", "schemaChanges", "[", "0", "]", ".", "Name", "(", ")", ")", "\n\n", "currentTime", ":=", "time", ".", "Now", "(", ")", "\n", "datePart", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "currentTime", ".", "Year", "(", ")", ",", "currentTime", ".", "Month", "(", ")", ",", "currentTime", ".", "Day", "(", ")", ")", "\n\n", "controller", ".", "errorDir", "=", "path", ".", "Join", "(", "dirpath", ",", "\"", "\"", ",", "datePart", ")", "\n", "controller", ".", "completeDir", "=", "path", ".", "Join", "(", "dirpath", ",", "\"", "\"", ",", "datePart", ")", "\n", "controller", ".", "logDir", "=", "path", ".", "Join", "(", "dirpath", ",", "\"", "\"", ",", "datePart", ")", "\n", "// the remaining schema changes will be picked by the next runs", "break", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Open goes through the schema change dir and find a keyspace with a pending // schema change.
[ "Open", "goes", "through", "the", "schema", "change", "dir", "and", "find", "a", "keyspace", "with", "a", "pending", "schema", "change", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/local_controller.go#L77-L114
train
vitessio/vitess
go/vt/schemamanager/local_controller.go
Read
func (controller *LocalController) Read(ctx context.Context) ([]string, error) { if controller.keyspace == "" || controller.sqlPath == "" { return []string{}, nil } data, err := ioutil.ReadFile(controller.sqlPath) if err != nil { return nil, err } return strings.Split(string(data), ";"), nil }
go
func (controller *LocalController) Read(ctx context.Context) ([]string, error) { if controller.keyspace == "" || controller.sqlPath == "" { return []string{}, nil } data, err := ioutil.ReadFile(controller.sqlPath) if err != nil { return nil, err } return strings.Split(string(data), ";"), nil }
[ "func", "(", "controller", "*", "LocalController", ")", "Read", "(", "ctx", "context", ".", "Context", ")", "(", "[", "]", "string", ",", "error", ")", "{", "if", "controller", ".", "keyspace", "==", "\"", "\"", "||", "controller", ".", "sqlPath", "==", "\"", "\"", "{", "return", "[", "]", "string", "{", "}", ",", "nil", "\n", "}", "\n", "data", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "controller", ".", "sqlPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "strings", ".", "Split", "(", "string", "(", "data", ")", ",", "\"", "\"", ")", ",", "nil", "\n", "}" ]
// Read reads schema changes.
[ "Read", "reads", "schema", "changes", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/local_controller.go#L117-L126
train
vitessio/vitess
go/vt/schemamanager/local_controller.go
Close
func (controller *LocalController) Close() { controller.keyspace = "" controller.sqlPath = "" controller.sqlFilename = "" controller.errorDir = "" controller.logDir = "" controller.completeDir = "" }
go
func (controller *LocalController) Close() { controller.keyspace = "" controller.sqlPath = "" controller.sqlFilename = "" controller.errorDir = "" controller.logDir = "" controller.completeDir = "" }
[ "func", "(", "controller", "*", "LocalController", ")", "Close", "(", ")", "{", "controller", ".", "keyspace", "=", "\"", "\"", "\n", "controller", ".", "sqlPath", "=", "\"", "\"", "\n", "controller", ".", "sqlFilename", "=", "\"", "\"", "\n", "controller", ".", "errorDir", "=", "\"", "\"", "\n", "controller", ".", "logDir", "=", "\"", "\"", "\n", "controller", ".", "completeDir", "=", "\"", "\"", "\n", "}" ]
// Close reset keyspace, sqlPath, errorDir, logDir and completeDir.
[ "Close", "reset", "keyspace", "sqlPath", "errorDir", "logDir", "and", "completeDir", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/local_controller.go#L134-L141
train
vitessio/vitess
go/vt/schemamanager/local_controller.go
OnValidationFail
func (controller *LocalController) OnValidationFail(ctx context.Context, err error) error { return controller.moveToErrorDir(ctx) }
go
func (controller *LocalController) OnValidationFail(ctx context.Context, err error) error { return controller.moveToErrorDir(ctx) }
[ "func", "(", "controller", "*", "LocalController", ")", "OnValidationFail", "(", "ctx", "context", ".", "Context", ",", "err", "error", ")", "error", "{", "return", "controller", ".", "moveToErrorDir", "(", "ctx", ")", "\n", "}" ]
// OnValidationFail is no-op
[ "OnValidationFail", "is", "no", "-", "op" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/local_controller.go#L160-L162
train
vitessio/vitess
go/vt/topo/topoproto/flag.go
TabletTypeVar
func TabletTypeVar(p *topodatapb.TabletType, name string, defaultValue topodatapb.TabletType, usage string) { *p = defaultValue flag.Var((*TabletTypeFlag)(p), name, usage) }
go
func TabletTypeVar(p *topodatapb.TabletType, name string, defaultValue topodatapb.TabletType, usage string) { *p = defaultValue flag.Var((*TabletTypeFlag)(p), name, usage) }
[ "func", "TabletTypeVar", "(", "p", "*", "topodatapb", ".", "TabletType", ",", "name", "string", ",", "defaultValue", "topodatapb", ".", "TabletType", ",", "usage", "string", ")", "{", "*", "p", "=", "defaultValue", "\n", "flag", ".", "Var", "(", "(", "*", "TabletTypeFlag", ")", "(", "p", ")", ",", "name", ",", "usage", ")", "\n", "}" ]
// TabletTypeVar defines a TabletType flag with the specified name, default value and usage // string. The argument 'p' points to a tabletType in which to store the value of the flag.
[ "TabletTypeVar", "defines", "a", "TabletType", "flag", "with", "the", "specified", "name", "default", "value", "and", "usage", "string", ".", "The", "argument", "p", "points", "to", "a", "tabletType", "in", "which", "to", "store", "the", "value", "of", "the", "flag", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/topoproto/flag.go#L18-L21
train
vitessio/vitess
go/vt/topo/topoproto/tablet.go
TabletAliasIsZero
func TabletAliasIsZero(ta *topodatapb.TabletAlias) bool { return ta == nil || (ta.Cell == "" && ta.Uid == 0) }
go
func TabletAliasIsZero(ta *topodatapb.TabletAlias) bool { return ta == nil || (ta.Cell == "" && ta.Uid == 0) }
[ "func", "TabletAliasIsZero", "(", "ta", "*", "topodatapb", ".", "TabletAlias", ")", "bool", "{", "return", "ta", "==", "nil", "||", "(", "ta", ".", "Cell", "==", "\"", "\"", "&&", "ta", ".", "Uid", "==", "0", ")", "\n", "}" ]
// TabletAliasIsZero returns true iff cell and uid are empty
[ "TabletAliasIsZero", "returns", "true", "iff", "cell", "and", "uid", "are", "empty" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/topoproto/tablet.go#L52-L54
train
vitessio/vitess
go/vt/topo/topoproto/tablet.go
TabletAliasEqual
func TabletAliasEqual(left, right *topodatapb.TabletAlias) bool { return proto.Equal(left, right) }
go
func TabletAliasEqual(left, right *topodatapb.TabletAlias) bool { return proto.Equal(left, right) }
[ "func", "TabletAliasEqual", "(", "left", ",", "right", "*", "topodatapb", ".", "TabletAlias", ")", "bool", "{", "return", "proto", ".", "Equal", "(", "left", ",", "right", ")", "\n", "}" ]
// TabletAliasEqual returns true if two TabletAlias match
[ "TabletAliasEqual", "returns", "true", "if", "two", "TabletAlias", "match" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/topoproto/tablet.go#L57-L59
train
vitessio/vitess
go/vt/topo/topoproto/tablet.go
TabletAliasString
func TabletAliasString(ta *topodatapb.TabletAlias) string { if ta == nil { return "<nil>" } return fmt.Sprintf("%v-%010d", ta.Cell, ta.Uid) }
go
func TabletAliasString(ta *topodatapb.TabletAlias) string { if ta == nil { return "<nil>" } return fmt.Sprintf("%v-%010d", ta.Cell, ta.Uid) }
[ "func", "TabletAliasString", "(", "ta", "*", "topodatapb", ".", "TabletAlias", ")", "string", "{", "if", "ta", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ta", ".", "Cell", ",", "ta", ".", "Uid", ")", "\n", "}" ]
// TabletAliasString formats a TabletAlias
[ "TabletAliasString", "formats", "a", "TabletAlias" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/topoproto/tablet.go#L62-L67
train
vitessio/vitess
go/vt/topo/topoproto/tablet.go
ParseTabletType
func ParseTabletType(param string) (topodatapb.TabletType, error) { value, ok := topodatapb.TabletType_value[strings.ToUpper(param)] if !ok { return topodatapb.TabletType_UNKNOWN, fmt.Errorf("unknown TabletType %v", param) } return topodatapb.TabletType(value), nil }
go
func ParseTabletType(param string) (topodatapb.TabletType, error) { value, ok := topodatapb.TabletType_value[strings.ToUpper(param)] if !ok { return topodatapb.TabletType_UNKNOWN, fmt.Errorf("unknown TabletType %v", param) } return topodatapb.TabletType(value), nil }
[ "func", "ParseTabletType", "(", "param", "string", ")", "(", "topodatapb", ".", "TabletType", ",", "error", ")", "{", "value", ",", "ok", ":=", "topodatapb", ".", "TabletType_value", "[", "strings", ".", "ToUpper", "(", "param", ")", "]", "\n", "if", "!", "ok", "{", "return", "topodatapb", ".", "TabletType_UNKNOWN", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "param", ")", "\n", "}", "\n", "return", "topodatapb", ".", "TabletType", "(", "value", ")", ",", "nil", "\n", "}" ]
// ParseTabletType parses the tablet type into the enum.
[ "ParseTabletType", "parses", "the", "tablet", "type", "into", "the", "enum", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/topoproto/tablet.go#L150-L156
train
vitessio/vitess
go/vt/topo/topoproto/tablet.go
ParseTabletTypes
func ParseTabletTypes(param string) ([]topodatapb.TabletType, error) { var tabletTypes []topodatapb.TabletType for _, typeStr := range strings.Split(param, ",") { t, err := ParseTabletType(typeStr) if err != nil { return nil, err } tabletTypes = append(tabletTypes, t) } return tabletTypes, nil }
go
func ParseTabletTypes(param string) ([]topodatapb.TabletType, error) { var tabletTypes []topodatapb.TabletType for _, typeStr := range strings.Split(param, ",") { t, err := ParseTabletType(typeStr) if err != nil { return nil, err } tabletTypes = append(tabletTypes, t) } return tabletTypes, nil }
[ "func", "ParseTabletTypes", "(", "param", "string", ")", "(", "[", "]", "topodatapb", ".", "TabletType", ",", "error", ")", "{", "var", "tabletTypes", "[", "]", "topodatapb", ".", "TabletType", "\n", "for", "_", ",", "typeStr", ":=", "range", "strings", ".", "Split", "(", "param", ",", "\"", "\"", ")", "{", "t", ",", "err", ":=", "ParseTabletType", "(", "typeStr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "tabletTypes", "=", "append", "(", "tabletTypes", ",", "t", ")", "\n", "}", "\n", "return", "tabletTypes", ",", "nil", "\n", "}" ]
// ParseTabletTypes parses a comma separated list of tablet types and returns a slice with the respective enums.
[ "ParseTabletTypes", "parses", "a", "comma", "separated", "list", "of", "tablet", "types", "and", "returns", "a", "slice", "with", "the", "respective", "enums", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/topoproto/tablet.go#L159-L169
train
vitessio/vitess
go/vt/topo/topoproto/tablet.go
TabletTypeLString
func TabletTypeLString(tabletType topodatapb.TabletType) string { value, ok := tabletTypeLowerName[int32(tabletType)] if !ok { return "unknown" } return value }
go
func TabletTypeLString(tabletType topodatapb.TabletType) string { value, ok := tabletTypeLowerName[int32(tabletType)] if !ok { return "unknown" } return value }
[ "func", "TabletTypeLString", "(", "tabletType", "topodatapb", ".", "TabletType", ")", "string", "{", "value", ",", "ok", ":=", "tabletTypeLowerName", "[", "int32", "(", "tabletType", ")", "]", "\n", "if", "!", "ok", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "value", "\n", "}" ]
// TabletTypeLString returns a lower case version of the tablet type, // or "unknown" if not known.
[ "TabletTypeLString", "returns", "a", "lower", "case", "version", "of", "the", "tablet", "type", "or", "unknown", "if", "not", "known", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/topoproto/tablet.go#L173-L179
train
vitessio/vitess
go/vt/topo/topoproto/tablet.go
IsTypeInList
func IsTypeInList(tabletType topodatapb.TabletType, types []topodatapb.TabletType) bool { for _, t := range types { if tabletType == t { return true } } return false }
go
func IsTypeInList(tabletType topodatapb.TabletType, types []topodatapb.TabletType) bool { for _, t := range types { if tabletType == t { return true } } return false }
[ "func", "IsTypeInList", "(", "tabletType", "topodatapb", ".", "TabletType", ",", "types", "[", "]", "topodatapb", ".", "TabletType", ")", "bool", "{", "for", "_", ",", "t", ":=", "range", "types", "{", "if", "tabletType", "==", "t", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsTypeInList returns true if the given type is in the list. // Use it with AllTabletType and SlaveTabletType for instance.
[ "IsTypeInList", "returns", "true", "if", "the", "given", "type", "is", "in", "the", "list", ".", "Use", "it", "with", "AllTabletType", "and", "SlaveTabletType", "for", "instance", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/topoproto/tablet.go#L183-L190
train
vitessio/vitess
go/vt/topo/topoproto/tablet.go
MakeStringTypeList
func MakeStringTypeList(types []topodatapb.TabletType) []string { strs := make([]string, len(types)) for i, t := range types { strs[i] = strings.ToLower(t.String()) } sort.Strings(strs) return strs }
go
func MakeStringTypeList(types []topodatapb.TabletType) []string { strs := make([]string, len(types)) for i, t := range types { strs[i] = strings.ToLower(t.String()) } sort.Strings(strs) return strs }
[ "func", "MakeStringTypeList", "(", "types", "[", "]", "topodatapb", ".", "TabletType", ")", "[", "]", "string", "{", "strs", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "types", ")", ")", "\n", "for", "i", ",", "t", ":=", "range", "types", "{", "strs", "[", "i", "]", "=", "strings", ".", "ToLower", "(", "t", ".", "String", "(", ")", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "strs", ")", "\n", "return", "strs", "\n", "}" ]
// MakeStringTypeList returns a list of strings that match the input list.
[ "MakeStringTypeList", "returns", "a", "list", "of", "strings", "that", "match", "the", "input", "list", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/topoproto/tablet.go#L193-L200
train
vitessio/vitess
go/vt/topo/topoproto/tablet.go
MySQLIP
func MySQLIP(tablet *topodatapb.Tablet) (string, error) { ipAddrs, err := net.LookupHost(MysqlHostname(tablet)) if err != nil { return "", err } return ipAddrs[0], nil }
go
func MySQLIP(tablet *topodatapb.Tablet) (string, error) { ipAddrs, err := net.LookupHost(MysqlHostname(tablet)) if err != nil { return "", err } return ipAddrs[0], nil }
[ "func", "MySQLIP", "(", "tablet", "*", "topodatapb", ".", "Tablet", ")", "(", "string", ",", "error", ")", "{", "ipAddrs", ",", "err", ":=", "net", ".", "LookupHost", "(", "MysqlHostname", "(", "tablet", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "ipAddrs", "[", "0", "]", ",", "nil", "\n", "}" ]
// MySQLIP returns the MySQL server's IP by resolvign the host name.
[ "MySQLIP", "returns", "the", "MySQL", "server", "s", "IP", "by", "resolvign", "the", "host", "name", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/topoproto/tablet.go#L244-L250
train
vitessio/vitess
go/vt/topo/topoproto/tablet.go
TabletDbName
func TabletDbName(tablet *topodatapb.Tablet) string { if tablet.DbNameOverride != "" { return tablet.DbNameOverride } if tablet.Keyspace == "" { return "" } return vtDbPrefix + tablet.Keyspace }
go
func TabletDbName(tablet *topodatapb.Tablet) string { if tablet.DbNameOverride != "" { return tablet.DbNameOverride } if tablet.Keyspace == "" { return "" } return vtDbPrefix + tablet.Keyspace }
[ "func", "TabletDbName", "(", "tablet", "*", "topodatapb", ".", "Tablet", ")", "string", "{", "if", "tablet", ".", "DbNameOverride", "!=", "\"", "\"", "{", "return", "tablet", ".", "DbNameOverride", "\n", "}", "\n", "if", "tablet", ".", "Keyspace", "==", "\"", "\"", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "vtDbPrefix", "+", "tablet", ".", "Keyspace", "\n", "}" ]
// TabletDbName is usually implied by keyspace. Having the shard // information in the database name complicates mysql replication.
[ "TabletDbName", "is", "usually", "implied", "by", "keyspace", ".", "Having", "the", "shard", "information", "in", "the", "database", "name", "complicates", "mysql", "replication", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/topoproto/tablet.go#L254-L262
train
vitessio/vitess
go/vt/topo/topoproto/tablet.go
TabletIsAssigned
func TabletIsAssigned(tablet *topodatapb.Tablet) bool { return tablet != nil && tablet.Keyspace != "" && tablet.Shard != "" }
go
func TabletIsAssigned(tablet *topodatapb.Tablet) bool { return tablet != nil && tablet.Keyspace != "" && tablet.Shard != "" }
[ "func", "TabletIsAssigned", "(", "tablet", "*", "topodatapb", ".", "Tablet", ")", "bool", "{", "return", "tablet", "!=", "nil", "&&", "tablet", ".", "Keyspace", "!=", "\"", "\"", "&&", "tablet", ".", "Shard", "!=", "\"", "\"", "\n", "}" ]
// TabletIsAssigned returns if this tablet is assigned to a keyspace and shard. // A "scrap" node will show up as assigned even though its data cannot be used // for serving.
[ "TabletIsAssigned", "returns", "if", "this", "tablet", "is", "assigned", "to", "a", "keyspace", "and", "shard", ".", "A", "scrap", "node", "will", "show", "up", "as", "assigned", "even", "though", "its", "data", "cannot", "be", "used", "for", "serving", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/topoproto/tablet.go#L267-L269
train
vitessio/vitess
go/mysql/binlog_event_rbr.go
metadataLength
func metadataLength(typ byte) int { switch typ { case TypeDecimal, TypeTiny, TypeShort, TypeLong, TypeNull, TypeTimestamp, TypeLongLong, TypeInt24, TypeDate, TypeTime, TypeDateTime, TypeYear, TypeNewDate: // No data here. return 0 case TypeFloat, TypeDouble, TypeTimestamp2, TypeDateTime2, TypeTime2, TypeJSON, TypeTinyBlob, TypeMediumBlob, TypeLongBlob, TypeBlob, TypeGeometry: // One byte. return 1 case TypeNewDecimal, TypeEnum, TypeSet, TypeString: // Two bytes, Big Endian because of crazy encoding. return 2 case TypeVarchar, TypeBit, TypeVarString: // Two bytes, Little Endian return 2 default: // Unknown type. This is used in tests only, so panic. panic(vterrors.Errorf(vtrpc.Code_INTERNAL, "metadataLength: unhandled data type: %v", typ)) } }
go
func metadataLength(typ byte) int { switch typ { case TypeDecimal, TypeTiny, TypeShort, TypeLong, TypeNull, TypeTimestamp, TypeLongLong, TypeInt24, TypeDate, TypeTime, TypeDateTime, TypeYear, TypeNewDate: // No data here. return 0 case TypeFloat, TypeDouble, TypeTimestamp2, TypeDateTime2, TypeTime2, TypeJSON, TypeTinyBlob, TypeMediumBlob, TypeLongBlob, TypeBlob, TypeGeometry: // One byte. return 1 case TypeNewDecimal, TypeEnum, TypeSet, TypeString: // Two bytes, Big Endian because of crazy encoding. return 2 case TypeVarchar, TypeBit, TypeVarString: // Two bytes, Little Endian return 2 default: // Unknown type. This is used in tests only, so panic. panic(vterrors.Errorf(vtrpc.Code_INTERNAL, "metadataLength: unhandled data type: %v", typ)) } }
[ "func", "metadataLength", "(", "typ", "byte", ")", "int", "{", "switch", "typ", "{", "case", "TypeDecimal", ",", "TypeTiny", ",", "TypeShort", ",", "TypeLong", ",", "TypeNull", ",", "TypeTimestamp", ",", "TypeLongLong", ",", "TypeInt24", ",", "TypeDate", ",", "TypeTime", ",", "TypeDateTime", ",", "TypeYear", ",", "TypeNewDate", ":", "// No data here.", "return", "0", "\n\n", "case", "TypeFloat", ",", "TypeDouble", ",", "TypeTimestamp2", ",", "TypeDateTime2", ",", "TypeTime2", ",", "TypeJSON", ",", "TypeTinyBlob", ",", "TypeMediumBlob", ",", "TypeLongBlob", ",", "TypeBlob", ",", "TypeGeometry", ":", "// One byte.", "return", "1", "\n\n", "case", "TypeNewDecimal", ",", "TypeEnum", ",", "TypeSet", ",", "TypeString", ":", "// Two bytes, Big Endian because of crazy encoding.", "return", "2", "\n\n", "case", "TypeVarchar", ",", "TypeBit", ",", "TypeVarString", ":", "// Two bytes, Little Endian", "return", "2", "\n\n", "default", ":", "// Unknown type. This is used in tests only, so panic.", "panic", "(", "vterrors", ".", "Errorf", "(", "vtrpc", ".", "Code_INTERNAL", ",", "\"", "\"", ",", "typ", ")", ")", "\n", "}", "\n", "}" ]
// metadataLength returns how many bytes are used for metadata, based on a type.
[ "metadataLength", "returns", "how", "many", "bytes", "are", "used", "for", "metadata", "based", "on", "a", "type", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/binlog_event_rbr.go#L104-L126
train
vitessio/vitess
go/mysql/binlog_event_rbr.go
metadataTotalLength
func metadataTotalLength(types []byte) int { sum := 0 for _, t := range types { sum += metadataLength(t) } return sum }
go
func metadataTotalLength(types []byte) int { sum := 0 for _, t := range types { sum += metadataLength(t) } return sum }
[ "func", "metadataTotalLength", "(", "types", "[", "]", "byte", ")", "int", "{", "sum", ":=", "0", "\n", "for", "_", ",", "t", ":=", "range", "types", "{", "sum", "+=", "metadataLength", "(", "t", ")", "\n", "}", "\n", "return", "sum", "\n", "}" ]
// metadataTotalLength returns the total size of the metadata for an // array of types.
[ "metadataTotalLength", "returns", "the", "total", "size", "of", "the", "metadata", "for", "an", "array", "of", "types", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/binlog_event_rbr.go#L130-L136
train
vitessio/vitess
go/mysql/binlog_event_rbr.go
metadataRead
func metadataRead(data []byte, pos int, typ byte) (uint16, int, error) { switch typ { case TypeDecimal, TypeTiny, TypeShort, TypeLong, TypeNull, TypeTimestamp, TypeLongLong, TypeInt24, TypeDate, TypeTime, TypeDateTime, TypeYear, TypeNewDate: // No data here. return 0, pos, nil case TypeFloat, TypeDouble, TypeTimestamp2, TypeDateTime2, TypeTime2, TypeJSON, TypeTinyBlob, TypeMediumBlob, TypeLongBlob, TypeBlob, TypeGeometry: // One byte. return uint16(data[pos]), pos + 1, nil case TypeNewDecimal, TypeEnum, TypeSet, TypeString: // Two bytes, Big Endian because of crazy encoding. return uint16(data[pos])<<8 + uint16(data[pos+1]), pos + 2, nil case TypeVarchar, TypeBit, TypeVarString: // Two bytes, Little Endian return uint16(data[pos]) + uint16(data[pos+1])<<8, pos + 2, nil default: // Unknown types, we can't go on. return 0, 0, vterrors.Errorf(vtrpc.Code_INTERNAL, "metadataRead: unhandled data type: %v", typ) } }
go
func metadataRead(data []byte, pos int, typ byte) (uint16, int, error) { switch typ { case TypeDecimal, TypeTiny, TypeShort, TypeLong, TypeNull, TypeTimestamp, TypeLongLong, TypeInt24, TypeDate, TypeTime, TypeDateTime, TypeYear, TypeNewDate: // No data here. return 0, pos, nil case TypeFloat, TypeDouble, TypeTimestamp2, TypeDateTime2, TypeTime2, TypeJSON, TypeTinyBlob, TypeMediumBlob, TypeLongBlob, TypeBlob, TypeGeometry: // One byte. return uint16(data[pos]), pos + 1, nil case TypeNewDecimal, TypeEnum, TypeSet, TypeString: // Two bytes, Big Endian because of crazy encoding. return uint16(data[pos])<<8 + uint16(data[pos+1]), pos + 2, nil case TypeVarchar, TypeBit, TypeVarString: // Two bytes, Little Endian return uint16(data[pos]) + uint16(data[pos+1])<<8, pos + 2, nil default: // Unknown types, we can't go on. return 0, 0, vterrors.Errorf(vtrpc.Code_INTERNAL, "metadataRead: unhandled data type: %v", typ) } }
[ "func", "metadataRead", "(", "data", "[", "]", "byte", ",", "pos", "int", ",", "typ", "byte", ")", "(", "uint16", ",", "int", ",", "error", ")", "{", "switch", "typ", "{", "case", "TypeDecimal", ",", "TypeTiny", ",", "TypeShort", ",", "TypeLong", ",", "TypeNull", ",", "TypeTimestamp", ",", "TypeLongLong", ",", "TypeInt24", ",", "TypeDate", ",", "TypeTime", ",", "TypeDateTime", ",", "TypeYear", ",", "TypeNewDate", ":", "// No data here.", "return", "0", ",", "pos", ",", "nil", "\n\n", "case", "TypeFloat", ",", "TypeDouble", ",", "TypeTimestamp2", ",", "TypeDateTime2", ",", "TypeTime2", ",", "TypeJSON", ",", "TypeTinyBlob", ",", "TypeMediumBlob", ",", "TypeLongBlob", ",", "TypeBlob", ",", "TypeGeometry", ":", "// One byte.", "return", "uint16", "(", "data", "[", "pos", "]", ")", ",", "pos", "+", "1", ",", "nil", "\n\n", "case", "TypeNewDecimal", ",", "TypeEnum", ",", "TypeSet", ",", "TypeString", ":", "// Two bytes, Big Endian because of crazy encoding.", "return", "uint16", "(", "data", "[", "pos", "]", ")", "<<", "8", "+", "uint16", "(", "data", "[", "pos", "+", "1", "]", ")", ",", "pos", "+", "2", ",", "nil", "\n\n", "case", "TypeVarchar", ",", "TypeBit", ",", "TypeVarString", ":", "// Two bytes, Little Endian", "return", "uint16", "(", "data", "[", "pos", "]", ")", "+", "uint16", "(", "data", "[", "pos", "+", "1", "]", ")", "<<", "8", ",", "pos", "+", "2", ",", "nil", "\n\n", "default", ":", "// Unknown types, we can't go on.", "return", "0", ",", "0", ",", "vterrors", ".", "Errorf", "(", "vtrpc", ".", "Code_INTERNAL", ",", "\"", "\"", ",", "typ", ")", "\n", "}", "\n", "}" ]
// metadataRead reads a single value from the metadata string.
[ "metadataRead", "reads", "a", "single", "value", "from", "the", "metadata", "string", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/binlog_event_rbr.go#L139-L162
train
vitessio/vitess
go/mysql/binlog_event_rbr.go
printTimestamp
func printTimestamp(v uint32) *bytes.Buffer { if v == 0 { return bytes.NewBuffer(ZeroTimestamp) } t := time.Unix(int64(v), 0).UTC() year, month, day := t.Date() hour, minute, second := t.Clock() result := &bytes.Buffer{} fmt.Fprintf(result, "%04d-%02d-%02d %02d:%02d:%02d", year, int(month), day, hour, minute, second) return result }
go
func printTimestamp(v uint32) *bytes.Buffer { if v == 0 { return bytes.NewBuffer(ZeroTimestamp) } t := time.Unix(int64(v), 0).UTC() year, month, day := t.Date() hour, minute, second := t.Clock() result := &bytes.Buffer{} fmt.Fprintf(result, "%04d-%02d-%02d %02d:%02d:%02d", year, int(month), day, hour, minute, second) return result }
[ "func", "printTimestamp", "(", "v", "uint32", ")", "*", "bytes", ".", "Buffer", "{", "if", "v", "==", "0", "{", "return", "bytes", ".", "NewBuffer", "(", "ZeroTimestamp", ")", "\n", "}", "\n\n", "t", ":=", "time", ".", "Unix", "(", "int64", "(", "v", ")", ",", "0", ")", ".", "UTC", "(", ")", "\n", "year", ",", "month", ",", "day", ":=", "t", ".", "Date", "(", ")", "\n", "hour", ",", "minute", ",", "second", ":=", "t", ".", "Clock", "(", ")", "\n\n", "result", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "fmt", ".", "Fprintf", "(", "result", ",", "\"", "\"", ",", "year", ",", "int", "(", "month", ")", ",", "day", ",", "hour", ",", "minute", ",", "second", ")", "\n", "return", "result", "\n", "}" ]
// printTimestamp is a helper method to append a timestamp into a bytes.Buffer, // and return the Buffer.
[ "printTimestamp", "is", "a", "helper", "method", "to", "append", "a", "timestamp", "into", "a", "bytes", ".", "Buffer", "and", "return", "the", "Buffer", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/binlog_event_rbr.go#L318-L330
train
vitessio/vitess
go/vt/vttablet/tabletserver/vstreamer/vstreamer.go
SetKSchema
func (vs *vstreamer) SetKSchema(kschema *vindexes.KeyspaceSchema) { // Since vs.Stream is a single-threaded loop. We just send an event to // that thread, which helps us avoid mutexes to update the plans. select { case vs.kevents <- kschema: case <-vs.ctx.Done(): } }
go
func (vs *vstreamer) SetKSchema(kschema *vindexes.KeyspaceSchema) { // Since vs.Stream is a single-threaded loop. We just send an event to // that thread, which helps us avoid mutexes to update the plans. select { case vs.kevents <- kschema: case <-vs.ctx.Done(): } }
[ "func", "(", "vs", "*", "vstreamer", ")", "SetKSchema", "(", "kschema", "*", "vindexes", ".", "KeyspaceSchema", ")", "{", "// Since vs.Stream is a single-threaded loop. We just send an event to", "// that thread, which helps us avoid mutexes to update the plans.", "select", "{", "case", "vs", ".", "kevents", "<-", "kschema", ":", "case", "<-", "vs", ".", "ctx", ".", "Done", "(", ")", ":", "}", "\n", "}" ]
// SetKSchema updates all existing against the new kschema.
[ "SetKSchema", "updates", "all", "existing", "against", "the", "new", "kschema", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/vstreamer/vstreamer.go#L88-L95
train
vitessio/vitess
go/vt/vttablet/tabletserver/vstreamer/vstreamer.go
Stream
func (vs *vstreamer) Stream() error { defer vs.cancel() pos, err := mysql.DecodePosition(vs.startPos) if err != nil { return err } vs.pos = pos // Ensure se is Open. If vttablet came up in a non_serving role, // the schema engine may not have been initialized. if err := vs.se.Open(); err != nil { return wrapError(err, vs.pos) } conn, err := binlog.NewSlaveConnection(vs.cp) if err != nil { return wrapError(err, vs.pos) } defer conn.Close() events, err := conn.StartBinlogDumpFromPosition(vs.ctx, vs.pos) if err != nil { return wrapError(err, vs.pos) } err = vs.parseEvents(vs.ctx, events) return wrapError(err, vs.pos) }
go
func (vs *vstreamer) Stream() error { defer vs.cancel() pos, err := mysql.DecodePosition(vs.startPos) if err != nil { return err } vs.pos = pos // Ensure se is Open. If vttablet came up in a non_serving role, // the schema engine may not have been initialized. if err := vs.se.Open(); err != nil { return wrapError(err, vs.pos) } conn, err := binlog.NewSlaveConnection(vs.cp) if err != nil { return wrapError(err, vs.pos) } defer conn.Close() events, err := conn.StartBinlogDumpFromPosition(vs.ctx, vs.pos) if err != nil { return wrapError(err, vs.pos) } err = vs.parseEvents(vs.ctx, events) return wrapError(err, vs.pos) }
[ "func", "(", "vs", "*", "vstreamer", ")", "Stream", "(", ")", "error", "{", "defer", "vs", ".", "cancel", "(", ")", "\n\n", "pos", ",", "err", ":=", "mysql", ".", "DecodePosition", "(", "vs", ".", "startPos", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "vs", ".", "pos", "=", "pos", "\n\n", "// Ensure se is Open. If vttablet came up in a non_serving role,", "// the schema engine may not have been initialized.", "if", "err", ":=", "vs", ".", "se", ".", "Open", "(", ")", ";", "err", "!=", "nil", "{", "return", "wrapError", "(", "err", ",", "vs", ".", "pos", ")", "\n", "}", "\n\n", "conn", ",", "err", ":=", "binlog", ".", "NewSlaveConnection", "(", "vs", ".", "cp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "wrapError", "(", "err", ",", "vs", ".", "pos", ")", "\n", "}", "\n", "defer", "conn", ".", "Close", "(", ")", "\n\n", "events", ",", "err", ":=", "conn", ".", "StartBinlogDumpFromPosition", "(", "vs", ".", "ctx", ",", "vs", ".", "pos", ")", "\n", "if", "err", "!=", "nil", "{", "return", "wrapError", "(", "err", ",", "vs", ".", "pos", ")", "\n", "}", "\n", "err", "=", "vs", ".", "parseEvents", "(", "vs", ".", "ctx", ",", "events", ")", "\n", "return", "wrapError", "(", "err", ",", "vs", ".", "pos", ")", "\n", "}" ]
// Stream runs a single-threaded loop.
[ "Stream", "runs", "a", "single", "-", "threaded", "loop", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/vstreamer/vstreamer.go#L102-L129
train
vitessio/vitess
go/vt/vttablet/tabletserver/query_engine.go
AddStats
func (ep *TabletPlan) AddStats(queryCount int64, duration, mysqlTime time.Duration, rowCount, errorCount int64) { ep.mu.Lock() ep.QueryCount += queryCount ep.Time += duration ep.MysqlTime += mysqlTime ep.RowCount += rowCount ep.ErrorCount += errorCount ep.mu.Unlock() }
go
func (ep *TabletPlan) AddStats(queryCount int64, duration, mysqlTime time.Duration, rowCount, errorCount int64) { ep.mu.Lock() ep.QueryCount += queryCount ep.Time += duration ep.MysqlTime += mysqlTime ep.RowCount += rowCount ep.ErrorCount += errorCount ep.mu.Unlock() }
[ "func", "(", "ep", "*", "TabletPlan", ")", "AddStats", "(", "queryCount", "int64", ",", "duration", ",", "mysqlTime", "time", ".", "Duration", ",", "rowCount", ",", "errorCount", "int64", ")", "{", "ep", ".", "mu", ".", "Lock", "(", ")", "\n", "ep", ".", "QueryCount", "+=", "queryCount", "\n", "ep", ".", "Time", "+=", "duration", "\n", "ep", ".", "MysqlTime", "+=", "mysqlTime", "\n", "ep", ".", "RowCount", "+=", "rowCount", "\n", "ep", ".", "ErrorCount", "+=", "errorCount", "\n", "ep", ".", "mu", ".", "Unlock", "(", ")", "\n", "}" ]
// AddStats updates the stats for the current TabletPlan.
[ "AddStats", "updates", "the", "stats", "for", "the", "current", "TabletPlan", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_engine.go#L79-L87
train
vitessio/vitess
go/vt/vttablet/tabletserver/query_engine.go
buildAuthorized
func (ep *TabletPlan) buildAuthorized() { ep.Authorized = make([]*tableacl.ACLResult, len(ep.Permissions)) for i, perm := range ep.Permissions { ep.Authorized[i] = tableacl.Authorized(perm.TableName, perm.Role) } }
go
func (ep *TabletPlan) buildAuthorized() { ep.Authorized = make([]*tableacl.ACLResult, len(ep.Permissions)) for i, perm := range ep.Permissions { ep.Authorized[i] = tableacl.Authorized(perm.TableName, perm.Role) } }
[ "func", "(", "ep", "*", "TabletPlan", ")", "buildAuthorized", "(", ")", "{", "ep", ".", "Authorized", "=", "make", "(", "[", "]", "*", "tableacl", ".", "ACLResult", ",", "len", "(", "ep", ".", "Permissions", ")", ")", "\n", "for", "i", ",", "perm", ":=", "range", "ep", ".", "Permissions", "{", "ep", ".", "Authorized", "[", "i", "]", "=", "tableacl", ".", "Authorized", "(", "perm", ".", "TableName", ",", "perm", ".", "Role", ")", "\n", "}", "\n", "}" ]
// buildAuthorized builds 'Authorized', which is the runtime part for 'Permissions'.
[ "buildAuthorized", "builds", "Authorized", "which", "is", "the", "runtime", "part", "for", "Permissions", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_engine.go#L102-L107
train
vitessio/vitess
go/vt/vttablet/tabletserver/query_engine.go
Open
func (qe *QueryEngine) Open() error { qe.conns.Open(qe.dbconfigs.AppWithDB(), qe.dbconfigs.DbaWithDB(), qe.dbconfigs.AppDebugWithDB()) conn, err := qe.conns.Get(tabletenv.LocalContext()) if err != nil { qe.conns.Close() return err } qe.binlogFormat, err = conn.VerifyMode(qe.strictTransTables) conn.Recycle() if err != nil { qe.conns.Close() return err } qe.streamConns.Open(qe.dbconfigs.AppWithDB(), qe.dbconfigs.DbaWithDB(), qe.dbconfigs.AppDebugWithDB()) qe.se.RegisterNotifier("qe", qe.schemaChanged) return nil }
go
func (qe *QueryEngine) Open() error { qe.conns.Open(qe.dbconfigs.AppWithDB(), qe.dbconfigs.DbaWithDB(), qe.dbconfigs.AppDebugWithDB()) conn, err := qe.conns.Get(tabletenv.LocalContext()) if err != nil { qe.conns.Close() return err } qe.binlogFormat, err = conn.VerifyMode(qe.strictTransTables) conn.Recycle() if err != nil { qe.conns.Close() return err } qe.streamConns.Open(qe.dbconfigs.AppWithDB(), qe.dbconfigs.DbaWithDB(), qe.dbconfigs.AppDebugWithDB()) qe.se.RegisterNotifier("qe", qe.schemaChanged) return nil }
[ "func", "(", "qe", "*", "QueryEngine", ")", "Open", "(", ")", "error", "{", "qe", ".", "conns", ".", "Open", "(", "qe", ".", "dbconfigs", ".", "AppWithDB", "(", ")", ",", "qe", ".", "dbconfigs", ".", "DbaWithDB", "(", ")", ",", "qe", ".", "dbconfigs", ".", "AppDebugWithDB", "(", ")", ")", "\n\n", "conn", ",", "err", ":=", "qe", ".", "conns", ".", "Get", "(", "tabletenv", ".", "LocalContext", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "qe", ".", "conns", ".", "Close", "(", ")", "\n", "return", "err", "\n", "}", "\n", "qe", ".", "binlogFormat", ",", "err", "=", "conn", ".", "VerifyMode", "(", "qe", ".", "strictTransTables", ")", "\n", "conn", ".", "Recycle", "(", ")", "\n\n", "if", "err", "!=", "nil", "{", "qe", ".", "conns", ".", "Close", "(", ")", "\n", "return", "err", "\n", "}", "\n\n", "qe", ".", "streamConns", ".", "Open", "(", "qe", ".", "dbconfigs", ".", "AppWithDB", "(", ")", ",", "qe", ".", "dbconfigs", ".", "DbaWithDB", "(", ")", ",", "qe", ".", "dbconfigs", ".", "AppDebugWithDB", "(", ")", ")", "\n", "qe", ".", "se", ".", "RegisterNotifier", "(", "\"", "\"", ",", "qe", ".", "schemaChanged", ")", "\n", "return", "nil", "\n", "}" ]
// Open must be called before sending requests to QueryEngine.
[ "Open", "must", "be", "called", "before", "sending", "requests", "to", "QueryEngine", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_engine.go#L285-L304
train
vitessio/vitess
go/vt/vttablet/tabletserver/query_engine.go
Close
func (qe *QueryEngine) Close() { // Close in reverse order of Open. qe.se.UnregisterNotifier("qe") qe.plans.Clear() qe.tables = make(map[string]*schema.Table) qe.streamConns.Close() qe.conns.Close() }
go
func (qe *QueryEngine) Close() { // Close in reverse order of Open. qe.se.UnregisterNotifier("qe") qe.plans.Clear() qe.tables = make(map[string]*schema.Table) qe.streamConns.Close() qe.conns.Close() }
[ "func", "(", "qe", "*", "QueryEngine", ")", "Close", "(", ")", "{", "// Close in reverse order of Open.", "qe", ".", "se", ".", "UnregisterNotifier", "(", "\"", "\"", ")", "\n", "qe", ".", "plans", ".", "Clear", "(", ")", "\n", "qe", ".", "tables", "=", "make", "(", "map", "[", "string", "]", "*", "schema", ".", "Table", ")", "\n", "qe", ".", "streamConns", ".", "Close", "(", ")", "\n", "qe", ".", "conns", ".", "Close", "(", ")", "\n", "}" ]
// Close must be called to shut down QueryEngine. // You must ensure that no more queries will be sent // before calling Close.
[ "Close", "must", "be", "called", "to", "shut", "down", "QueryEngine", ".", "You", "must", "ensure", "that", "no", "more", "queries", "will", "be", "sent", "before", "calling", "Close", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_engine.go#L309-L316
train
vitessio/vitess
go/vt/vttablet/tabletserver/query_engine.go
GetPlan
func (qe *QueryEngine) GetPlan(ctx context.Context, logStats *tabletenv.LogStats, sql string, skipQueryPlanCache bool) (*TabletPlan, error) { span, ctx := trace.NewSpan(ctx, "QueryEngine.GetPlan") defer span.Finish() if plan := qe.getQuery(sql); plan != nil { return plan, nil } // Obtain read lock to prevent schema from changing while // we build a plan. The read lock allows multiple identical // queries to build the same plan. One of them will win by // updating the query cache and prevent future races. Due to // this, query stats reporting may not be accurate, but it's // acceptable because those numbers are best effort. qe.mu.RLock() defer qe.mu.RUnlock() statement, err := sqlparser.Parse(sql) if err != nil { return nil, err } splan, err := planbuilder.Build(statement, qe.tables) if err != nil { return nil, err } plan := &TabletPlan{Plan: splan} plan.Rules = qe.queryRuleSources.FilterByPlan(sql, plan.PlanID, plan.TableName().String()) plan.buildAuthorized() if plan.PlanID.IsSelect() { if plan.FieldQuery != nil { conn, err := qe.getQueryConn(ctx) if err != nil { return nil, err } defer conn.Recycle() sql := plan.FieldQuery.Query start := time.Now() r, err := conn.Exec(ctx, sql, 1, true) logStats.AddRewrittenSQL(sql, start) if err != nil { return nil, err } plan.Fields = r.Fields } } else if plan.PlanID == planbuilder.PlanDDL || plan.PlanID == planbuilder.PlanSet { return plan, nil } if !skipQueryPlanCache && !sqlparser.SkipQueryPlanCacheDirective(statement) { qe.plans.Set(sql, plan) } return plan, nil }
go
func (qe *QueryEngine) GetPlan(ctx context.Context, logStats *tabletenv.LogStats, sql string, skipQueryPlanCache bool) (*TabletPlan, error) { span, ctx := trace.NewSpan(ctx, "QueryEngine.GetPlan") defer span.Finish() if plan := qe.getQuery(sql); plan != nil { return plan, nil } // Obtain read lock to prevent schema from changing while // we build a plan. The read lock allows multiple identical // queries to build the same plan. One of them will win by // updating the query cache and prevent future races. Due to // this, query stats reporting may not be accurate, but it's // acceptable because those numbers are best effort. qe.mu.RLock() defer qe.mu.RUnlock() statement, err := sqlparser.Parse(sql) if err != nil { return nil, err } splan, err := planbuilder.Build(statement, qe.tables) if err != nil { return nil, err } plan := &TabletPlan{Plan: splan} plan.Rules = qe.queryRuleSources.FilterByPlan(sql, plan.PlanID, plan.TableName().String()) plan.buildAuthorized() if plan.PlanID.IsSelect() { if plan.FieldQuery != nil { conn, err := qe.getQueryConn(ctx) if err != nil { return nil, err } defer conn.Recycle() sql := plan.FieldQuery.Query start := time.Now() r, err := conn.Exec(ctx, sql, 1, true) logStats.AddRewrittenSQL(sql, start) if err != nil { return nil, err } plan.Fields = r.Fields } } else if plan.PlanID == planbuilder.PlanDDL || plan.PlanID == planbuilder.PlanSet { return plan, nil } if !skipQueryPlanCache && !sqlparser.SkipQueryPlanCacheDirective(statement) { qe.plans.Set(sql, plan) } return plan, nil }
[ "func", "(", "qe", "*", "QueryEngine", ")", "GetPlan", "(", "ctx", "context", ".", "Context", ",", "logStats", "*", "tabletenv", ".", "LogStats", ",", "sql", "string", ",", "skipQueryPlanCache", "bool", ")", "(", "*", "TabletPlan", ",", "error", ")", "{", "span", ",", "ctx", ":=", "trace", ".", "NewSpan", "(", "ctx", ",", "\"", "\"", ")", "\n", "defer", "span", ".", "Finish", "(", ")", "\n\n", "if", "plan", ":=", "qe", ".", "getQuery", "(", "sql", ")", ";", "plan", "!=", "nil", "{", "return", "plan", ",", "nil", "\n", "}", "\n\n", "// Obtain read lock to prevent schema from changing while", "// we build a plan. The read lock allows multiple identical", "// queries to build the same plan. One of them will win by", "// updating the query cache and prevent future races. Due to", "// this, query stats reporting may not be accurate, but it's", "// acceptable because those numbers are best effort.", "qe", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "qe", ".", "mu", ".", "RUnlock", "(", ")", "\n", "statement", ",", "err", ":=", "sqlparser", ".", "Parse", "(", "sql", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "splan", ",", "err", ":=", "planbuilder", ".", "Build", "(", "statement", ",", "qe", ".", "tables", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "plan", ":=", "&", "TabletPlan", "{", "Plan", ":", "splan", "}", "\n", "plan", ".", "Rules", "=", "qe", ".", "queryRuleSources", ".", "FilterByPlan", "(", "sql", ",", "plan", ".", "PlanID", ",", "plan", ".", "TableName", "(", ")", ".", "String", "(", ")", ")", "\n", "plan", ".", "buildAuthorized", "(", ")", "\n", "if", "plan", ".", "PlanID", ".", "IsSelect", "(", ")", "{", "if", "plan", ".", "FieldQuery", "!=", "nil", "{", "conn", ",", "err", ":=", "qe", ".", "getQueryConn", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "conn", ".", "Recycle", "(", ")", "\n\n", "sql", ":=", "plan", ".", "FieldQuery", ".", "Query", "\n", "start", ":=", "time", ".", "Now", "(", ")", "\n", "r", ",", "err", ":=", "conn", ".", "Exec", "(", "ctx", ",", "sql", ",", "1", ",", "true", ")", "\n", "logStats", ".", "AddRewrittenSQL", "(", "sql", ",", "start", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "plan", ".", "Fields", "=", "r", ".", "Fields", "\n", "}", "\n", "}", "else", "if", "plan", ".", "PlanID", "==", "planbuilder", ".", "PlanDDL", "||", "plan", ".", "PlanID", "==", "planbuilder", ".", "PlanSet", "{", "return", "plan", ",", "nil", "\n", "}", "\n", "if", "!", "skipQueryPlanCache", "&&", "!", "sqlparser", ".", "SkipQueryPlanCacheDirective", "(", "statement", ")", "{", "qe", ".", "plans", ".", "Set", "(", "sql", ",", "plan", ")", "\n", "}", "\n", "return", "plan", ",", "nil", "\n", "}" ]
// GetPlan returns the TabletPlan that for the query. Plans are cached in a cache.LRUCache.
[ "GetPlan", "returns", "the", "TabletPlan", "that", "for", "the", "query", ".", "Plans", "are", "cached", "in", "a", "cache", ".", "LRUCache", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_engine.go#L319-L370
train
vitessio/vitess
go/vt/vttablet/tabletserver/query_engine.go
getQueryConn
func (qe *QueryEngine) getQueryConn(ctx context.Context) (*connpool.DBConn, error) { waiterCount := qe.queryPoolWaiters.Add(1) defer qe.queryPoolWaiters.Add(-1) if waiterCount > qe.queryPoolWaiterCap.Get() { return nil, vterrors.New(vtrpcpb.Code_RESOURCE_EXHAUSTED, "query pool waiter count exceeded") } timeout := qe.connTimeout.Get() if timeout != 0 { ctxTimeout, cancel := context.WithTimeout(ctx, timeout) defer cancel() conn, err := qe.conns.Get(ctxTimeout) if err != nil { return nil, vterrors.Errorf(vtrpcpb.Code_RESOURCE_EXHAUSTED, "query pool wait time exceeded") } return conn, err } return qe.conns.Get(ctx) }
go
func (qe *QueryEngine) getQueryConn(ctx context.Context) (*connpool.DBConn, error) { waiterCount := qe.queryPoolWaiters.Add(1) defer qe.queryPoolWaiters.Add(-1) if waiterCount > qe.queryPoolWaiterCap.Get() { return nil, vterrors.New(vtrpcpb.Code_RESOURCE_EXHAUSTED, "query pool waiter count exceeded") } timeout := qe.connTimeout.Get() if timeout != 0 { ctxTimeout, cancel := context.WithTimeout(ctx, timeout) defer cancel() conn, err := qe.conns.Get(ctxTimeout) if err != nil { return nil, vterrors.Errorf(vtrpcpb.Code_RESOURCE_EXHAUSTED, "query pool wait time exceeded") } return conn, err } return qe.conns.Get(ctx) }
[ "func", "(", "qe", "*", "QueryEngine", ")", "getQueryConn", "(", "ctx", "context", ".", "Context", ")", "(", "*", "connpool", ".", "DBConn", ",", "error", ")", "{", "waiterCount", ":=", "qe", ".", "queryPoolWaiters", ".", "Add", "(", "1", ")", "\n", "defer", "qe", ".", "queryPoolWaiters", ".", "Add", "(", "-", "1", ")", "\n\n", "if", "waiterCount", ">", "qe", ".", "queryPoolWaiterCap", ".", "Get", "(", ")", "{", "return", "nil", ",", "vterrors", ".", "New", "(", "vtrpcpb", ".", "Code_RESOURCE_EXHAUSTED", ",", "\"", "\"", ")", "\n", "}", "\n\n", "timeout", ":=", "qe", ".", "connTimeout", ".", "Get", "(", ")", "\n", "if", "timeout", "!=", "0", "{", "ctxTimeout", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "ctx", ",", "timeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "conn", ",", "err", ":=", "qe", ".", "conns", ".", "Get", "(", "ctxTimeout", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_RESOURCE_EXHAUSTED", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "conn", ",", "err", "\n", "}", "\n", "return", "qe", ".", "conns", ".", "Get", "(", "ctx", ")", "\n", "}" ]
// getQueryConn returns a connection from the query pool using either // the conn pool timeout if configured, or the original context query timeout
[ "getQueryConn", "returns", "a", "connection", "from", "the", "query", "pool", "using", "either", "the", "conn", "pool", "timeout", "if", "configured", "or", "the", "original", "context", "query", "timeout" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_engine.go#L374-L393
train
vitessio/vitess
go/vt/vttablet/tabletserver/query_engine.go
GetStreamPlan
func (qe *QueryEngine) GetStreamPlan(sql string) (*TabletPlan, error) { qe.mu.RLock() defer qe.mu.RUnlock() splan, err := planbuilder.BuildStreaming(sql, qe.tables) if err != nil { return nil, err } plan := &TabletPlan{Plan: splan} plan.Rules = qe.queryRuleSources.FilterByPlan(sql, plan.PlanID, plan.TableName().String()) plan.buildAuthorized() return plan, nil }
go
func (qe *QueryEngine) GetStreamPlan(sql string) (*TabletPlan, error) { qe.mu.RLock() defer qe.mu.RUnlock() splan, err := planbuilder.BuildStreaming(sql, qe.tables) if err != nil { return nil, err } plan := &TabletPlan{Plan: splan} plan.Rules = qe.queryRuleSources.FilterByPlan(sql, plan.PlanID, plan.TableName().String()) plan.buildAuthorized() return plan, nil }
[ "func", "(", "qe", "*", "QueryEngine", ")", "GetStreamPlan", "(", "sql", "string", ")", "(", "*", "TabletPlan", ",", "error", ")", "{", "qe", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "qe", ".", "mu", ".", "RUnlock", "(", ")", "\n", "splan", ",", "err", ":=", "planbuilder", ".", "BuildStreaming", "(", "sql", ",", "qe", ".", "tables", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "plan", ":=", "&", "TabletPlan", "{", "Plan", ":", "splan", "}", "\n", "plan", ".", "Rules", "=", "qe", ".", "queryRuleSources", ".", "FilterByPlan", "(", "sql", ",", "plan", ".", "PlanID", ",", "plan", ".", "TableName", "(", ")", ".", "String", "(", ")", ")", "\n", "plan", ".", "buildAuthorized", "(", ")", "\n", "return", "plan", ",", "nil", "\n", "}" ]
// GetStreamPlan is similar to GetPlan, but doesn't use the cache // and doesn't enforce a limit. It just returns the parsed query.
[ "GetStreamPlan", "is", "similar", "to", "GetPlan", "but", "doesn", "t", "use", "the", "cache", "and", "doesn", "t", "enforce", "a", "limit", ".", "It", "just", "returns", "the", "parsed", "query", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_engine.go#L397-L408
train
vitessio/vitess
go/vt/vttablet/tabletserver/query_engine.go
GetMessageStreamPlan
func (qe *QueryEngine) GetMessageStreamPlan(name string) (*TabletPlan, error) { qe.mu.RLock() defer qe.mu.RUnlock() splan, err := planbuilder.BuildMessageStreaming(name, qe.tables) if err != nil { return nil, err } plan := &TabletPlan{Plan: splan} plan.Rules = qe.queryRuleSources.FilterByPlan("stream from "+name, plan.PlanID, plan.TableName().String()) plan.buildAuthorized() return plan, nil }
go
func (qe *QueryEngine) GetMessageStreamPlan(name string) (*TabletPlan, error) { qe.mu.RLock() defer qe.mu.RUnlock() splan, err := planbuilder.BuildMessageStreaming(name, qe.tables) if err != nil { return nil, err } plan := &TabletPlan{Plan: splan} plan.Rules = qe.queryRuleSources.FilterByPlan("stream from "+name, plan.PlanID, plan.TableName().String()) plan.buildAuthorized() return plan, nil }
[ "func", "(", "qe", "*", "QueryEngine", ")", "GetMessageStreamPlan", "(", "name", "string", ")", "(", "*", "TabletPlan", ",", "error", ")", "{", "qe", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "qe", ".", "mu", ".", "RUnlock", "(", ")", "\n", "splan", ",", "err", ":=", "planbuilder", ".", "BuildMessageStreaming", "(", "name", ",", "qe", ".", "tables", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "plan", ":=", "&", "TabletPlan", "{", "Plan", ":", "splan", "}", "\n", "plan", ".", "Rules", "=", "qe", ".", "queryRuleSources", ".", "FilterByPlan", "(", "\"", "\"", "+", "name", ",", "plan", ".", "PlanID", ",", "plan", ".", "TableName", "(", ")", ".", "String", "(", ")", ")", "\n", "plan", ".", "buildAuthorized", "(", ")", "\n", "return", "plan", ",", "nil", "\n", "}" ]
// GetMessageStreamPlan builds a plan for Message streaming.
[ "GetMessageStreamPlan", "builds", "a", "plan", "for", "Message", "streaming", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_engine.go#L411-L422
train
vitessio/vitess
go/vt/vttablet/tabletserver/query_engine.go
IsMySQLReachable
func (qe *QueryEngine) IsMySQLReachable() bool { conn, err := dbconnpool.NewDBConnection(qe.dbconfigs.AppWithDB(), tabletenv.MySQLStats) if err != nil { if mysql.IsConnErr(err) { return false } log.Warningf("checking MySQL, unexpected error: %v", err) return true } conn.Close() return true }
go
func (qe *QueryEngine) IsMySQLReachable() bool { conn, err := dbconnpool.NewDBConnection(qe.dbconfigs.AppWithDB(), tabletenv.MySQLStats) if err != nil { if mysql.IsConnErr(err) { return false } log.Warningf("checking MySQL, unexpected error: %v", err) return true } conn.Close() return true }
[ "func", "(", "qe", "*", "QueryEngine", ")", "IsMySQLReachable", "(", ")", "bool", "{", "conn", ",", "err", ":=", "dbconnpool", ".", "NewDBConnection", "(", "qe", ".", "dbconfigs", ".", "AppWithDB", "(", ")", ",", "tabletenv", ".", "MySQLStats", ")", "\n", "if", "err", "!=", "nil", "{", "if", "mysql", ".", "IsConnErr", "(", "err", ")", "{", "return", "false", "\n", "}", "\n", "log", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "true", "\n", "}", "\n", "conn", ".", "Close", "(", ")", "\n", "return", "true", "\n", "}" ]
// IsMySQLReachable returns true if we can connect to MySQL.
[ "IsMySQLReachable", "returns", "true", "if", "we", "can", "connect", "to", "MySQL", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_engine.go#L430-L441
train
vitessio/vitess
go/vt/vttablet/tabletserver/query_engine.go
getQuery
func (qe *QueryEngine) getQuery(sql string) *TabletPlan { if cacheResult, ok := qe.plans.Get(sql); ok { return cacheResult.(*TabletPlan) } return nil }
go
func (qe *QueryEngine) getQuery(sql string) *TabletPlan { if cacheResult, ok := qe.plans.Get(sql); ok { return cacheResult.(*TabletPlan) } return nil }
[ "func", "(", "qe", "*", "QueryEngine", ")", "getQuery", "(", "sql", "string", ")", "*", "TabletPlan", "{", "if", "cacheResult", ",", "ok", ":=", "qe", ".", "plans", ".", "Get", "(", "sql", ")", ";", "ok", "{", "return", "cacheResult", ".", "(", "*", "TabletPlan", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// getQuery fetches the plan and makes it the most recent.
[ "getQuery", "fetches", "the", "plan", "and", "makes", "it", "the", "most", "recent", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_engine.go#L453-L458
train
vitessio/vitess
go/vt/vttablet/tabletserver/query_engine.go
peekQuery
func (qe *QueryEngine) peekQuery(sql string) *TabletPlan { if cacheResult, ok := qe.plans.Peek(sql); ok { return cacheResult.(*TabletPlan) } return nil }
go
func (qe *QueryEngine) peekQuery(sql string) *TabletPlan { if cacheResult, ok := qe.plans.Peek(sql); ok { return cacheResult.(*TabletPlan) } return nil }
[ "func", "(", "qe", "*", "QueryEngine", ")", "peekQuery", "(", "sql", "string", ")", "*", "TabletPlan", "{", "if", "cacheResult", ",", "ok", ":=", "qe", ".", "plans", ".", "Peek", "(", "sql", ")", ";", "ok", "{", "return", "cacheResult", ".", "(", "*", "TabletPlan", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// peekQuery fetches the plan without changing the LRU order.
[ "peekQuery", "fetches", "the", "plan", "without", "changing", "the", "LRU", "order", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_engine.go#L461-L466
train
vitessio/vitess
go/vt/vttablet/tabletserver/query_engine.go
SetQueryPlanCacheCap
func (qe *QueryEngine) SetQueryPlanCacheCap(size int) { if size <= 0 { size = 1 } qe.plans.SetCapacity(int64(size)) }
go
func (qe *QueryEngine) SetQueryPlanCacheCap(size int) { if size <= 0 { size = 1 } qe.plans.SetCapacity(int64(size)) }
[ "func", "(", "qe", "*", "QueryEngine", ")", "SetQueryPlanCacheCap", "(", "size", "int", ")", "{", "if", "size", "<=", "0", "{", "size", "=", "1", "\n", "}", "\n", "qe", ".", "plans", ".", "SetCapacity", "(", "int64", "(", "size", ")", ")", "\n", "}" ]
// SetQueryPlanCacheCap sets the query plan cache capacity.
[ "SetQueryPlanCacheCap", "sets", "the", "query", "plan", "cache", "capacity", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_engine.go#L469-L474
train
vitessio/vitess
go/vt/vttablet/tabletserver/query_engine.go
AddStats
func (qe *QueryEngine) AddStats(planName, tableName string, queryCount int64, duration, mysqlTime time.Duration, rowCount, errorCount int64) { key := tableName + "." + planName qe.queryStatsMu.RLock() stats, ok := qe.queryStats[key] qe.queryStatsMu.RUnlock() if !ok { // Check again with the write lock held and // create a new record only if none exists qe.queryStatsMu.Lock() if stats, ok = qe.queryStats[key]; !ok { stats = &QueryStats{} qe.queryStats[key] = stats } qe.queryStatsMu.Unlock() } stats.mu.Lock() stats.queryCount += queryCount stats.time += duration stats.mysqlTime += mysqlTime stats.rowCount += rowCount stats.errorCount += errorCount stats.mu.Unlock() }
go
func (qe *QueryEngine) AddStats(planName, tableName string, queryCount int64, duration, mysqlTime time.Duration, rowCount, errorCount int64) { key := tableName + "." + planName qe.queryStatsMu.RLock() stats, ok := qe.queryStats[key] qe.queryStatsMu.RUnlock() if !ok { // Check again with the write lock held and // create a new record only if none exists qe.queryStatsMu.Lock() if stats, ok = qe.queryStats[key]; !ok { stats = &QueryStats{} qe.queryStats[key] = stats } qe.queryStatsMu.Unlock() } stats.mu.Lock() stats.queryCount += queryCount stats.time += duration stats.mysqlTime += mysqlTime stats.rowCount += rowCount stats.errorCount += errorCount stats.mu.Unlock() }
[ "func", "(", "qe", "*", "QueryEngine", ")", "AddStats", "(", "planName", ",", "tableName", "string", ",", "queryCount", "int64", ",", "duration", ",", "mysqlTime", "time", ".", "Duration", ",", "rowCount", ",", "errorCount", "int64", ")", "{", "key", ":=", "tableName", "+", "\"", "\"", "+", "planName", "\n\n", "qe", ".", "queryStatsMu", ".", "RLock", "(", ")", "\n", "stats", ",", "ok", ":=", "qe", ".", "queryStats", "[", "key", "]", "\n", "qe", ".", "queryStatsMu", ".", "RUnlock", "(", ")", "\n\n", "if", "!", "ok", "{", "// Check again with the write lock held and", "// create a new record only if none exists", "qe", ".", "queryStatsMu", ".", "Lock", "(", ")", "\n", "if", "stats", ",", "ok", "=", "qe", ".", "queryStats", "[", "key", "]", ";", "!", "ok", "{", "stats", "=", "&", "QueryStats", "{", "}", "\n", "qe", ".", "queryStats", "[", "key", "]", "=", "stats", "\n", "}", "\n", "qe", ".", "queryStatsMu", ".", "Unlock", "(", ")", "\n", "}", "\n\n", "stats", ".", "mu", ".", "Lock", "(", ")", "\n", "stats", ".", "queryCount", "+=", "queryCount", "\n", "stats", ".", "time", "+=", "duration", "\n", "stats", ".", "mysqlTime", "+=", "mysqlTime", "\n", "stats", ".", "rowCount", "+=", "rowCount", "\n", "stats", ".", "errorCount", "+=", "errorCount", "\n", "stats", ".", "mu", ".", "Unlock", "(", ")", "\n", "}" ]
// AddStats adds the given stats for the planName.tableName
[ "AddStats", "adds", "the", "given", "stats", "for", "the", "planName", ".", "tableName" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_engine.go#L492-L517
train
vitessio/vitess
go/vt/mysqlctl/s3backupstorage/s3.go
AddFile
func (bh *S3BackupHandle) AddFile(ctx context.Context, filename string, filesize int64) (io.WriteCloser, error) { if bh.readOnly { return nil, fmt.Errorf("AddFile cannot be called on read-only backup") } // Calculate s3 upload part size using the source filesize partSizeBytes := s3manager.DefaultUploadPartSize if filesize > 0 { minimumPartSize := float64(filesize) / float64(s3manager.MaxUploadParts) // Round up to ensure large enough partsize calculatedPartSizeBytes := int64(math.Ceil(minimumPartSize)) if calculatedPartSizeBytes > partSizeBytes { partSizeBytes = calculatedPartSizeBytes } } reader, writer := io.Pipe() bh.waitGroup.Add(1) go func() { defer bh.waitGroup.Done() uploader := s3manager.NewUploaderWithClient(bh.client, func(u *s3manager.Uploader) { u.PartSize = partSizeBytes }) object := objName(bh.dir, bh.name, filename) var sseOption *string if *sse != "" { sseOption = sse } _, err := uploader.Upload(&s3manager.UploadInput{ Bucket: bucket, Key: object, Body: reader, ServerSideEncryption: sseOption, }) if err != nil { reader.CloseWithError(err) bh.errors.RecordError(err) } }() return writer, nil }
go
func (bh *S3BackupHandle) AddFile(ctx context.Context, filename string, filesize int64) (io.WriteCloser, error) { if bh.readOnly { return nil, fmt.Errorf("AddFile cannot be called on read-only backup") } // Calculate s3 upload part size using the source filesize partSizeBytes := s3manager.DefaultUploadPartSize if filesize > 0 { minimumPartSize := float64(filesize) / float64(s3manager.MaxUploadParts) // Round up to ensure large enough partsize calculatedPartSizeBytes := int64(math.Ceil(minimumPartSize)) if calculatedPartSizeBytes > partSizeBytes { partSizeBytes = calculatedPartSizeBytes } } reader, writer := io.Pipe() bh.waitGroup.Add(1) go func() { defer bh.waitGroup.Done() uploader := s3manager.NewUploaderWithClient(bh.client, func(u *s3manager.Uploader) { u.PartSize = partSizeBytes }) object := objName(bh.dir, bh.name, filename) var sseOption *string if *sse != "" { sseOption = sse } _, err := uploader.Upload(&s3manager.UploadInput{ Bucket: bucket, Key: object, Body: reader, ServerSideEncryption: sseOption, }) if err != nil { reader.CloseWithError(err) bh.errors.RecordError(err) } }() return writer, nil }
[ "func", "(", "bh", "*", "S3BackupHandle", ")", "AddFile", "(", "ctx", "context", ".", "Context", ",", "filename", "string", ",", "filesize", "int64", ")", "(", "io", ".", "WriteCloser", ",", "error", ")", "{", "if", "bh", ".", "readOnly", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Calculate s3 upload part size using the source filesize", "partSizeBytes", ":=", "s3manager", ".", "DefaultUploadPartSize", "\n", "if", "filesize", ">", "0", "{", "minimumPartSize", ":=", "float64", "(", "filesize", ")", "/", "float64", "(", "s3manager", ".", "MaxUploadParts", ")", "\n", "// Round up to ensure large enough partsize", "calculatedPartSizeBytes", ":=", "int64", "(", "math", ".", "Ceil", "(", "minimumPartSize", ")", ")", "\n", "if", "calculatedPartSizeBytes", ">", "partSizeBytes", "{", "partSizeBytes", "=", "calculatedPartSizeBytes", "\n", "}", "\n", "}", "\n\n", "reader", ",", "writer", ":=", "io", ".", "Pipe", "(", ")", "\n", "bh", ".", "waitGroup", ".", "Add", "(", "1", ")", "\n\n", "go", "func", "(", ")", "{", "defer", "bh", ".", "waitGroup", ".", "Done", "(", ")", "\n", "uploader", ":=", "s3manager", ".", "NewUploaderWithClient", "(", "bh", ".", "client", ",", "func", "(", "u", "*", "s3manager", ".", "Uploader", ")", "{", "u", ".", "PartSize", "=", "partSizeBytes", "\n", "}", ")", "\n", "object", ":=", "objName", "(", "bh", ".", "dir", ",", "bh", ".", "name", ",", "filename", ")", "\n\n", "var", "sseOption", "*", "string", "\n", "if", "*", "sse", "!=", "\"", "\"", "{", "sseOption", "=", "sse", "\n", "}", "\n", "_", ",", "err", ":=", "uploader", ".", "Upload", "(", "&", "s3manager", ".", "UploadInput", "{", "Bucket", ":", "bucket", ",", "Key", ":", "object", ",", "Body", ":", "reader", ",", "ServerSideEncryption", ":", "sseOption", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "reader", ".", "CloseWithError", "(", "err", ")", "\n", "bh", ".", "errors", ".", "RecordError", "(", "err", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "return", "writer", ",", "nil", "\n", "}" ]
// AddFile is part of the backupstorage.BackupHandle interface.
[ "AddFile", "is", "part", "of", "the", "backupstorage", ".", "BackupHandle", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/s3backupstorage/s3.go#L103-L146
train
vitessio/vitess
go/vt/mysqlctl/s3backupstorage/s3.go
EndBackup
func (bh *S3BackupHandle) EndBackup(ctx context.Context) error { if bh.readOnly { return fmt.Errorf("EndBackup cannot be called on read-only backup") } bh.waitGroup.Wait() return bh.errors.Error() }
go
func (bh *S3BackupHandle) EndBackup(ctx context.Context) error { if bh.readOnly { return fmt.Errorf("EndBackup cannot be called on read-only backup") } bh.waitGroup.Wait() return bh.errors.Error() }
[ "func", "(", "bh", "*", "S3BackupHandle", ")", "EndBackup", "(", "ctx", "context", ".", "Context", ")", "error", "{", "if", "bh", ".", "readOnly", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "bh", ".", "waitGroup", ".", "Wait", "(", ")", "\n", "return", "bh", ".", "errors", ".", "Error", "(", ")", "\n", "}" ]
// EndBackup is part of the backupstorage.BackupHandle interface.
[ "EndBackup", "is", "part", "of", "the", "backupstorage", ".", "BackupHandle", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/s3backupstorage/s3.go#L149-L155
train
vitessio/vitess
go/vt/mysqlctl/s3backupstorage/s3.go
ReadFile
func (bh *S3BackupHandle) ReadFile(ctx context.Context, filename string) (io.ReadCloser, error) { if !bh.readOnly { return nil, fmt.Errorf("ReadFile cannot be called on read-write backup") } object := objName(bh.dir, bh.name, filename) out, err := bh.client.GetObject(&s3.GetObjectInput{ Bucket: bucket, Key: object, }) if err != nil { return nil, err } return out.Body, nil }
go
func (bh *S3BackupHandle) ReadFile(ctx context.Context, filename string) (io.ReadCloser, error) { if !bh.readOnly { return nil, fmt.Errorf("ReadFile cannot be called on read-write backup") } object := objName(bh.dir, bh.name, filename) out, err := bh.client.GetObject(&s3.GetObjectInput{ Bucket: bucket, Key: object, }) if err != nil { return nil, err } return out.Body, nil }
[ "func", "(", "bh", "*", "S3BackupHandle", ")", "ReadFile", "(", "ctx", "context", ".", "Context", ",", "filename", "string", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", "{", "if", "!", "bh", ".", "readOnly", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "object", ":=", "objName", "(", "bh", ".", "dir", ",", "bh", ".", "name", ",", "filename", ")", "\n", "out", ",", "err", ":=", "bh", ".", "client", ".", "GetObject", "(", "&", "s3", ".", "GetObjectInput", "{", "Bucket", ":", "bucket", ",", "Key", ":", "object", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "out", ".", "Body", ",", "nil", "\n", "}" ]
// ReadFile is part of the backupstorage.BackupHandle interface.
[ "ReadFile", "is", "part", "of", "the", "backupstorage", ".", "BackupHandle", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/s3backupstorage/s3.go#L166-L179
train
vitessio/vitess
go/vt/mysqlctl/s3backupstorage/s3.go
ListBackups
func (bs *S3BackupStorage) ListBackups(ctx context.Context, dir string) ([]backupstorage.BackupHandle, error) { log.Infof("ListBackups: [s3] dir: %v, bucket: %v", dir, *bucket) c, err := bs.client() if err != nil { return nil, err } searchPrefix := objName(dir, "") query := &s3.ListObjectsV2Input{ Bucket: bucket, Delimiter: &delimiter, Prefix: searchPrefix, } var subdirs []string for { objs, err := c.ListObjectsV2(query) if err != nil { return nil, err } for _, prefix := range objs.CommonPrefixes { subdir := strings.TrimPrefix(*prefix.Prefix, *searchPrefix) subdir = strings.TrimSuffix(subdir, delimiter) subdirs = append(subdirs, subdir) } if objs.NextContinuationToken == nil { break } query.ContinuationToken = objs.NextContinuationToken } // Backups must be returned in order, oldest first. sort.Strings(subdirs) result := make([]backupstorage.BackupHandle, 0, len(subdirs)) for _, subdir := range subdirs { result = append(result, &S3BackupHandle{ client: c, bs: bs, dir: dir, name: subdir, readOnly: true, }) } return result, nil }
go
func (bs *S3BackupStorage) ListBackups(ctx context.Context, dir string) ([]backupstorage.BackupHandle, error) { log.Infof("ListBackups: [s3] dir: %v, bucket: %v", dir, *bucket) c, err := bs.client() if err != nil { return nil, err } searchPrefix := objName(dir, "") query := &s3.ListObjectsV2Input{ Bucket: bucket, Delimiter: &delimiter, Prefix: searchPrefix, } var subdirs []string for { objs, err := c.ListObjectsV2(query) if err != nil { return nil, err } for _, prefix := range objs.CommonPrefixes { subdir := strings.TrimPrefix(*prefix.Prefix, *searchPrefix) subdir = strings.TrimSuffix(subdir, delimiter) subdirs = append(subdirs, subdir) } if objs.NextContinuationToken == nil { break } query.ContinuationToken = objs.NextContinuationToken } // Backups must be returned in order, oldest first. sort.Strings(subdirs) result := make([]backupstorage.BackupHandle, 0, len(subdirs)) for _, subdir := range subdirs { result = append(result, &S3BackupHandle{ client: c, bs: bs, dir: dir, name: subdir, readOnly: true, }) } return result, nil }
[ "func", "(", "bs", "*", "S3BackupStorage", ")", "ListBackups", "(", "ctx", "context", ".", "Context", ",", "dir", "string", ")", "(", "[", "]", "backupstorage", ".", "BackupHandle", ",", "error", ")", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "dir", ",", "*", "bucket", ")", "\n", "c", ",", "err", ":=", "bs", ".", "client", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "searchPrefix", ":=", "objName", "(", "dir", ",", "\"", "\"", ")", "\n", "query", ":=", "&", "s3", ".", "ListObjectsV2Input", "{", "Bucket", ":", "bucket", ",", "Delimiter", ":", "&", "delimiter", ",", "Prefix", ":", "searchPrefix", ",", "}", "\n\n", "var", "subdirs", "[", "]", "string", "\n", "for", "{", "objs", ",", "err", ":=", "c", ".", "ListObjectsV2", "(", "query", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "prefix", ":=", "range", "objs", ".", "CommonPrefixes", "{", "subdir", ":=", "strings", ".", "TrimPrefix", "(", "*", "prefix", ".", "Prefix", ",", "*", "searchPrefix", ")", "\n", "subdir", "=", "strings", ".", "TrimSuffix", "(", "subdir", ",", "delimiter", ")", "\n", "subdirs", "=", "append", "(", "subdirs", ",", "subdir", ")", "\n", "}", "\n\n", "if", "objs", ".", "NextContinuationToken", "==", "nil", "{", "break", "\n", "}", "\n", "query", ".", "ContinuationToken", "=", "objs", ".", "NextContinuationToken", "\n", "}", "\n\n", "// Backups must be returned in order, oldest first.", "sort", ".", "Strings", "(", "subdirs", ")", "\n\n", "result", ":=", "make", "(", "[", "]", "backupstorage", ".", "BackupHandle", ",", "0", ",", "len", "(", "subdirs", ")", ")", "\n", "for", "_", ",", "subdir", ":=", "range", "subdirs", "{", "result", "=", "append", "(", "result", ",", "&", "S3BackupHandle", "{", "client", ":", "c", ",", "bs", ":", "bs", ",", "dir", ":", "dir", ",", "name", ":", "subdir", ",", "readOnly", ":", "true", ",", "}", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// ListBackups is part of the backupstorage.BackupStorage interface.
[ "ListBackups", "is", "part", "of", "the", "backupstorage", ".", "BackupStorage", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/s3backupstorage/s3.go#L190-L236
train
vitessio/vitess
go/vt/mysqlctl/s3backupstorage/s3.go
StartBackup
func (bs *S3BackupStorage) StartBackup(ctx context.Context, dir, name string) (backupstorage.BackupHandle, error) { log.Infof("StartBackup: [s3] dir: %v, name: %v, bucket: %v", dir, name, *bucket) c, err := bs.client() if err != nil { return nil, err } return &S3BackupHandle{ client: c, bs: bs, dir: dir, name: name, readOnly: false, }, nil }
go
func (bs *S3BackupStorage) StartBackup(ctx context.Context, dir, name string) (backupstorage.BackupHandle, error) { log.Infof("StartBackup: [s3] dir: %v, name: %v, bucket: %v", dir, name, *bucket) c, err := bs.client() if err != nil { return nil, err } return &S3BackupHandle{ client: c, bs: bs, dir: dir, name: name, readOnly: false, }, nil }
[ "func", "(", "bs", "*", "S3BackupStorage", ")", "StartBackup", "(", "ctx", "context", ".", "Context", ",", "dir", ",", "name", "string", ")", "(", "backupstorage", ".", "BackupHandle", ",", "error", ")", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "dir", ",", "name", ",", "*", "bucket", ")", "\n", "c", ",", "err", ":=", "bs", ".", "client", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "S3BackupHandle", "{", "client", ":", "c", ",", "bs", ":", "bs", ",", "dir", ":", "dir", ",", "name", ":", "name", ",", "readOnly", ":", "false", ",", "}", ",", "nil", "\n", "}" ]
// StartBackup is part of the backupstorage.BackupStorage interface.
[ "StartBackup", "is", "part", "of", "the", "backupstorage", ".", "BackupStorage", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/s3backupstorage/s3.go#L239-L253
train
vitessio/vitess
go/vt/mysqlctl/s3backupstorage/s3.go
RemoveBackup
func (bs *S3BackupStorage) RemoveBackup(ctx context.Context, dir, name string) error { log.Infof("RemoveBackup: [s3] dir: %v, name: %v, bucket: %v", dir, name, *bucket) c, err := bs.client() if err != nil { return err } query := &s3.ListObjectsV2Input{ Bucket: bucket, Prefix: objName(dir, name), } for { objs, err := c.ListObjectsV2(query) if err != nil { return err } objIds := make([]*s3.ObjectIdentifier, 0, len(objs.Contents)) for _, obj := range objs.Contents { objIds = append(objIds, &s3.ObjectIdentifier{ Key: obj.Key, }) } quiet := true // return less in the Delete response out, err := c.DeleteObjects(&s3.DeleteObjectsInput{ Bucket: bucket, Delete: &s3.Delete{ Objects: objIds, Quiet: &quiet, }, }) if err != nil { return err } for _, objError := range out.Errors { return fmt.Errorf(objError.String()) } if objs.NextContinuationToken == nil { break } query.ContinuationToken = objs.NextContinuationToken } return nil }
go
func (bs *S3BackupStorage) RemoveBackup(ctx context.Context, dir, name string) error { log.Infof("RemoveBackup: [s3] dir: %v, name: %v, bucket: %v", dir, name, *bucket) c, err := bs.client() if err != nil { return err } query := &s3.ListObjectsV2Input{ Bucket: bucket, Prefix: objName(dir, name), } for { objs, err := c.ListObjectsV2(query) if err != nil { return err } objIds := make([]*s3.ObjectIdentifier, 0, len(objs.Contents)) for _, obj := range objs.Contents { objIds = append(objIds, &s3.ObjectIdentifier{ Key: obj.Key, }) } quiet := true // return less in the Delete response out, err := c.DeleteObjects(&s3.DeleteObjectsInput{ Bucket: bucket, Delete: &s3.Delete{ Objects: objIds, Quiet: &quiet, }, }) if err != nil { return err } for _, objError := range out.Errors { return fmt.Errorf(objError.String()) } if objs.NextContinuationToken == nil { break } query.ContinuationToken = objs.NextContinuationToken } return nil }
[ "func", "(", "bs", "*", "S3BackupStorage", ")", "RemoveBackup", "(", "ctx", "context", ".", "Context", ",", "dir", ",", "name", "string", ")", "error", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "dir", ",", "name", ",", "*", "bucket", ")", "\n\n", "c", ",", "err", ":=", "bs", ".", "client", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "query", ":=", "&", "s3", ".", "ListObjectsV2Input", "{", "Bucket", ":", "bucket", ",", "Prefix", ":", "objName", "(", "dir", ",", "name", ")", ",", "}", "\n\n", "for", "{", "objs", ",", "err", ":=", "c", ".", "ListObjectsV2", "(", "query", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "objIds", ":=", "make", "(", "[", "]", "*", "s3", ".", "ObjectIdentifier", ",", "0", ",", "len", "(", "objs", ".", "Contents", ")", ")", "\n", "for", "_", ",", "obj", ":=", "range", "objs", ".", "Contents", "{", "objIds", "=", "append", "(", "objIds", ",", "&", "s3", ".", "ObjectIdentifier", "{", "Key", ":", "obj", ".", "Key", ",", "}", ")", "\n", "}", "\n\n", "quiet", ":=", "true", "// return less in the Delete response", "\n", "out", ",", "err", ":=", "c", ".", "DeleteObjects", "(", "&", "s3", ".", "DeleteObjectsInput", "{", "Bucket", ":", "bucket", ",", "Delete", ":", "&", "s3", ".", "Delete", "{", "Objects", ":", "objIds", ",", "Quiet", ":", "&", "quiet", ",", "}", ",", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "for", "_", ",", "objError", ":=", "range", "out", ".", "Errors", "{", "return", "fmt", ".", "Errorf", "(", "objError", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "if", "objs", ".", "NextContinuationToken", "==", "nil", "{", "break", "\n", "}", "\n\n", "query", ".", "ContinuationToken", "=", "objs", ".", "NextContinuationToken", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// RemoveBackup is part of the backupstorage.BackupStorage interface.
[ "RemoveBackup", "is", "part", "of", "the", "backupstorage", ".", "BackupStorage", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/s3backupstorage/s3.go#L256-L307
train
vitessio/vitess
go/vt/mysqlctl/s3backupstorage/s3.go
getLogLevel
func getLogLevel() *aws.LogLevelType { l := new(aws.LogLevelType) *l = aws.LogOff // default setting if level, found := logNameMap[*requiredLogLevel]; found { *l = level // adjust as required } return l }
go
func getLogLevel() *aws.LogLevelType { l := new(aws.LogLevelType) *l = aws.LogOff // default setting if level, found := logNameMap[*requiredLogLevel]; found { *l = level // adjust as required } return l }
[ "func", "getLogLevel", "(", ")", "*", "aws", ".", "LogLevelType", "{", "l", ":=", "new", "(", "aws", ".", "LogLevelType", ")", "\n", "*", "l", "=", "aws", ".", "LogOff", "// default setting", "\n", "if", "level", ",", "found", ":=", "logNameMap", "[", "*", "requiredLogLevel", "]", ";", "found", "{", "*", "l", "=", "level", "// adjust as required", "\n", "}", "\n", "return", "l", "\n", "}" ]
// getLogLevel converts the string loglevel to an aws.LogLevelType
[ "getLogLevel", "converts", "the", "string", "loglevel", "to", "an", "aws", ".", "LogLevelType" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/s3backupstorage/s3.go#L320-L327
train
vitessio/vitess
go/vt/worker/executor.go
fetchLoop
func (e *executor) fetchLoop(ctx context.Context, insertChannel chan string) error { for { select { case cmd, ok := <-insertChannel: if !ok { // no more to read, we're done return nil } if err := e.fetchWithRetries(ctx, func(ctx context.Context, tablet *topodatapb.Tablet) error { _, err := e.wr.TabletManagerClient().ExecuteFetchAsApp(ctx, tablet, true, []byte(cmd), 0) return err }); err != nil { return vterrors.Wrap(err, "ExecuteFetch failed") } case <-ctx.Done(): // Doesn't really matter if this select gets starved, because the other case // will also return an error due to executeFetch's context being closed. This case // does prevent us from blocking indefinitely on insertChannel when the worker is canceled. return nil } } }
go
func (e *executor) fetchLoop(ctx context.Context, insertChannel chan string) error { for { select { case cmd, ok := <-insertChannel: if !ok { // no more to read, we're done return nil } if err := e.fetchWithRetries(ctx, func(ctx context.Context, tablet *topodatapb.Tablet) error { _, err := e.wr.TabletManagerClient().ExecuteFetchAsApp(ctx, tablet, true, []byte(cmd), 0) return err }); err != nil { return vterrors.Wrap(err, "ExecuteFetch failed") } case <-ctx.Done(): // Doesn't really matter if this select gets starved, because the other case // will also return an error due to executeFetch's context being closed. This case // does prevent us from blocking indefinitely on insertChannel when the worker is canceled. return nil } } }
[ "func", "(", "e", "*", "executor", ")", "fetchLoop", "(", "ctx", "context", ".", "Context", ",", "insertChannel", "chan", "string", ")", "error", "{", "for", "{", "select", "{", "case", "cmd", ",", "ok", ":=", "<-", "insertChannel", ":", "if", "!", "ok", "{", "// no more to read, we're done", "return", "nil", "\n", "}", "\n", "if", "err", ":=", "e", ".", "fetchWithRetries", "(", "ctx", ",", "func", "(", "ctx", "context", ".", "Context", ",", "tablet", "*", "topodatapb", ".", "Tablet", ")", "error", "{", "_", ",", "err", ":=", "e", ".", "wr", ".", "TabletManagerClient", "(", ")", ".", "ExecuteFetchAsApp", "(", "ctx", ",", "tablet", ",", "true", ",", "[", "]", "byte", "(", "cmd", ")", ",", "0", ")", "\n", "return", "err", "\n", "}", ")", ";", "err", "!=", "nil", "{", "return", "vterrors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "// Doesn't really matter if this select gets starved, because the other case", "// will also return an error due to executeFetch's context being closed. This case", "// does prevent us from blocking indefinitely on insertChannel when the worker is canceled.", "return", "nil", "\n", "}", "\n", "}", "\n", "}" ]
// fetchLoop loops over the provided insertChannel and sends the commands to the // current master.
[ "fetchLoop", "loops", "over", "the", "provided", "insertChannel", "and", "sends", "the", "commands", "to", "the", "current", "master", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/executor.go#L68-L89
train
vitessio/vitess
go/vt/worker/executor.go
checkError
func (e *executor) checkError(ctx context.Context, err error, isRetry bool, master *discovery.TabletStats) (bool, error) { tabletString := fmt.Sprintf("%v (%v/%v)", topoproto.TabletAliasString(master.Tablet.Alias), e.keyspace, e.shard) // first see if it was a context timeout. select { case <-ctx.Done(): if ctx.Err() == context.DeadlineExceeded { e.wr.Logger().Warningf("ExecuteFetch failed on %v; will retry because it was a timeout error on the context", tabletString) statsRetryCount.Add(1) statsRetryCounters.Add(retryCategoryTimeoutError, 1) return false, nil } default: } // If the ExecuteFetch call failed because of an application error, we will try to figure out why. // We need to extract the MySQL error number, and will attempt to retry if we think the error is recoverable. match := errExtract.FindStringSubmatch(err.Error()) var errNo string if len(match) == 2 { errNo = match[1] } switch { case errNo == "1290": e.wr.Logger().Warningf("ExecuteFetch failed on %v; will reresolve and retry because it's due to a MySQL read-only error: %v", tabletString, err) statsRetryCount.Add(1) statsRetryCounters.Add(retryCategoryReadOnly, 1) case errNo == "2002" || errNo == "2006" || errNo == "2013" || errNo == "1053": // Note: // "2006" happens if the connection is already dead. Retrying a query in // this case is safe. // "2013" happens if the connection dies in the middle of a query. This is // also safe to retry because either the query went through on the server or // it was aborted. If we retry the query and get a duplicate entry error, we // assume that the previous execution was successful and ignore the error. // See below for the handling of duplicate entry error "1062". // "1053" is mysql shutting down e.wr.Logger().Warningf("ExecuteFetch failed on %v; will reresolve and retry because it's due to a MySQL connection error: %v", tabletString, err) statsRetryCount.Add(1) statsRetryCounters.Add(retryCategoryConnectionError, 1) case errNo == "1062": if !isRetry { return false, vterrors.Wrapf(err, "ExecuteFetch failed on %v on the first attempt; not retrying as this is not a recoverable error", tabletString) } e.wr.Logger().Infof("ExecuteFetch failed on %v with a duplicate entry error; marking this as a success, because of the likelihood that this query has already succeeded before being retried: %v", tabletString, err) return true, nil default: // Unknown error. return false, err } return false, nil }
go
func (e *executor) checkError(ctx context.Context, err error, isRetry bool, master *discovery.TabletStats) (bool, error) { tabletString := fmt.Sprintf("%v (%v/%v)", topoproto.TabletAliasString(master.Tablet.Alias), e.keyspace, e.shard) // first see if it was a context timeout. select { case <-ctx.Done(): if ctx.Err() == context.DeadlineExceeded { e.wr.Logger().Warningf("ExecuteFetch failed on %v; will retry because it was a timeout error on the context", tabletString) statsRetryCount.Add(1) statsRetryCounters.Add(retryCategoryTimeoutError, 1) return false, nil } default: } // If the ExecuteFetch call failed because of an application error, we will try to figure out why. // We need to extract the MySQL error number, and will attempt to retry if we think the error is recoverable. match := errExtract.FindStringSubmatch(err.Error()) var errNo string if len(match) == 2 { errNo = match[1] } switch { case errNo == "1290": e.wr.Logger().Warningf("ExecuteFetch failed on %v; will reresolve and retry because it's due to a MySQL read-only error: %v", tabletString, err) statsRetryCount.Add(1) statsRetryCounters.Add(retryCategoryReadOnly, 1) case errNo == "2002" || errNo == "2006" || errNo == "2013" || errNo == "1053": // Note: // "2006" happens if the connection is already dead. Retrying a query in // this case is safe. // "2013" happens if the connection dies in the middle of a query. This is // also safe to retry because either the query went through on the server or // it was aborted. If we retry the query and get a duplicate entry error, we // assume that the previous execution was successful and ignore the error. // See below for the handling of duplicate entry error "1062". // "1053" is mysql shutting down e.wr.Logger().Warningf("ExecuteFetch failed on %v; will reresolve and retry because it's due to a MySQL connection error: %v", tabletString, err) statsRetryCount.Add(1) statsRetryCounters.Add(retryCategoryConnectionError, 1) case errNo == "1062": if !isRetry { return false, vterrors.Wrapf(err, "ExecuteFetch failed on %v on the first attempt; not retrying as this is not a recoverable error", tabletString) } e.wr.Logger().Infof("ExecuteFetch failed on %v with a duplicate entry error; marking this as a success, because of the likelihood that this query has already succeeded before being retried: %v", tabletString, err) return true, nil default: // Unknown error. return false, err } return false, nil }
[ "func", "(", "e", "*", "executor", ")", "checkError", "(", "ctx", "context", ".", "Context", ",", "err", "error", ",", "isRetry", "bool", ",", "master", "*", "discovery", ".", "TabletStats", ")", "(", "bool", ",", "error", ")", "{", "tabletString", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "topoproto", ".", "TabletAliasString", "(", "master", ".", "Tablet", ".", "Alias", ")", ",", "e", ".", "keyspace", ",", "e", ".", "shard", ")", "\n\n", "// first see if it was a context timeout.", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "if", "ctx", ".", "Err", "(", ")", "==", "context", ".", "DeadlineExceeded", "{", "e", ".", "wr", ".", "Logger", "(", ")", ".", "Warningf", "(", "\"", "\"", ",", "tabletString", ")", "\n", "statsRetryCount", ".", "Add", "(", "1", ")", "\n", "statsRetryCounters", ".", "Add", "(", "retryCategoryTimeoutError", ",", "1", ")", "\n", "return", "false", ",", "nil", "\n", "}", "\n", "default", ":", "}", "\n\n", "// If the ExecuteFetch call failed because of an application error, we will try to figure out why.", "// We need to extract the MySQL error number, and will attempt to retry if we think the error is recoverable.", "match", ":=", "errExtract", ".", "FindStringSubmatch", "(", "err", ".", "Error", "(", ")", ")", "\n", "var", "errNo", "string", "\n", "if", "len", "(", "match", ")", "==", "2", "{", "errNo", "=", "match", "[", "1", "]", "\n", "}", "\n", "switch", "{", "case", "errNo", "==", "\"", "\"", ":", "e", ".", "wr", ".", "Logger", "(", ")", ".", "Warningf", "(", "\"", "\"", ",", "tabletString", ",", "err", ")", "\n", "statsRetryCount", ".", "Add", "(", "1", ")", "\n", "statsRetryCounters", ".", "Add", "(", "retryCategoryReadOnly", ",", "1", ")", "\n", "case", "errNo", "==", "\"", "\"", "||", "errNo", "==", "\"", "\"", "||", "errNo", "==", "\"", "\"", "||", "errNo", "==", "\"", "\"", ":", "// Note:", "// \"2006\" happens if the connection is already dead. Retrying a query in", "// this case is safe.", "// \"2013\" happens if the connection dies in the middle of a query. This is", "// also safe to retry because either the query went through on the server or", "// it was aborted. If we retry the query and get a duplicate entry error, we", "// assume that the previous execution was successful and ignore the error.", "// See below for the handling of duplicate entry error \"1062\".", "// \"1053\" is mysql shutting down", "e", ".", "wr", ".", "Logger", "(", ")", ".", "Warningf", "(", "\"", "\"", ",", "tabletString", ",", "err", ")", "\n", "statsRetryCount", ".", "Add", "(", "1", ")", "\n", "statsRetryCounters", ".", "Add", "(", "retryCategoryConnectionError", ",", "1", ")", "\n", "case", "errNo", "==", "\"", "\"", ":", "if", "!", "isRetry", "{", "return", "false", ",", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "tabletString", ")", "\n", "}", "\n", "e", ".", "wr", ".", "Logger", "(", ")", ".", "Infof", "(", "\"", "\"", ",", "tabletString", ",", "err", ")", "\n", "return", "true", ",", "nil", "\n", "default", ":", "// Unknown error.", "return", "false", ",", "err", "\n", "}", "\n", "return", "false", ",", "nil", "\n", "}" ]
// checkError returns true if the error can be ignored and the command // succeeded, false if the error is retryable and a non-nil error if the // command must not be retried.
[ "checkError", "returns", "true", "if", "the", "error", "can", "be", "ignored", "and", "the", "command", "succeeded", "false", "if", "the", "error", "is", "retryable", "and", "a", "non", "-", "nil", "error", "if", "the", "command", "must", "not", "be", "retried", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/executor.go#L197-L248
train
vitessio/vitess
go/vt/status/status.go
MakeVtctldRedirect
func MakeVtctldRedirect(text string, q map[string]string) template.HTML { query := url.Values{} for k, v := range q { query.Set(k, v) } url := "explorers/redirect" + "?" + query.Encode() return VtctldLink(text, url) }
go
func MakeVtctldRedirect(text string, q map[string]string) template.HTML { query := url.Values{} for k, v := range q { query.Set(k, v) } url := "explorers/redirect" + "?" + query.Encode() return VtctldLink(text, url) }
[ "func", "MakeVtctldRedirect", "(", "text", "string", ",", "q", "map", "[", "string", "]", "string", ")", "template", ".", "HTML", "{", "query", ":=", "url", ".", "Values", "{", "}", "\n", "for", "k", ",", "v", ":=", "range", "q", "{", "query", ".", "Set", "(", "k", ",", "v", ")", "\n", "}", "\n", "url", ":=", "\"", "\"", "+", "\"", "\"", "+", "query", ".", "Encode", "(", ")", "\n", "return", "VtctldLink", "(", "text", ",", "url", ")", "\n", "}" ]
// MakeVtctldRedirect returns an absolute vtctld url that will // redirect to the page for the topology object specified in q.
[ "MakeVtctldRedirect", "returns", "an", "absolute", "vtctld", "url", "that", "will", "redirect", "to", "the", "page", "for", "the", "topology", "object", "specified", "in", "q", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/status/status.go#L37-L44
train
vitessio/vitess
go/vt/status/status.go
VtctldLink
func VtctldLink(text, urlPath string) template.HTML { if *vtctldAddr == "" { return template.HTML(text) } var fullURL string if strings.HasSuffix(*vtctldAddr, "/") { fullURL = *vtctldAddr + urlPath } else { fullURL = *vtctldAddr + "/" + urlPath } return template.HTML(fmt.Sprintf(`<a href="%v">%v</a>`, fullURL, text)) }
go
func VtctldLink(text, urlPath string) template.HTML { if *vtctldAddr == "" { return template.HTML(text) } var fullURL string if strings.HasSuffix(*vtctldAddr, "/") { fullURL = *vtctldAddr + urlPath } else { fullURL = *vtctldAddr + "/" + urlPath } return template.HTML(fmt.Sprintf(`<a href="%v">%v</a>`, fullURL, text)) }
[ "func", "VtctldLink", "(", "text", ",", "urlPath", "string", ")", "template", ".", "HTML", "{", "if", "*", "vtctldAddr", "==", "\"", "\"", "{", "return", "template", ".", "HTML", "(", "text", ")", "\n", "}", "\n", "var", "fullURL", "string", "\n", "if", "strings", ".", "HasSuffix", "(", "*", "vtctldAddr", ",", "\"", "\"", ")", "{", "fullURL", "=", "*", "vtctldAddr", "+", "urlPath", "\n", "}", "else", "{", "fullURL", "=", "*", "vtctldAddr", "+", "\"", "\"", "+", "urlPath", "\n", "}", "\n\n", "return", "template", ".", "HTML", "(", "fmt", ".", "Sprintf", "(", "`<a href=\"%v\">%v</a>`", ",", "fullURL", ",", "text", ")", ")", "\n", "}" ]
// VtctldLink returns the HTML to display a link to the fully // qualified vtctld url whose path is given as parameter. // If no vtctld_addr flag was passed in, we just return the text with no link.
[ "VtctldLink", "returns", "the", "HTML", "to", "display", "a", "link", "to", "the", "fully", "qualified", "vtctld", "url", "whose", "path", "is", "given", "as", "parameter", ".", "If", "no", "vtctld_addr", "flag", "was", "passed", "in", "we", "just", "return", "the", "text", "with", "no", "link", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/status/status.go#L49-L61
train
vitessio/vitess
go/vt/status/status.go
VtctldKeyspace
func VtctldKeyspace(keyspace string) template.HTML { return MakeVtctldRedirect(keyspace, map[string]string{ "type": "keyspace", "keyspace": keyspace, }) }
go
func VtctldKeyspace(keyspace string) template.HTML { return MakeVtctldRedirect(keyspace, map[string]string{ "type": "keyspace", "keyspace": keyspace, }) }
[ "func", "VtctldKeyspace", "(", "keyspace", "string", ")", "template", ".", "HTML", "{", "return", "MakeVtctldRedirect", "(", "keyspace", ",", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "keyspace", ",", "}", ")", "\n", "}" ]
// VtctldKeyspace returns the keyspace name, possibly linked to the // keyspace page in vtctld.
[ "VtctldKeyspace", "returns", "the", "keyspace", "name", "possibly", "linked", "to", "the", "keyspace", "page", "in", "vtctld", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/status/status.go#L65-L71
train
vitessio/vitess
go/vt/status/status.go
VtctldShard
func VtctldShard(keyspace, shard string) template.HTML { return MakeVtctldRedirect(shard, map[string]string{ "type": "shard", "keyspace": keyspace, "shard": shard, }) }
go
func VtctldShard(keyspace, shard string) template.HTML { return MakeVtctldRedirect(shard, map[string]string{ "type": "shard", "keyspace": keyspace, "shard": shard, }) }
[ "func", "VtctldShard", "(", "keyspace", ",", "shard", "string", ")", "template", ".", "HTML", "{", "return", "MakeVtctldRedirect", "(", "shard", ",", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "keyspace", ",", "\"", "\"", ":", "shard", ",", "}", ")", "\n", "}" ]
// VtctldShard returns the shard name, possibly linked to the shard // page in vtctld.
[ "VtctldShard", "returns", "the", "shard", "name", "possibly", "linked", "to", "the", "shard", "page", "in", "vtctld", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/status/status.go#L75-L81
train
vitessio/vitess
go/vt/status/status.go
VtctldSrvKeyspace
func VtctldSrvKeyspace(cell, keyspace string) template.HTML { return MakeVtctldRedirect(keyspace, map[string]string{ "type": "srv_keyspace", "cell": cell, "keyspace": keyspace, }) }
go
func VtctldSrvKeyspace(cell, keyspace string) template.HTML { return MakeVtctldRedirect(keyspace, map[string]string{ "type": "srv_keyspace", "cell": cell, "keyspace": keyspace, }) }
[ "func", "VtctldSrvKeyspace", "(", "cell", ",", "keyspace", "string", ")", "template", ".", "HTML", "{", "return", "MakeVtctldRedirect", "(", "keyspace", ",", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "cell", ",", "\"", "\"", ":", "keyspace", ",", "}", ")", "\n", "}" ]
// VtctldSrvKeyspace returns the keyspace name, possibly linked to the // SrvKeyspace page in vtctld.
[ "VtctldSrvKeyspace", "returns", "the", "keyspace", "name", "possibly", "linked", "to", "the", "SrvKeyspace", "page", "in", "vtctld", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/status/status.go#L91-L97
train
vitessio/vitess
go/vt/status/status.go
VtctldTablet
func VtctldTablet(aliasName string) template.HTML { return MakeVtctldRedirect(aliasName, map[string]string{ "type": "tablet", "alias": aliasName, }) }
go
func VtctldTablet(aliasName string) template.HTML { return MakeVtctldRedirect(aliasName, map[string]string{ "type": "tablet", "alias": aliasName, }) }
[ "func", "VtctldTablet", "(", "aliasName", "string", ")", "template", ".", "HTML", "{", "return", "MakeVtctldRedirect", "(", "aliasName", ",", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "aliasName", ",", "}", ")", "\n", "}" ]
// VtctldTablet returns the tablet alias, possibly linked to the // Tablet page in vtctld.
[ "VtctldTablet", "returns", "the", "tablet", "alias", "possibly", "linked", "to", "the", "Tablet", "page", "in", "vtctld", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/status/status.go#L113-L118
train
vitessio/vitess
go/stats/opentsdb/opentsdb.go
sendDataPoints
func sendDataPoints(data []dataPoint) error { json, err := json.Marshal(data) if err != nil { return err } resp, err := http.Post(*openTsdbURI, "application/json", bytes.NewReader(json)) if err != nil { return err } resp.Body.Close() return nil }
go
func sendDataPoints(data []dataPoint) error { json, err := json.Marshal(data) if err != nil { return err } resp, err := http.Post(*openTsdbURI, "application/json", bytes.NewReader(json)) if err != nil { return err } resp.Body.Close() return nil }
[ "func", "sendDataPoints", "(", "data", "[", "]", "dataPoint", ")", "error", "{", "json", ",", "err", ":=", "json", ".", "Marshal", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "resp", ",", "err", ":=", "http", ".", "Post", "(", "*", "openTsdbURI", ",", "\"", "\"", ",", "bytes", ".", "NewReader", "(", "json", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "return", "nil", "\n", "}" ]
// sendDataPoints pushes a list of data points to openTSDB. // All other code in this file is just to support getting this function called // with all stats represented as data points.
[ "sendDataPoints", "pushes", "a", "list", "of", "data", "points", "to", "openTSDB", ".", "All", "other", "code", "in", "this", "file", "is", "just", "to", "support", "getting", "this", "function", "called", "with", "all", "stats", "represented", "as", "data", "points", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/stats/opentsdb/opentsdb.go#L36-L48
train
vitessio/vitess
go/stats/opentsdb/opentsdb.go
Init
func Init(prefix string) { // Needs to happen in servenv.OnRun() instead of init because it requires flag parsing and logging servenv.OnRun(func() { if *openTsdbURI == "" { return } backend := &openTSDBBackend{ prefix: prefix, // If you want to global service values like host, service name, git revision, etc, // this is the place to do it. commonTags: map[string]string{}, } stats.RegisterPushBackend("opentsdb", backend) http.HandleFunc("/debug/opentsdb", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json; charset=utf-8") dataPoints := (*backend).getDataPoints() sort.Sort(byMetric(dataPoints)) if b, err := json.MarshalIndent(dataPoints, "", " "); err != nil { w.Write([]byte(err.Error())) } else { w.Write(b) } }) }) }
go
func Init(prefix string) { // Needs to happen in servenv.OnRun() instead of init because it requires flag parsing and logging servenv.OnRun(func() { if *openTsdbURI == "" { return } backend := &openTSDBBackend{ prefix: prefix, // If you want to global service values like host, service name, git revision, etc, // this is the place to do it. commonTags: map[string]string{}, } stats.RegisterPushBackend("opentsdb", backend) http.HandleFunc("/debug/opentsdb", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json; charset=utf-8") dataPoints := (*backend).getDataPoints() sort.Sort(byMetric(dataPoints)) if b, err := json.MarshalIndent(dataPoints, "", " "); err != nil { w.Write([]byte(err.Error())) } else { w.Write(b) } }) }) }
[ "func", "Init", "(", "prefix", "string", ")", "{", "// Needs to happen in servenv.OnRun() instead of init because it requires flag parsing and logging", "servenv", ".", "OnRun", "(", "func", "(", ")", "{", "if", "*", "openTsdbURI", "==", "\"", "\"", "{", "return", "\n", "}", "\n\n", "backend", ":=", "&", "openTSDBBackend", "{", "prefix", ":", "prefix", ",", "// If you want to global service values like host, service name, git revision, etc,", "// this is the place to do it.", "commonTags", ":", "map", "[", "string", "]", "string", "{", "}", ",", "}", "\n\n", "stats", ".", "RegisterPushBackend", "(", "\"", "\"", ",", "backend", ")", "\n\n", "http", ".", "HandleFunc", "(", "\"", "\"", ",", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "dataPoints", ":=", "(", "*", "backend", ")", ".", "getDataPoints", "(", ")", "\n", "sort", ".", "Sort", "(", "byMetric", "(", "dataPoints", ")", ")", "\n\n", "if", "b", ",", "err", ":=", "json", ".", "MarshalIndent", "(", "dataPoints", ",", "\"", "\"", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "w", ".", "Write", "(", "[", "]", "byte", "(", "err", ".", "Error", "(", ")", ")", ")", "\n", "}", "else", "{", "w", ".", "Write", "(", "b", ")", "\n", "}", "\n", "}", ")", "\n", "}", ")", "\n", "}" ]
// Init attempts to create a singleton openTSDBBackend and register it as a PushBackend. // If it fails to create one, this is a noop. The prefix argument is an optional string // to prepend to the name of every data point reported.
[ "Init", "attempts", "to", "create", "a", "singleton", "openTSDBBackend", "and", "register", "it", "as", "a", "PushBackend", ".", "If", "it", "fails", "to", "create", "one", "this", "is", "a", "noop", ".", "The", "prefix", "argument", "is", "an", "optional", "string", "to", "prepend", "to", "the", "name", "of", "every", "data", "point", "reported", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/stats/opentsdb/opentsdb.go#L71-L99
train
vitessio/vitess
go/stats/opentsdb/opentsdb.go
makeLabel
func makeLabel(labelName string, labelVal string) map[string]string { return map[string]string{labelName: labelVal} }
go
func makeLabel(labelName string, labelVal string) map[string]string { return map[string]string{labelName: labelVal} }
[ "func", "makeLabel", "(", "labelName", "string", ",", "labelVal", "string", ")", "map", "[", "string", "]", "string", "{", "return", "map", "[", "string", "]", "string", "{", "labelName", ":", "labelVal", "}", "\n", "}" ]
// makeLabel builds a tag list with a single label + value.
[ "makeLabel", "builds", "a", "tag", "list", "with", "a", "single", "label", "+", "value", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/stats/opentsdb/opentsdb.go#L242-L244
train
vitessio/vitess
go/stats/opentsdb/opentsdb.go
addUnrecognizedExpvars
func (dc *dataCollector) addUnrecognizedExpvars(prefix string, obj map[string]interface{}) { for k, v := range obj { prefix := combineMetricName(prefix, k) switch v := v.(type) { case map[string]interface{}: dc.addUnrecognizedExpvars(prefix, v) case float64: dc.addFloat(prefix, v, nil) } } }
go
func (dc *dataCollector) addUnrecognizedExpvars(prefix string, obj map[string]interface{}) { for k, v := range obj { prefix := combineMetricName(prefix, k) switch v := v.(type) { case map[string]interface{}: dc.addUnrecognizedExpvars(prefix, v) case float64: dc.addFloat(prefix, v, nil) } } }
[ "func", "(", "dc", "*", "dataCollector", ")", "addUnrecognizedExpvars", "(", "prefix", "string", ",", "obj", "map", "[", "string", "]", "interface", "{", "}", ")", "{", "for", "k", ",", "v", ":=", "range", "obj", "{", "prefix", ":=", "combineMetricName", "(", "prefix", ",", "k", ")", "\n", "switch", "v", ":=", "v", ".", "(", "type", ")", "{", "case", "map", "[", "string", "]", "interface", "{", "}", ":", "dc", ".", "addUnrecognizedExpvars", "(", "prefix", ",", "v", ")", "\n", "case", "float64", ":", "dc", ".", "addFloat", "(", "prefix", ",", "v", ",", "nil", ")", "\n", "}", "\n", "}", "\n", "}" ]
// addUnrecognizedExpvars recurses into a json object to pull out float64 variables to report.
[ "addUnrecognizedExpvars", "recurses", "into", "a", "json", "object", "to", "pull", "out", "float64", "variables", "to", "report", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/stats/opentsdb/opentsdb.go#L258-L268
train
vitessio/vitess
go/stats/opentsdb/opentsdb.go
addTimings
func (dc *dataCollector) addTimings(labels []string, timings *stats.Timings, prefix string) { histograms := timings.Histograms() for labelValsCombined, histogram := range histograms { // If you prefer millisecond timings over nanoseconds you can pass 1000000 here instead of 1. dc.addHistogram(histogram, 1, prefix, makeLabels(labels, labelValsCombined)) } }
go
func (dc *dataCollector) addTimings(labels []string, timings *stats.Timings, prefix string) { histograms := timings.Histograms() for labelValsCombined, histogram := range histograms { // If you prefer millisecond timings over nanoseconds you can pass 1000000 here instead of 1. dc.addHistogram(histogram, 1, prefix, makeLabels(labels, labelValsCombined)) } }
[ "func", "(", "dc", "*", "dataCollector", ")", "addTimings", "(", "labels", "[", "]", "string", ",", "timings", "*", "stats", ".", "Timings", ",", "prefix", "string", ")", "{", "histograms", ":=", "timings", ".", "Histograms", "(", ")", "\n", "for", "labelValsCombined", ",", "histogram", ":=", "range", "histograms", "{", "// If you prefer millisecond timings over nanoseconds you can pass 1000000 here instead of 1.", "dc", ".", "addHistogram", "(", "histogram", ",", "1", ",", "prefix", ",", "makeLabels", "(", "labels", ",", "labelValsCombined", ")", ")", "\n", "}", "\n", "}" ]
// addTimings converts a vitess Timings stat to something opentsdb can deal with.
[ "addTimings", "converts", "a", "vitess", "Timings", "stat", "to", "something", "opentsdb", "can", "deal", "with", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/stats/opentsdb/opentsdb.go#L271-L277
train