repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
vitessio/vitess
go/vt/vtgate/grpcvtgateservice/server.go
MessageAck
func (vtg *VTGate) MessageAck(ctx context.Context, request *vtgatepb.MessageAckRequest) (response *querypb.MessageAckResponse, err error) { defer vtg.server.HandlePanic(&err) ctx = withCallerIDContext(ctx, request.CallerId) count, vtgErr := vtg.server.MessageAck(ctx, request.Keyspace, request.Name, request.Ids) if vtgErr != nil { return nil, vterrors.ToGRPC(vtgErr) } return &querypb.MessageAckResponse{ Result: &querypb.QueryResult{ RowsAffected: uint64(count), }, }, nil }
go
func (vtg *VTGate) MessageAck(ctx context.Context, request *vtgatepb.MessageAckRequest) (response *querypb.MessageAckResponse, err error) { defer vtg.server.HandlePanic(&err) ctx = withCallerIDContext(ctx, request.CallerId) count, vtgErr := vtg.server.MessageAck(ctx, request.Keyspace, request.Name, request.Ids) if vtgErr != nil { return nil, vterrors.ToGRPC(vtgErr) } return &querypb.MessageAckResponse{ Result: &querypb.QueryResult{ RowsAffected: uint64(count), }, }, nil }
[ "func", "(", "vtg", "*", "VTGate", ")", "MessageAck", "(", "ctx", "context", ".", "Context", ",", "request", "*", "vtgatepb", ".", "MessageAckRequest", ")", "(", "response", "*", "querypb", ".", "MessageAckResponse", ",", "err", "error", ")", "{", "defer", "vtg", ".", "server", ".", "HandlePanic", "(", "&", "err", ")", "\n", "ctx", "=", "withCallerIDContext", "(", "ctx", ",", "request", ".", "CallerId", ")", "\n", "count", ",", "vtgErr", ":=", "vtg", ".", "server", ".", "MessageAck", "(", "ctx", ",", "request", ".", "Keyspace", ",", "request", ".", "Name", ",", "request", ".", "Ids", ")", "\n", "if", "vtgErr", "!=", "nil", "{", "return", "nil", ",", "vterrors", ".", "ToGRPC", "(", "vtgErr", ")", "\n", "}", "\n", "return", "&", "querypb", ".", "MessageAckResponse", "{", "Result", ":", "&", "querypb", ".", "QueryResult", "{", "RowsAffected", ":", "uint64", "(", "count", ")", ",", "}", ",", "}", ",", "nil", "\n", "}" ]
// MessageAck is the RPC version of vtgateservice.VTGateService method
[ "MessageAck", "is", "the", "RPC", "version", "of", "vtgateservice", ".", "VTGateService", "method" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/grpcvtgateservice/server.go#L424-L436
train
vitessio/vitess
go/vt/vtgate/grpcvtgateservice/server.go
SplitQuery
func (vtg *VTGate) SplitQuery(ctx context.Context, request *vtgatepb.SplitQueryRequest) (response *vtgatepb.SplitQueryResponse, err error) { defer vtg.server.HandlePanic(&err) ctx = withCallerIDContext(ctx, request.CallerId) splits, vtgErr := vtg.server.SplitQuery( ctx, request.Keyspace, request.Query.Sql, request.Query.BindVariables, request.SplitColumn, request.SplitCount, request.NumRowsPerQueryPart, request.Algorithm) if vtgErr != nil { return nil, vterrors.ToGRPC(vtgErr) } return &vtgatepb.SplitQueryResponse{ Splits: splits, }, nil }
go
func (vtg *VTGate) SplitQuery(ctx context.Context, request *vtgatepb.SplitQueryRequest) (response *vtgatepb.SplitQueryResponse, err error) { defer vtg.server.HandlePanic(&err) ctx = withCallerIDContext(ctx, request.CallerId) splits, vtgErr := vtg.server.SplitQuery( ctx, request.Keyspace, request.Query.Sql, request.Query.BindVariables, request.SplitColumn, request.SplitCount, request.NumRowsPerQueryPart, request.Algorithm) if vtgErr != nil { return nil, vterrors.ToGRPC(vtgErr) } return &vtgatepb.SplitQueryResponse{ Splits: splits, }, nil }
[ "func", "(", "vtg", "*", "VTGate", ")", "SplitQuery", "(", "ctx", "context", ".", "Context", ",", "request", "*", "vtgatepb", ".", "SplitQueryRequest", ")", "(", "response", "*", "vtgatepb", ".", "SplitQueryResponse", ",", "err", "error", ")", "{", "defer", "vtg", ".", "server", ".", "HandlePanic", "(", "&", "err", ")", "\n", "ctx", "=", "withCallerIDContext", "(", "ctx", ",", "request", ".", "CallerId", ")", "\n", "splits", ",", "vtgErr", ":=", "vtg", ".", "server", ".", "SplitQuery", "(", "ctx", ",", "request", ".", "Keyspace", ",", "request", ".", "Query", ".", "Sql", ",", "request", ".", "Query", ".", "BindVariables", ",", "request", ".", "SplitColumn", ",", "request", ".", "SplitCount", ",", "request", ".", "NumRowsPerQueryPart", ",", "request", ".", "Algorithm", ")", "\n", "if", "vtgErr", "!=", "nil", "{", "return", "nil", ",", "vterrors", ".", "ToGRPC", "(", "vtgErr", ")", "\n", "}", "\n", "return", "&", "vtgatepb", ".", "SplitQueryResponse", "{", "Splits", ":", "splits", ",", "}", ",", "nil", "\n", "}" ]
// SplitQuery is the RPC version of vtgateservice.VTGateService method
[ "SplitQuery", "is", "the", "RPC", "version", "of", "vtgateservice", ".", "VTGateService", "method" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/grpcvtgateservice/server.go#L455-L474
train
vitessio/vitess
go/vt/vtgate/grpcvtgateservice/server.go
GetSrvKeyspace
func (vtg *VTGate) GetSrvKeyspace(ctx context.Context, request *vtgatepb.GetSrvKeyspaceRequest) (response *vtgatepb.GetSrvKeyspaceResponse, err error) { defer vtg.server.HandlePanic(&err) sk, vtgErr := vtg.server.GetSrvKeyspace(ctx, request.Keyspace) if vtgErr != nil { return nil, vterrors.ToGRPC(vtgErr) } return &vtgatepb.GetSrvKeyspaceResponse{ SrvKeyspace: sk, }, nil }
go
func (vtg *VTGate) GetSrvKeyspace(ctx context.Context, request *vtgatepb.GetSrvKeyspaceRequest) (response *vtgatepb.GetSrvKeyspaceResponse, err error) { defer vtg.server.HandlePanic(&err) sk, vtgErr := vtg.server.GetSrvKeyspace(ctx, request.Keyspace) if vtgErr != nil { return nil, vterrors.ToGRPC(vtgErr) } return &vtgatepb.GetSrvKeyspaceResponse{ SrvKeyspace: sk, }, nil }
[ "func", "(", "vtg", "*", "VTGate", ")", "GetSrvKeyspace", "(", "ctx", "context", ".", "Context", ",", "request", "*", "vtgatepb", ".", "GetSrvKeyspaceRequest", ")", "(", "response", "*", "vtgatepb", ".", "GetSrvKeyspaceResponse", ",", "err", "error", ")", "{", "defer", "vtg", ".", "server", ".", "HandlePanic", "(", "&", "err", ")", "\n", "sk", ",", "vtgErr", ":=", "vtg", ".", "server", ".", "GetSrvKeyspace", "(", "ctx", ",", "request", ".", "Keyspace", ")", "\n", "if", "vtgErr", "!=", "nil", "{", "return", "nil", ",", "vterrors", ".", "ToGRPC", "(", "vtgErr", ")", "\n", "}", "\n", "return", "&", "vtgatepb", ".", "GetSrvKeyspaceResponse", "{", "SrvKeyspace", ":", "sk", ",", "}", ",", "nil", "\n", "}" ]
// GetSrvKeyspace is the RPC version of vtgateservice.VTGateService method
[ "GetSrvKeyspace", "is", "the", "RPC", "version", "of", "vtgateservice", ".", "VTGateService", "method" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/grpcvtgateservice/server.go#L477-L486
train
vitessio/vitess
go/vt/vtgate/grpcvtgateservice/server.go
UpdateStream
func (vtg *VTGate) UpdateStream(request *vtgatepb.UpdateStreamRequest, stream vtgateservicepb.Vitess_UpdateStreamServer) (err error) { defer vtg.server.HandlePanic(&err) ctx := withCallerIDContext(stream.Context(), request.CallerId) vtgErr := vtg.server.UpdateStream(ctx, request.Keyspace, request.Shard, request.KeyRange, request.TabletType, request.Timestamp, request.Event, func(event *querypb.StreamEvent, resumeTimestamp int64) error { // Send is not safe to call concurrently, but vtgate // guarantees that it's not. return stream.Send(&vtgatepb.UpdateStreamResponse{ Event: event, ResumeTimestamp: resumeTimestamp, }) }) return vterrors.ToGRPC(vtgErr) }
go
func (vtg *VTGate) UpdateStream(request *vtgatepb.UpdateStreamRequest, stream vtgateservicepb.Vitess_UpdateStreamServer) (err error) { defer vtg.server.HandlePanic(&err) ctx := withCallerIDContext(stream.Context(), request.CallerId) vtgErr := vtg.server.UpdateStream(ctx, request.Keyspace, request.Shard, request.KeyRange, request.TabletType, request.Timestamp, request.Event, func(event *querypb.StreamEvent, resumeTimestamp int64) error { // Send is not safe to call concurrently, but vtgate // guarantees that it's not. return stream.Send(&vtgatepb.UpdateStreamResponse{ Event: event, ResumeTimestamp: resumeTimestamp, }) }) return vterrors.ToGRPC(vtgErr) }
[ "func", "(", "vtg", "*", "VTGate", ")", "UpdateStream", "(", "request", "*", "vtgatepb", ".", "UpdateStreamRequest", ",", "stream", "vtgateservicepb", ".", "Vitess_UpdateStreamServer", ")", "(", "err", "error", ")", "{", "defer", "vtg", ".", "server", ".", "HandlePanic", "(", "&", "err", ")", "\n", "ctx", ":=", "withCallerIDContext", "(", "stream", ".", "Context", "(", ")", ",", "request", ".", "CallerId", ")", "\n", "vtgErr", ":=", "vtg", ".", "server", ".", "UpdateStream", "(", "ctx", ",", "request", ".", "Keyspace", ",", "request", ".", "Shard", ",", "request", ".", "KeyRange", ",", "request", ".", "TabletType", ",", "request", ".", "Timestamp", ",", "request", ".", "Event", ",", "func", "(", "event", "*", "querypb", ".", "StreamEvent", ",", "resumeTimestamp", "int64", ")", "error", "{", "// Send is not safe to call concurrently, but vtgate", "// guarantees that it's not.", "return", "stream", ".", "Send", "(", "&", "vtgatepb", ".", "UpdateStreamResponse", "{", "Event", ":", "event", ",", "ResumeTimestamp", ":", "resumeTimestamp", ",", "}", ")", "\n", "}", ")", "\n", "return", "vterrors", ".", "ToGRPC", "(", "vtgErr", ")", "\n", "}" ]
// UpdateStream is the RPC version of vtgateservice.VTGateService method
[ "UpdateStream", "is", "the", "RPC", "version", "of", "vtgateservice", ".", "VTGateService", "method" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/grpcvtgateservice/server.go#L489-L508
train
vitessio/vitess
go/vt/dbconnpool/connection.go
ExecuteFetch
func (dbc *DBConnection) ExecuteFetch(query string, maxrows int, wantfields bool) (*sqltypes.Result, error) { defer dbc.mysqlStats.Record("Exec", time.Now()) mqr, err := dbc.Conn.ExecuteFetch(query, maxrows, wantfields) if err != nil { dbc.handleError(err) return nil, err } return mqr, nil }
go
func (dbc *DBConnection) ExecuteFetch(query string, maxrows int, wantfields bool) (*sqltypes.Result, error) { defer dbc.mysqlStats.Record("Exec", time.Now()) mqr, err := dbc.Conn.ExecuteFetch(query, maxrows, wantfields) if err != nil { dbc.handleError(err) return nil, err } return mqr, nil }
[ "func", "(", "dbc", "*", "DBConnection", ")", "ExecuteFetch", "(", "query", "string", ",", "maxrows", "int", ",", "wantfields", "bool", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "defer", "dbc", ".", "mysqlStats", ".", "Record", "(", "\"", "\"", ",", "time", ".", "Now", "(", ")", ")", "\n", "mqr", ",", "err", ":=", "dbc", ".", "Conn", ".", "ExecuteFetch", "(", "query", ",", "maxrows", ",", "wantfields", ")", "\n", "if", "err", "!=", "nil", "{", "dbc", ".", "handleError", "(", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "return", "mqr", ",", "nil", "\n", "}" ]
// ExecuteFetch overwrites mysql.Conn.ExecuteFetch.
[ "ExecuteFetch", "overwrites", "mysql", ".", "Conn", ".", "ExecuteFetch", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/dbconnpool/connection.go#L46-L54
train
vitessio/vitess
go/vt/dbconnpool/connection.go
ExecuteStreamFetch
func (dbc *DBConnection) ExecuteStreamFetch(query string, callback func(*sqltypes.Result) error, streamBufferSize int) error { defer dbc.mysqlStats.Record("ExecStream", time.Now()) err := dbc.Conn.ExecuteStreamFetch(query) if err != nil { dbc.handleError(err) return err } defer dbc.CloseResult() // first call the callback with the fields flds, err := dbc.Fields() if err != nil { return err } err = callback(&sqltypes.Result{Fields: flds}) if err != nil { return fmt.Errorf("stream send error: %v", err) } // then get all the rows, sending them as we reach a decent packet size // start with a pre-allocated array of 256 rows capacity qr := &sqltypes.Result{Rows: make([][]sqltypes.Value, 0, 256)} byteCount := 0 for { row, err := dbc.FetchNext() if err != nil { dbc.handleError(err) return err } if row == nil { break } qr.Rows = append(qr.Rows, row) for _, s := range row { byteCount += s.Len() } if byteCount >= streamBufferSize { err = callback(qr) if err != nil { return err } // empty the rows so we start over, but we keep the // same capacity qr.Rows = qr.Rows[:0] byteCount = 0 } } if len(qr.Rows) > 0 { err = callback(qr) if err != nil { return err } } return nil }
go
func (dbc *DBConnection) ExecuteStreamFetch(query string, callback func(*sqltypes.Result) error, streamBufferSize int) error { defer dbc.mysqlStats.Record("ExecStream", time.Now()) err := dbc.Conn.ExecuteStreamFetch(query) if err != nil { dbc.handleError(err) return err } defer dbc.CloseResult() // first call the callback with the fields flds, err := dbc.Fields() if err != nil { return err } err = callback(&sqltypes.Result{Fields: flds}) if err != nil { return fmt.Errorf("stream send error: %v", err) } // then get all the rows, sending them as we reach a decent packet size // start with a pre-allocated array of 256 rows capacity qr := &sqltypes.Result{Rows: make([][]sqltypes.Value, 0, 256)} byteCount := 0 for { row, err := dbc.FetchNext() if err != nil { dbc.handleError(err) return err } if row == nil { break } qr.Rows = append(qr.Rows, row) for _, s := range row { byteCount += s.Len() } if byteCount >= streamBufferSize { err = callback(qr) if err != nil { return err } // empty the rows so we start over, but we keep the // same capacity qr.Rows = qr.Rows[:0] byteCount = 0 } } if len(qr.Rows) > 0 { err = callback(qr) if err != nil { return err } } return nil }
[ "func", "(", "dbc", "*", "DBConnection", ")", "ExecuteStreamFetch", "(", "query", "string", ",", "callback", "func", "(", "*", "sqltypes", ".", "Result", ")", "error", ",", "streamBufferSize", "int", ")", "error", "{", "defer", "dbc", ".", "mysqlStats", ".", "Record", "(", "\"", "\"", ",", "time", ".", "Now", "(", ")", ")", "\n\n", "err", ":=", "dbc", ".", "Conn", ".", "ExecuteStreamFetch", "(", "query", ")", "\n", "if", "err", "!=", "nil", "{", "dbc", ".", "handleError", "(", "err", ")", "\n", "return", "err", "\n", "}", "\n", "defer", "dbc", ".", "CloseResult", "(", ")", "\n\n", "// first call the callback with the fields", "flds", ",", "err", ":=", "dbc", ".", "Fields", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "callback", "(", "&", "sqltypes", ".", "Result", "{", "Fields", ":", "flds", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// then get all the rows, sending them as we reach a decent packet size", "// start with a pre-allocated array of 256 rows capacity", "qr", ":=", "&", "sqltypes", ".", "Result", "{", "Rows", ":", "make", "(", "[", "]", "[", "]", "sqltypes", ".", "Value", ",", "0", ",", "256", ")", "}", "\n", "byteCount", ":=", "0", "\n", "for", "{", "row", ",", "err", ":=", "dbc", ".", "FetchNext", "(", ")", "\n", "if", "err", "!=", "nil", "{", "dbc", ".", "handleError", "(", "err", ")", "\n", "return", "err", "\n", "}", "\n", "if", "row", "==", "nil", "{", "break", "\n", "}", "\n", "qr", ".", "Rows", "=", "append", "(", "qr", ".", "Rows", ",", "row", ")", "\n", "for", "_", ",", "s", ":=", "range", "row", "{", "byteCount", "+=", "s", ".", "Len", "(", ")", "\n", "}", "\n\n", "if", "byteCount", ">=", "streamBufferSize", "{", "err", "=", "callback", "(", "qr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// empty the rows so we start over, but we keep the", "// same capacity", "qr", ".", "Rows", "=", "qr", ".", "Rows", "[", ":", "0", "]", "\n", "byteCount", "=", "0", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "qr", ".", "Rows", ")", ">", "0", "{", "err", "=", "callback", "(", "qr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// ExecuteStreamFetch overwrites mysql.Conn.ExecuteStreamFetch.
[ "ExecuteStreamFetch", "overwrites", "mysql", ".", "Conn", ".", "ExecuteStreamFetch", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/dbconnpool/connection.go#L57-L115
train
vitessio/vitess
go/vt/dbconnpool/connection.go
NewDBConnection
func NewDBConnection(info *mysql.ConnParams, mysqlStats *stats.Timings) (*DBConnection, error) { start := time.Now() defer mysqlStats.Record("Connect", start) params, err := dbconfigs.WithCredentials(info) if err != nil { return nil, err } ctx := context.Background() c, err := mysql.Connect(ctx, params) if err != nil { mysqlStats.Record("ConnectError", start) } return &DBConnection{c, mysqlStats}, err }
go
func NewDBConnection(info *mysql.ConnParams, mysqlStats *stats.Timings) (*DBConnection, error) { start := time.Now() defer mysqlStats.Record("Connect", start) params, err := dbconfigs.WithCredentials(info) if err != nil { return nil, err } ctx := context.Background() c, err := mysql.Connect(ctx, params) if err != nil { mysqlStats.Record("ConnectError", start) } return &DBConnection{c, mysqlStats}, err }
[ "func", "NewDBConnection", "(", "info", "*", "mysql", ".", "ConnParams", ",", "mysqlStats", "*", "stats", ".", "Timings", ")", "(", "*", "DBConnection", ",", "error", ")", "{", "start", ":=", "time", ".", "Now", "(", ")", "\n", "defer", "mysqlStats", ".", "Record", "(", "\"", "\"", ",", "start", ")", "\n", "params", ",", "err", ":=", "dbconfigs", ".", "WithCredentials", "(", "info", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "c", ",", "err", ":=", "mysql", ".", "Connect", "(", "ctx", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "mysqlStats", ".", "Record", "(", "\"", "\"", ",", "start", ")", "\n", "}", "\n", "return", "&", "DBConnection", "{", "c", ",", "mysqlStats", "}", ",", "err", "\n", "}" ]
// NewDBConnection returns a new DBConnection based on the ConnParams // and will use the provided stats to collect timing.
[ "NewDBConnection", "returns", "a", "new", "DBConnection", "based", "on", "the", "ConnParams", "and", "will", "use", "the", "provided", "stats", "to", "collect", "timing", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/dbconnpool/connection.go#L119-L132
train
vitessio/vitess
go/vt/vtgate/buffer/timeout_thread.go
waitForEntry
func (tt *timeoutThread) waitForEntry(e *entry) bool { windowExceeded := time.NewTimer(time.Until(e.deadline)) defer windowExceeded.Stop() select { // a) Always check these channels, regardless of the state. case <-tt.maxDuration.C: // Max duration is up. Stop buffering. Do not error out entries explicitly. tt.sb.stopBufferingDueToMaxDuration() return true case <-tt.stopChan: // Failover ended before timeout. Do nothing. return true // b) Entry-specific checks. case <-e.done: // Entry was drained or evicted. Get the next entry. return false // NOTE: We're not waiting for e.bufferCtx here (which triggers when the // request was externally aborted e.g. due to context canceled) because then // this thread would race with the request thread which runs // shardBuffer.remove(). Instead, remove() will notify us here eventually by // closing "e.done". case <-windowExceeded.C: // Entry expired. Evict it and then get the next entry. tt.sb.evictOldestEntry(e) return false } }
go
func (tt *timeoutThread) waitForEntry(e *entry) bool { windowExceeded := time.NewTimer(time.Until(e.deadline)) defer windowExceeded.Stop() select { // a) Always check these channels, regardless of the state. case <-tt.maxDuration.C: // Max duration is up. Stop buffering. Do not error out entries explicitly. tt.sb.stopBufferingDueToMaxDuration() return true case <-tt.stopChan: // Failover ended before timeout. Do nothing. return true // b) Entry-specific checks. case <-e.done: // Entry was drained or evicted. Get the next entry. return false // NOTE: We're not waiting for e.bufferCtx here (which triggers when the // request was externally aborted e.g. due to context canceled) because then // this thread would race with the request thread which runs // shardBuffer.remove(). Instead, remove() will notify us here eventually by // closing "e.done". case <-windowExceeded.C: // Entry expired. Evict it and then get the next entry. tt.sb.evictOldestEntry(e) return false } }
[ "func", "(", "tt", "*", "timeoutThread", ")", "waitForEntry", "(", "e", "*", "entry", ")", "bool", "{", "windowExceeded", ":=", "time", ".", "NewTimer", "(", "time", ".", "Until", "(", "e", ".", "deadline", ")", ")", "\n", "defer", "windowExceeded", ".", "Stop", "(", ")", "\n\n", "select", "{", "// a) Always check these channels, regardless of the state.", "case", "<-", "tt", ".", "maxDuration", ".", "C", ":", "// Max duration is up. Stop buffering. Do not error out entries explicitly.", "tt", ".", "sb", ".", "stopBufferingDueToMaxDuration", "(", ")", "\n", "return", "true", "\n", "case", "<-", "tt", ".", "stopChan", ":", "// Failover ended before timeout. Do nothing.", "return", "true", "\n", "// b) Entry-specific checks.", "case", "<-", "e", ".", "done", ":", "// Entry was drained or evicted. Get the next entry.", "return", "false", "\n", "// NOTE: We're not waiting for e.bufferCtx here (which triggers when the", "// request was externally aborted e.g. due to context canceled) because then", "// this thread would race with the request thread which runs", "// shardBuffer.remove(). Instead, remove() will notify us here eventually by", "// closing \"e.done\".", "case", "<-", "windowExceeded", ".", "C", ":", "// Entry expired. Evict it and then get the next entry.", "tt", ".", "sb", ".", "evictOldestEntry", "(", "e", ")", "\n", "return", "false", "\n", "}", "\n", "}" ]
// waitForEntry blocks until "e" exceeds its buffering window or buffering stops // in general. It returns true if the timeout thread should stop.
[ "waitForEntry", "blocks", "until", "e", "exceeds", "its", "buffering", "window", "or", "buffering", "stops", "in", "general", ".", "It", "returns", "true", "if", "the", "timeout", "thread", "should", "stop", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/buffer/timeout_thread.go#L97-L124
train
vitessio/vitess
go/vt/vtgate/buffer/timeout_thread.go
waitForNonEmptyQueue
func (tt *timeoutThread) waitForNonEmptyQueue() bool { tt.mu.Lock() queueNotEmpty := tt.queueNotEmpty tt.mu.Unlock() select { // a) Always check these channels, regardless of the state. case <-tt.maxDuration.C: // Max duration is up. Stop buffering. Do not error out entries explicitly. tt.sb.stopBufferingDueToMaxDuration() return true case <-tt.stopChan: // Failover ended before timeout. Do nothing. return true // b) State-specific check. case <-queueNotEmpty: // At least one entry present. Check its timeout in the next iteration. return false } }
go
func (tt *timeoutThread) waitForNonEmptyQueue() bool { tt.mu.Lock() queueNotEmpty := tt.queueNotEmpty tt.mu.Unlock() select { // a) Always check these channels, regardless of the state. case <-tt.maxDuration.C: // Max duration is up. Stop buffering. Do not error out entries explicitly. tt.sb.stopBufferingDueToMaxDuration() return true case <-tt.stopChan: // Failover ended before timeout. Do nothing. return true // b) State-specific check. case <-queueNotEmpty: // At least one entry present. Check its timeout in the next iteration. return false } }
[ "func", "(", "tt", "*", "timeoutThread", ")", "waitForNonEmptyQueue", "(", ")", "bool", "{", "tt", ".", "mu", ".", "Lock", "(", ")", "\n", "queueNotEmpty", ":=", "tt", ".", "queueNotEmpty", "\n", "tt", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "select", "{", "// a) Always check these channels, regardless of the state.", "case", "<-", "tt", ".", "maxDuration", ".", "C", ":", "// Max duration is up. Stop buffering. Do not error out entries explicitly.", "tt", ".", "sb", ".", "stopBufferingDueToMaxDuration", "(", ")", "\n", "return", "true", "\n", "case", "<-", "tt", ".", "stopChan", ":", "// Failover ended before timeout. Do nothing.", "return", "true", "\n", "// b) State-specific check.", "case", "<-", "queueNotEmpty", ":", "// At least one entry present. Check its timeout in the next iteration.", "return", "false", "\n", "}", "\n", "}" ]
// waitForNonEmptyQueue blocks until the buffer queue gets a new element or // the timeout thread should be stopped. // It returns true if the timeout thread should stop.
[ "waitForNonEmptyQueue", "blocks", "until", "the", "buffer", "queue", "gets", "a", "new", "element", "or", "the", "timeout", "thread", "should", "be", "stopped", ".", "It", "returns", "true", "if", "the", "timeout", "thread", "should", "stop", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/buffer/timeout_thread.go#L129-L148
train
vitessio/vitess
go/vt/vttime/interval.go
NewInterval
func NewInterval(earliest, latest time.Time) (Interval, error) { if latest.Sub(earliest) < 0 { return Interval{}, fmt.Errorf("NewInterval: earliest has to be smaller or equal to latest, but got: earliest=%v latest=%v", earliest, latest) } return Interval{ earliest: earliest, latest: latest, }, nil }
go
func NewInterval(earliest, latest time.Time) (Interval, error) { if latest.Sub(earliest) < 0 { return Interval{}, fmt.Errorf("NewInterval: earliest has to be smaller or equal to latest, but got: earliest=%v latest=%v", earliest, latest) } return Interval{ earliest: earliest, latest: latest, }, nil }
[ "func", "NewInterval", "(", "earliest", ",", "latest", "time", ".", "Time", ")", "(", "Interval", ",", "error", ")", "{", "if", "latest", ".", "Sub", "(", "earliest", ")", "<", "0", "{", "return", "Interval", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "earliest", ",", "latest", ")", "\n", "}", "\n", "return", "Interval", "{", "earliest", ":", "earliest", ",", "latest", ":", "latest", ",", "}", ",", "nil", "\n", "}" ]
// NewInterval creates a new Interval from the provided times. // earliest has to be smaller or equal to latest, or an error is returned.
[ "NewInterval", "creates", "a", "new", "Interval", "from", "the", "provided", "times", ".", "earliest", "has", "to", "be", "smaller", "or", "equal", "to", "latest", "or", "an", "error", "is", "returned", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttime/interval.go#L32-L40
train
vitessio/vitess
go/vt/vttime/interval.go
Less
func (i Interval) Less(other Interval) bool { return i.latest.Sub(other.earliest) < 0 }
go
func (i Interval) Less(other Interval) bool { return i.latest.Sub(other.earliest) < 0 }
[ "func", "(", "i", "Interval", ")", "Less", "(", "other", "Interval", ")", "bool", "{", "return", "i", ".", "latest", ".", "Sub", "(", "other", ".", "earliest", ")", "<", "0", "\n", "}" ]
// Less returns true if the provided interval is earlier than the parameter. // Since both intervals are inclusive, comparison has to be strict.
[ "Less", "returns", "true", "if", "the", "provided", "interval", "is", "earlier", "than", "the", "parameter", ".", "Since", "both", "intervals", "are", "inclusive", "comparison", "has", "to", "be", "strict", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttime/interval.go#L58-L60
train
vitessio/vitess
go/vt/servenv/grpc_server_auth_static.go
Authenticate
func (sa *StaticAuthPlugin) Authenticate(ctx context.Context, fullMethod string) (context.Context, error) { if md, ok := metadata.FromIncomingContext(ctx); ok { if len(md["username"]) == 0 || len(md["password"]) == 0 { return nil, status.Errorf(codes.Unauthenticated, "username and password must be provided") } username := md["username"][0] password := md["password"][0] for _, authEntry := range sa.entries { if username == authEntry.Username && password == authEntry.Password { return ctx, nil } } return nil, status.Errorf(codes.PermissionDenied, "auth failure: caller %q provided invalid credentials", username) } return nil, status.Errorf(codes.Unauthenticated, "username and password must be provided") }
go
func (sa *StaticAuthPlugin) Authenticate(ctx context.Context, fullMethod string) (context.Context, error) { if md, ok := metadata.FromIncomingContext(ctx); ok { if len(md["username"]) == 0 || len(md["password"]) == 0 { return nil, status.Errorf(codes.Unauthenticated, "username and password must be provided") } username := md["username"][0] password := md["password"][0] for _, authEntry := range sa.entries { if username == authEntry.Username && password == authEntry.Password { return ctx, nil } } return nil, status.Errorf(codes.PermissionDenied, "auth failure: caller %q provided invalid credentials", username) } return nil, status.Errorf(codes.Unauthenticated, "username and password must be provided") }
[ "func", "(", "sa", "*", "StaticAuthPlugin", ")", "Authenticate", "(", "ctx", "context", ".", "Context", ",", "fullMethod", "string", ")", "(", "context", ".", "Context", ",", "error", ")", "{", "if", "md", ",", "ok", ":=", "metadata", ".", "FromIncomingContext", "(", "ctx", ")", ";", "ok", "{", "if", "len", "(", "md", "[", "\"", "\"", "]", ")", "==", "0", "||", "len", "(", "md", "[", "\"", "\"", "]", ")", "==", "0", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "Unauthenticated", ",", "\"", "\"", ")", "\n", "}", "\n", "username", ":=", "md", "[", "\"", "\"", "]", "[", "0", "]", "\n", "password", ":=", "md", "[", "\"", "\"", "]", "[", "0", "]", "\n", "for", "_", ",", "authEntry", ":=", "range", "sa", ".", "entries", "{", "if", "username", "==", "authEntry", ".", "Username", "&&", "password", "==", "authEntry", ".", "Password", "{", "return", "ctx", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "PermissionDenied", ",", "\"", "\"", ",", "username", ")", "\n", "}", "\n", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "Unauthenticated", ",", "\"", "\"", ")", "\n", "}" ]
// Authenticate implements AuthPlugin interface. This method will be used inside a middleware in grpc_server to authenticate // incoming requests.
[ "Authenticate", "implements", "AuthPlugin", "interface", ".", "This", "method", "will", "be", "used", "inside", "a", "middleware", "in", "grpc_server", "to", "authenticate", "incoming", "requests", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/servenv/grpc_server_auth_static.go#L56-L71
train
vitessio/vitess
go/vt/logutil/purge.go
purgeLogsOnce
func purgeLogsOnce(now time.Time, dir, program string, keep time.Duration) { current := make(map[string]bool) for _, level := range levels { c, err := os.Readlink(path.Join(dir, fmt.Sprintf("%s.%s", program, level))) if err != nil { continue } current[c] = true } files, err := filepath.Glob(path.Join(dir, fmt.Sprintf("%s.*", program))) if err != nil { return } for _, file := range files { if current[file] { continue } created, err := parseTimestamp(file) if err != nil { continue } if now.Sub(created) > keep { os.Remove(file) } } }
go
func purgeLogsOnce(now time.Time, dir, program string, keep time.Duration) { current := make(map[string]bool) for _, level := range levels { c, err := os.Readlink(path.Join(dir, fmt.Sprintf("%s.%s", program, level))) if err != nil { continue } current[c] = true } files, err := filepath.Glob(path.Join(dir, fmt.Sprintf("%s.*", program))) if err != nil { return } for _, file := range files { if current[file] { continue } created, err := parseTimestamp(file) if err != nil { continue } if now.Sub(created) > keep { os.Remove(file) } } }
[ "func", "purgeLogsOnce", "(", "now", "time", ".", "Time", ",", "dir", ",", "program", "string", ",", "keep", "time", ".", "Duration", ")", "{", "current", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "for", "_", ",", "level", ":=", "range", "levels", "{", "c", ",", "err", ":=", "os", ".", "Readlink", "(", "path", ".", "Join", "(", "dir", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "program", ",", "level", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "current", "[", "c", "]", "=", "true", "\n", "}", "\n\n", "files", ",", "err", ":=", "filepath", ".", "Glob", "(", "path", ".", "Join", "(", "dir", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "program", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "for", "_", ",", "file", ":=", "range", "files", "{", "if", "current", "[", "file", "]", "{", "continue", "\n", "}", "\n", "created", ",", "err", ":=", "parseTimestamp", "(", "file", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "if", "now", ".", "Sub", "(", "created", ")", ">", "keep", "{", "os", ".", "Remove", "(", "file", ")", "\n", "}", "\n", "}", "\n", "}" ]
// purgeLogsOnce removes logfiles for program for dir, if their age // relative to now is greater than keep.
[ "purgeLogsOnce", "removes", "logfiles", "for", "program", "for", "dir", "if", "their", "age", "relative", "to", "now", "is", "greater", "than", "keep", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/logutil/purge.go#L49-L75
train
vitessio/vitess
go/vt/logutil/purge.go
PurgeLogs
func PurgeLogs() { f := flag.Lookup("log_dir") if f == nil { panic("the logging module doesn't specify a log_dir flag") } if *keepLogs == 0*time.Second { return } logDir := f.Value.String() program := filepath.Base(os.Args[0]) timer := time.NewTimer(*purgeLogsInterval) for range timer.C { purgeLogsOnce(time.Now(), logDir, program, *keepLogs) } }
go
func PurgeLogs() { f := flag.Lookup("log_dir") if f == nil { panic("the logging module doesn't specify a log_dir flag") } if *keepLogs == 0*time.Second { return } logDir := f.Value.String() program := filepath.Base(os.Args[0]) timer := time.NewTimer(*purgeLogsInterval) for range timer.C { purgeLogsOnce(time.Now(), logDir, program, *keepLogs) } }
[ "func", "PurgeLogs", "(", ")", "{", "f", ":=", "flag", ".", "Lookup", "(", "\"", "\"", ")", "\n", "if", "f", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "*", "keepLogs", "==", "0", "*", "time", ".", "Second", "{", "return", "\n", "}", "\n", "logDir", ":=", "f", ".", "Value", ".", "String", "(", ")", "\n", "program", ":=", "filepath", ".", "Base", "(", "os", ".", "Args", "[", "0", "]", ")", "\n\n", "timer", ":=", "time", ".", "NewTimer", "(", "*", "purgeLogsInterval", ")", "\n", "for", "range", "timer", ".", "C", "{", "purgeLogsOnce", "(", "time", ".", "Now", "(", ")", ",", "logDir", ",", "program", ",", "*", "keepLogs", ")", "\n", "}", "\n", "}" ]
// PurgeLogs removes any log files that were started more than // keepLogs ago and that aren't the current log.
[ "PurgeLogs", "removes", "any", "log", "files", "that", "were", "started", "more", "than", "keepLogs", "ago", "and", "that", "aren", "t", "the", "current", "log", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/logutil/purge.go#L79-L95
train
vitessio/vitess
go/vt/vterrors/proto3.go
ToVTRPC
func ToVTRPC(err error) *vtrpcpb.RPCError { if err == nil { return nil } code := Code(err) return &vtrpcpb.RPCError{ LegacyCode: CodeToLegacyErrorCode(code), Code: code, Message: err.Error(), } }
go
func ToVTRPC(err error) *vtrpcpb.RPCError { if err == nil { return nil } code := Code(err) return &vtrpcpb.RPCError{ LegacyCode: CodeToLegacyErrorCode(code), Code: code, Message: err.Error(), } }
[ "func", "ToVTRPC", "(", "err", "error", ")", "*", "vtrpcpb", ".", "RPCError", "{", "if", "err", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "code", ":=", "Code", "(", "err", ")", "\n", "return", "&", "vtrpcpb", ".", "RPCError", "{", "LegacyCode", ":", "CodeToLegacyErrorCode", "(", "code", ")", ",", "Code", ":", "code", ",", "Message", ":", "err", ".", "Error", "(", ")", ",", "}", "\n", "}" ]
// ToVTRPC converts from vtError to a vtrpcpb.RPCError.
[ "ToVTRPC", "converts", "from", "vtError", "to", "a", "vtrpcpb", ".", "RPCError", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vterrors/proto3.go#L42-L52
train
vitessio/vitess
go/fileutil/wildcards.go
HasWildcard
func HasWildcard(path string) bool { for i := 0; i < len(path); i++ { switch path[i] { case '\\': if i+1 >= len(path) { return true } i++ case '*', '?', '[': return true } } return false }
go
func HasWildcard(path string) bool { for i := 0; i < len(path); i++ { switch path[i] { case '\\': if i+1 >= len(path) { return true } i++ case '*', '?', '[': return true } } return false }
[ "func", "HasWildcard", "(", "path", "string", ")", "bool", "{", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "path", ")", ";", "i", "++", "{", "switch", "path", "[", "i", "]", "{", "case", "'\\\\'", ":", "if", "i", "+", "1", ">=", "len", "(", "path", ")", "{", "return", "true", "\n", "}", "\n", "i", "++", "\n", "case", "'*'", ",", "'?'", ",", "'['", ":", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// HasWildcard checks if a string has a wildcard in it. In the cases // where we detect a bad pattern, we return 'true', and let the path.Match // function find it.
[ "HasWildcard", "checks", "if", "a", "string", "has", "a", "wildcard", "in", "it", ".", "In", "the", "cases", "where", "we", "detect", "a", "bad", "pattern", "we", "return", "true", "and", "let", "the", "path", ".", "Match", "function", "find", "it", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/fileutil/wildcards.go#L23-L36
train
vitessio/vitess
go/event/hooks.go
Add
func (h *Hooks) Add(f func()) { h.mu.Lock() defer h.mu.Unlock() h.funcs = append(h.funcs, f) }
go
func (h *Hooks) Add(f func()) { h.mu.Lock() defer h.mu.Unlock() h.funcs = append(h.funcs, f) }
[ "func", "(", "h", "*", "Hooks", ")", "Add", "(", "f", "func", "(", ")", ")", "{", "h", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "h", ".", "mu", ".", "Unlock", "(", ")", "\n", "h", ".", "funcs", "=", "append", "(", "h", ".", "funcs", ",", "f", ")", "\n", "}" ]
// Add appends the given function to the list to be triggered.
[ "Add", "appends", "the", "given", "function", "to", "the", "list", "to", "be", "triggered", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/event/hooks.go#L31-L35
train
vitessio/vitess
go/vt/worker/legacy_split_clone.go
NewLegacySplitCloneWorker
func NewLegacySplitCloneWorker(wr *wrangler.Wrangler, cell, keyspace, shard string, excludeTables []string, sourceReaderCount, destinationPackCount, destinationWriterCount, minHealthyRdonlyTablets int, maxTPS int64) (Worker, error) { if maxTPS != throttler.MaxRateModuleDisabled { wr.Logger().Infof("throttling enabled and set to a max of %v transactions/second", maxTPS) } if maxTPS != throttler.MaxRateModuleDisabled && maxTPS < int64(destinationWriterCount) { return nil, fmt.Errorf("-max_tps must be >= -destination_writer_count: %v >= %v", maxTPS, destinationWriterCount) } return &LegacySplitCloneWorker{ StatusWorker: NewStatusWorker(), wr: wr, cell: cell, keyspace: keyspace, shard: shard, excludeTables: excludeTables, sourceReaderCount: sourceReaderCount, destinationPackCount: destinationPackCount, destinationWriterCount: destinationWriterCount, minHealthyRdonlyTablets: minHealthyRdonlyTablets, maxTPS: maxTPS, cleaner: &wrangler.Cleaner{}, destinationDbNames: make(map[string]string), destinationThrottlers: make(map[string]*throttler.Throttler), ev: &events.SplitClone{ Cell: cell, Keyspace: keyspace, Shard: shard, ExcludeTables: excludeTables, }, }, nil }
go
func NewLegacySplitCloneWorker(wr *wrangler.Wrangler, cell, keyspace, shard string, excludeTables []string, sourceReaderCount, destinationPackCount, destinationWriterCount, minHealthyRdonlyTablets int, maxTPS int64) (Worker, error) { if maxTPS != throttler.MaxRateModuleDisabled { wr.Logger().Infof("throttling enabled and set to a max of %v transactions/second", maxTPS) } if maxTPS != throttler.MaxRateModuleDisabled && maxTPS < int64(destinationWriterCount) { return nil, fmt.Errorf("-max_tps must be >= -destination_writer_count: %v >= %v", maxTPS, destinationWriterCount) } return &LegacySplitCloneWorker{ StatusWorker: NewStatusWorker(), wr: wr, cell: cell, keyspace: keyspace, shard: shard, excludeTables: excludeTables, sourceReaderCount: sourceReaderCount, destinationPackCount: destinationPackCount, destinationWriterCount: destinationWriterCount, minHealthyRdonlyTablets: minHealthyRdonlyTablets, maxTPS: maxTPS, cleaner: &wrangler.Cleaner{}, destinationDbNames: make(map[string]string), destinationThrottlers: make(map[string]*throttler.Throttler), ev: &events.SplitClone{ Cell: cell, Keyspace: keyspace, Shard: shard, ExcludeTables: excludeTables, }, }, nil }
[ "func", "NewLegacySplitCloneWorker", "(", "wr", "*", "wrangler", ".", "Wrangler", ",", "cell", ",", "keyspace", ",", "shard", "string", ",", "excludeTables", "[", "]", "string", ",", "sourceReaderCount", ",", "destinationPackCount", ",", "destinationWriterCount", ",", "minHealthyRdonlyTablets", "int", ",", "maxTPS", "int64", ")", "(", "Worker", ",", "error", ")", "{", "if", "maxTPS", "!=", "throttler", ".", "MaxRateModuleDisabled", "{", "wr", ".", "Logger", "(", ")", ".", "Infof", "(", "\"", "\"", ",", "maxTPS", ")", "\n", "}", "\n", "if", "maxTPS", "!=", "throttler", ".", "MaxRateModuleDisabled", "&&", "maxTPS", "<", "int64", "(", "destinationWriterCount", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "maxTPS", ",", "destinationWriterCount", ")", "\n", "}", "\n", "return", "&", "LegacySplitCloneWorker", "{", "StatusWorker", ":", "NewStatusWorker", "(", ")", ",", "wr", ":", "wr", ",", "cell", ":", "cell", ",", "keyspace", ":", "keyspace", ",", "shard", ":", "shard", ",", "excludeTables", ":", "excludeTables", ",", "sourceReaderCount", ":", "sourceReaderCount", ",", "destinationPackCount", ":", "destinationPackCount", ",", "destinationWriterCount", ":", "destinationWriterCount", ",", "minHealthyRdonlyTablets", ":", "minHealthyRdonlyTablets", ",", "maxTPS", ":", "maxTPS", ",", "cleaner", ":", "&", "wrangler", ".", "Cleaner", "{", "}", ",", "destinationDbNames", ":", "make", "(", "map", "[", "string", "]", "string", ")", ",", "destinationThrottlers", ":", "make", "(", "map", "[", "string", "]", "*", "throttler", ".", "Throttler", ")", ",", "ev", ":", "&", "events", ".", "SplitClone", "{", "Cell", ":", "cell", ",", "Keyspace", ":", "keyspace", ",", "Shard", ":", "shard", ",", "ExcludeTables", ":", "excludeTables", ",", "}", ",", "}", ",", "nil", "\n", "}" ]
// NewLegacySplitCloneWorker returns a new LegacySplitCloneWorker object.
[ "NewLegacySplitCloneWorker", "returns", "a", "new", "LegacySplitCloneWorker", "object", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/legacy_split_clone.go#L102-L133
train
vitessio/vitess
go/vt/worker/legacy_split_clone.go
Run
func (scw *LegacySplitCloneWorker) Run(ctx context.Context) error { resetVars() // Run the command. err := scw.run(ctx) // Cleanup. scw.setState(WorkerStateCleanUp) // Reverse any changes e.g. setting the tablet type of a source RDONLY tablet. cerr := scw.cleaner.CleanUp(scw.wr) if cerr != nil { if err != nil { scw.wr.Logger().Errorf2(cerr, "CleanUp failed in addition to job error") } else { err = cerr } } // Stop Throttlers. for _, throttler := range scw.destinationThrottlers { throttler.Close() } // Stop healthcheck. for _, watcher := range scw.destinationShardWatchers { watcher.Stop() } if scw.healthCheck != nil { if err := scw.healthCheck.Close(); err != nil { scw.wr.Logger().Errorf2(err, "HealthCheck.Close() failed") } } if err != nil { scw.setErrorState(err) return err } scw.setState(WorkerStateDone) return nil }
go
func (scw *LegacySplitCloneWorker) Run(ctx context.Context) error { resetVars() // Run the command. err := scw.run(ctx) // Cleanup. scw.setState(WorkerStateCleanUp) // Reverse any changes e.g. setting the tablet type of a source RDONLY tablet. cerr := scw.cleaner.CleanUp(scw.wr) if cerr != nil { if err != nil { scw.wr.Logger().Errorf2(cerr, "CleanUp failed in addition to job error") } else { err = cerr } } // Stop Throttlers. for _, throttler := range scw.destinationThrottlers { throttler.Close() } // Stop healthcheck. for _, watcher := range scw.destinationShardWatchers { watcher.Stop() } if scw.healthCheck != nil { if err := scw.healthCheck.Close(); err != nil { scw.wr.Logger().Errorf2(err, "HealthCheck.Close() failed") } } if err != nil { scw.setErrorState(err) return err } scw.setState(WorkerStateDone) return nil }
[ "func", "(", "scw", "*", "LegacySplitCloneWorker", ")", "Run", "(", "ctx", "context", ".", "Context", ")", "error", "{", "resetVars", "(", ")", "\n\n", "// Run the command.", "err", ":=", "scw", ".", "run", "(", "ctx", ")", "\n\n", "// Cleanup.", "scw", ".", "setState", "(", "WorkerStateCleanUp", ")", "\n", "// Reverse any changes e.g. setting the tablet type of a source RDONLY tablet.", "cerr", ":=", "scw", ".", "cleaner", ".", "CleanUp", "(", "scw", ".", "wr", ")", "\n", "if", "cerr", "!=", "nil", "{", "if", "err", "!=", "nil", "{", "scw", ".", "wr", ".", "Logger", "(", ")", ".", "Errorf2", "(", "cerr", ",", "\"", "\"", ")", "\n", "}", "else", "{", "err", "=", "cerr", "\n", "}", "\n", "}", "\n\n", "// Stop Throttlers.", "for", "_", ",", "throttler", ":=", "range", "scw", ".", "destinationThrottlers", "{", "throttler", ".", "Close", "(", ")", "\n", "}", "\n", "// Stop healthcheck.", "for", "_", ",", "watcher", ":=", "range", "scw", ".", "destinationShardWatchers", "{", "watcher", ".", "Stop", "(", ")", "\n", "}", "\n", "if", "scw", ".", "healthCheck", "!=", "nil", "{", "if", "err", ":=", "scw", ".", "healthCheck", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "scw", ".", "wr", ".", "Logger", "(", ")", ".", "Errorf2", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "scw", ".", "setErrorState", "(", "err", ")", "\n", "return", "err", "\n", "}", "\n", "scw", ".", "setState", "(", "WorkerStateDone", ")", "\n", "return", "nil", "\n", "}" ]
// Run implements the Worker interface
[ "Run", "implements", "the", "Worker", "interface" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/legacy_split_clone.go#L197-L235
train
vitessio/vitess
go/vt/worker/legacy_split_clone.go
processData
func (scw *LegacySplitCloneWorker) processData(ctx context.Context, dbNames []string, td *tabletmanagerdatapb.TableDefinition, tableIndex int, rr ResultReader, rowSplitter *RowSplitter, insertChannels []chan string, destinationPackCount int) error { // Store the baseCmd per destination shard because each tablet may have a // different dbName. baseCmds := make([]string, len(dbNames)) for i, dbName := range dbNames { baseCmds[i] = "INSERT INTO " + sqlescape.EscapeID(dbName) + "." + sqlescape.EscapeID(td.Name) + " (" + strings.Join(escapeAll(td.Columns), ", ") + ") VALUES " } sr := rowSplitter.StartSplit() packCount := 0 fields := rr.Fields() for { r, err := rr.Next() if err != nil { // we are done, see if there was an error if err != io.EOF { return err } // send the remainder if any (ignoring // the return value, we don't care // here if we're aborted) if packCount > 0 { rowSplitter.Send(fields, sr, baseCmds, insertChannels, ctx.Done()) } return nil } // Split the rows by keyspace ID, and insert each chunk into each destination if err := rowSplitter.Split(sr, r.Rows); err != nil { return vterrors.Wrapf(err, "RowSplitter failed for table %v", td.Name) } scw.tableStatusList.addCopiedRows(tableIndex, len(r.Rows)) // see if we reach the destination pack count packCount++ if packCount < destinationPackCount { continue } // send the rows to be inserted if aborted := rowSplitter.Send(fields, sr, baseCmds, insertChannels, ctx.Done()); aborted { return nil } // and reset our row buffer sr = rowSplitter.StartSplit() packCount = 0 } }
go
func (scw *LegacySplitCloneWorker) processData(ctx context.Context, dbNames []string, td *tabletmanagerdatapb.TableDefinition, tableIndex int, rr ResultReader, rowSplitter *RowSplitter, insertChannels []chan string, destinationPackCount int) error { // Store the baseCmd per destination shard because each tablet may have a // different dbName. baseCmds := make([]string, len(dbNames)) for i, dbName := range dbNames { baseCmds[i] = "INSERT INTO " + sqlescape.EscapeID(dbName) + "." + sqlescape.EscapeID(td.Name) + " (" + strings.Join(escapeAll(td.Columns), ", ") + ") VALUES " } sr := rowSplitter.StartSplit() packCount := 0 fields := rr.Fields() for { r, err := rr.Next() if err != nil { // we are done, see if there was an error if err != io.EOF { return err } // send the remainder if any (ignoring // the return value, we don't care // here if we're aborted) if packCount > 0 { rowSplitter.Send(fields, sr, baseCmds, insertChannels, ctx.Done()) } return nil } // Split the rows by keyspace ID, and insert each chunk into each destination if err := rowSplitter.Split(sr, r.Rows); err != nil { return vterrors.Wrapf(err, "RowSplitter failed for table %v", td.Name) } scw.tableStatusList.addCopiedRows(tableIndex, len(r.Rows)) // see if we reach the destination pack count packCount++ if packCount < destinationPackCount { continue } // send the rows to be inserted if aborted := rowSplitter.Send(fields, sr, baseCmds, insertChannels, ctx.Done()); aborted { return nil } // and reset our row buffer sr = rowSplitter.StartSplit() packCount = 0 } }
[ "func", "(", "scw", "*", "LegacySplitCloneWorker", ")", "processData", "(", "ctx", "context", ".", "Context", ",", "dbNames", "[", "]", "string", ",", "td", "*", "tabletmanagerdatapb", ".", "TableDefinition", ",", "tableIndex", "int", ",", "rr", "ResultReader", ",", "rowSplitter", "*", "RowSplitter", ",", "insertChannels", "[", "]", "chan", "string", ",", "destinationPackCount", "int", ")", "error", "{", "// Store the baseCmd per destination shard because each tablet may have a", "// different dbName.", "baseCmds", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "dbNames", ")", ")", "\n", "for", "i", ",", "dbName", ":=", "range", "dbNames", "{", "baseCmds", "[", "i", "]", "=", "\"", "\"", "+", "sqlescape", ".", "EscapeID", "(", "dbName", ")", "+", "\"", "\"", "+", "sqlescape", ".", "EscapeID", "(", "td", ".", "Name", ")", "+", "\"", "\"", "+", "strings", ".", "Join", "(", "escapeAll", "(", "td", ".", "Columns", ")", ",", "\"", "\"", ")", "+", "\"", "\"", "\n", "}", "\n", "sr", ":=", "rowSplitter", ".", "StartSplit", "(", ")", "\n", "packCount", ":=", "0", "\n\n", "fields", ":=", "rr", ".", "Fields", "(", ")", "\n", "for", "{", "r", ",", "err", ":=", "rr", ".", "Next", "(", ")", "\n", "if", "err", "!=", "nil", "{", "// we are done, see if there was an error", "if", "err", "!=", "io", ".", "EOF", "{", "return", "err", "\n", "}", "\n\n", "// send the remainder if any (ignoring", "// the return value, we don't care", "// here if we're aborted)", "if", "packCount", ">", "0", "{", "rowSplitter", ".", "Send", "(", "fields", ",", "sr", ",", "baseCmds", ",", "insertChannels", ",", "ctx", ".", "Done", "(", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n\n", "// Split the rows by keyspace ID, and insert each chunk into each destination", "if", "err", ":=", "rowSplitter", ".", "Split", "(", "sr", ",", "r", ".", "Rows", ")", ";", "err", "!=", "nil", "{", "return", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "td", ".", "Name", ")", "\n", "}", "\n", "scw", ".", "tableStatusList", ".", "addCopiedRows", "(", "tableIndex", ",", "len", "(", "r", ".", "Rows", ")", ")", "\n\n", "// see if we reach the destination pack count", "packCount", "++", "\n", "if", "packCount", "<", "destinationPackCount", "{", "continue", "\n", "}", "\n\n", "// send the rows to be inserted", "if", "aborted", ":=", "rowSplitter", ".", "Send", "(", "fields", ",", "sr", ",", "baseCmds", ",", "insertChannels", ",", "ctx", ".", "Done", "(", ")", ")", ";", "aborted", "{", "return", "nil", "\n", "}", "\n\n", "// and reset our row buffer", "sr", "=", "rowSplitter", ".", "StartSplit", "(", ")", "\n", "packCount", "=", "0", "\n", "}", "\n", "}" ]
// processData pumps the data out of the provided QueryResultReader. // It returns any error the source encounters.
[ "processData", "pumps", "the", "data", "out", "of", "the", "provided", "QueryResultReader", ".", "It", "returns", "any", "error", "the", "source", "encounters", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/legacy_split_clone.go#L658-L707
train
vitessio/vitess
go/vt/throttler/throttler.go
updateMaxRate
func (t *Throttler) updateMaxRate() { // Set it to infinite initially. maxRate := int64(math.MaxInt64) // Find out the new max rate (minimum among all modules). for _, m := range t.modules { if moduleMaxRate := m.MaxRate(); moduleMaxRate < maxRate { maxRate = moduleMaxRate } } // Set the new max rate on each thread. t.mu.Lock() defer t.mu.Unlock() threadsRunning := len(t.runningThreads) if threadsRunning == 0 { // Throttler is done. Set rates don't matter anymore. return } if maxRate != ZeroRateNoProgess && maxRate < int64(threadsRunning) { log.Warningf("Set maxRate is less than the number of threads (%v). To prevent threads from starving, maxRate was increased from: %v to: %v.", threadsRunning, maxRate, threadsRunning) maxRate = int64(threadsRunning) } maxRatePerThread := maxRate / int64(threadsRunning) // Distribute the remainder of the division across all threads. remainder := maxRate % int64(threadsRunning) remainderPerThread := make(map[int]int64, threadsRunning) for id := 0; remainder > 0; { remainderPerThread[id]++ remainder-- id++ } for threadID := range t.runningThreads { t.threadThrottlers[threadID].setMaxRate(maxRatePerThread + remainderPerThread[threadID]) } t.threadRunningsLastUpdate = threadsRunning }
go
func (t *Throttler) updateMaxRate() { // Set it to infinite initially. maxRate := int64(math.MaxInt64) // Find out the new max rate (minimum among all modules). for _, m := range t.modules { if moduleMaxRate := m.MaxRate(); moduleMaxRate < maxRate { maxRate = moduleMaxRate } } // Set the new max rate on each thread. t.mu.Lock() defer t.mu.Unlock() threadsRunning := len(t.runningThreads) if threadsRunning == 0 { // Throttler is done. Set rates don't matter anymore. return } if maxRate != ZeroRateNoProgess && maxRate < int64(threadsRunning) { log.Warningf("Set maxRate is less than the number of threads (%v). To prevent threads from starving, maxRate was increased from: %v to: %v.", threadsRunning, maxRate, threadsRunning) maxRate = int64(threadsRunning) } maxRatePerThread := maxRate / int64(threadsRunning) // Distribute the remainder of the division across all threads. remainder := maxRate % int64(threadsRunning) remainderPerThread := make(map[int]int64, threadsRunning) for id := 0; remainder > 0; { remainderPerThread[id]++ remainder-- id++ } for threadID := range t.runningThreads { t.threadThrottlers[threadID].setMaxRate(maxRatePerThread + remainderPerThread[threadID]) } t.threadRunningsLastUpdate = threadsRunning }
[ "func", "(", "t", "*", "Throttler", ")", "updateMaxRate", "(", ")", "{", "// Set it to infinite initially.", "maxRate", ":=", "int64", "(", "math", ".", "MaxInt64", ")", "\n\n", "// Find out the new max rate (minimum among all modules).", "for", "_", ",", "m", ":=", "range", "t", ".", "modules", "{", "if", "moduleMaxRate", ":=", "m", ".", "MaxRate", "(", ")", ";", "moduleMaxRate", "<", "maxRate", "{", "maxRate", "=", "moduleMaxRate", "\n", "}", "\n", "}", "\n\n", "// Set the new max rate on each thread.", "t", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "mu", ".", "Unlock", "(", ")", "\n", "threadsRunning", ":=", "len", "(", "t", ".", "runningThreads", ")", "\n", "if", "threadsRunning", "==", "0", "{", "// Throttler is done. Set rates don't matter anymore.", "return", "\n", "}", "\n\n", "if", "maxRate", "!=", "ZeroRateNoProgess", "&&", "maxRate", "<", "int64", "(", "threadsRunning", ")", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "threadsRunning", ",", "maxRate", ",", "threadsRunning", ")", "\n", "maxRate", "=", "int64", "(", "threadsRunning", ")", "\n", "}", "\n", "maxRatePerThread", ":=", "maxRate", "/", "int64", "(", "threadsRunning", ")", "\n", "// Distribute the remainder of the division across all threads.", "remainder", ":=", "maxRate", "%", "int64", "(", "threadsRunning", ")", "\n", "remainderPerThread", ":=", "make", "(", "map", "[", "int", "]", "int64", ",", "threadsRunning", ")", "\n", "for", "id", ":=", "0", ";", "remainder", ">", "0", ";", "{", "remainderPerThread", "[", "id", "]", "++", "\n", "remainder", "--", "\n", "id", "++", "\n", "}", "\n\n", "for", "threadID", ":=", "range", "t", ".", "runningThreads", "{", "t", ".", "threadThrottlers", "[", "threadID", "]", ".", "setMaxRate", "(", "maxRatePerThread", "+", "remainderPerThread", "[", "threadID", "]", ")", "\n", "}", "\n", "t", ".", "threadRunningsLastUpdate", "=", "threadsRunning", "\n", "}" ]
// updateMaxRate recalculates the current max rate and updates all // threadThrottlers accordingly. // The rate changes when the number of thread changes or a module updated its // max rate.
[ "updateMaxRate", "recalculates", "the", "current", "max", "rate", "and", "updates", "all", "threadThrottlers", "accordingly", ".", "The", "rate", "changes", "when", "the", "number", "of", "thread", "changes", "or", "a", "module", "updated", "its", "max", "rate", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/throttler.go#L245-L283
train
vitessio/vitess
go/vt/throttler/throttler.go
UpdateConfiguration
func (t *Throttler) UpdateConfiguration(configuration *throttlerdatapb.Configuration, copyZeroValues bool) error { return t.maxReplicationLagModule.updateConfiguration(configuration, copyZeroValues) }
go
func (t *Throttler) UpdateConfiguration(configuration *throttlerdatapb.Configuration, copyZeroValues bool) error { return t.maxReplicationLagModule.updateConfiguration(configuration, copyZeroValues) }
[ "func", "(", "t", "*", "Throttler", ")", "UpdateConfiguration", "(", "configuration", "*", "throttlerdatapb", ".", "Configuration", ",", "copyZeroValues", "bool", ")", "error", "{", "return", "t", ".", "maxReplicationLagModule", ".", "updateConfiguration", "(", "configuration", ",", "copyZeroValues", ")", "\n", "}" ]
// UpdateConfiguration updates the configuration of the MaxReplicationLag module.
[ "UpdateConfiguration", "updates", "the", "configuration", "of", "the", "MaxReplicationLag", "module", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/throttler.go#L308-L310
train
vitessio/vitess
go/vt/vtgate/planbuilder/limit.go
newLimit
func newLimit(bldr builder) *limit { return &limit{ order: bldr.Order() + 1, resultColumns: bldr.ResultColumns(), input: bldr, elimit: &engine.Limit{}, } }
go
func newLimit(bldr builder) *limit { return &limit{ order: bldr.Order() + 1, resultColumns: bldr.ResultColumns(), input: bldr, elimit: &engine.Limit{}, } }
[ "func", "newLimit", "(", "bldr", "builder", ")", "*", "limit", "{", "return", "&", "limit", "{", "order", ":", "bldr", ".", "Order", "(", ")", "+", "1", ",", "resultColumns", ":", "bldr", ".", "ResultColumns", "(", ")", ",", "input", ":", "bldr", ",", "elimit", ":", "&", "engine", ".", "Limit", "{", "}", ",", "}", "\n", "}" ]
// newLimit builds a new limit.
[ "newLimit", "builds", "a", "new", "limit", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/limit.go#L39-L46
train
vitessio/vitess
go/vt/vtgate/planbuilder/limit.go
SetLimit
func (l *limit) SetLimit(limit *sqlparser.Limit) error { count, ok := limit.Rowcount.(*sqlparser.SQLVal) if !ok { return fmt.Errorf("unexpected expression in LIMIT: %v", sqlparser.String(limit)) } pv, err := sqlparser.NewPlanValue(count) if err != nil { return err } l.elimit.Count = pv switch offset := limit.Offset.(type) { case *sqlparser.SQLVal: pv, err = sqlparser.NewPlanValue(offset) if err != nil { return err } l.elimit.Offset = pv case nil: // NOOP default: return fmt.Errorf("unexpected expression in LIMIT: %v", sqlparser.String(limit)) } l.input.SetUpperLimit(sqlparser.NewValArg([]byte(":__upper_limit"))) return nil }
go
func (l *limit) SetLimit(limit *sqlparser.Limit) error { count, ok := limit.Rowcount.(*sqlparser.SQLVal) if !ok { return fmt.Errorf("unexpected expression in LIMIT: %v", sqlparser.String(limit)) } pv, err := sqlparser.NewPlanValue(count) if err != nil { return err } l.elimit.Count = pv switch offset := limit.Offset.(type) { case *sqlparser.SQLVal: pv, err = sqlparser.NewPlanValue(offset) if err != nil { return err } l.elimit.Offset = pv case nil: // NOOP default: return fmt.Errorf("unexpected expression in LIMIT: %v", sqlparser.String(limit)) } l.input.SetUpperLimit(sqlparser.NewValArg([]byte(":__upper_limit"))) return nil }
[ "func", "(", "l", "*", "limit", ")", "SetLimit", "(", "limit", "*", "sqlparser", ".", "Limit", ")", "error", "{", "count", ",", "ok", ":=", "limit", ".", "Rowcount", ".", "(", "*", "sqlparser", ".", "SQLVal", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "sqlparser", ".", "String", "(", "limit", ")", ")", "\n", "}", "\n", "pv", ",", "err", ":=", "sqlparser", ".", "NewPlanValue", "(", "count", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "l", ".", "elimit", ".", "Count", "=", "pv", "\n\n", "switch", "offset", ":=", "limit", ".", "Offset", ".", "(", "type", ")", "{", "case", "*", "sqlparser", ".", "SQLVal", ":", "pv", ",", "err", "=", "sqlparser", ".", "NewPlanValue", "(", "offset", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "l", ".", "elimit", ".", "Offset", "=", "pv", "\n", "case", "nil", ":", "// NOOP", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "sqlparser", ".", "String", "(", "limit", ")", ")", "\n", "}", "\n\n", "l", ".", "input", ".", "SetUpperLimit", "(", "sqlparser", ".", "NewValArg", "(", "[", "]", "byte", "(", "\"", "\"", ")", ")", ")", "\n", "return", "nil", "\n", "}" ]
// SetLimit sets the limit for the primitive. It calls the underlying // primitive's SetUpperLimit, which is an optimization hint that informs // the underlying primitive that it doesn't need to return more rows than // specified.
[ "SetLimit", "sets", "the", "limit", "for", "the", "primitive", ".", "It", "calls", "the", "underlying", "primitive", "s", "SetUpperLimit", "which", "is", "an", "optimization", "hint", "that", "informs", "the", "underlying", "primitive", "that", "it", "doesn", "t", "need", "to", "return", "more", "rows", "than", "specified", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/limit.go#L109-L135
train
vitessio/vitess
go/stats/counters.go
ResetAll
func (c *counters) ResetAll() { c.mu.Lock() defer c.mu.Unlock() c.counts = make(map[string]*int64) }
go
func (c *counters) ResetAll() { c.mu.Lock() defer c.mu.Unlock() c.counts = make(map[string]*int64) }
[ "func", "(", "c", "*", "counters", ")", "ResetAll", "(", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "c", ".", "counts", "=", "make", "(", "map", "[", "string", "]", "*", "int64", ")", "\n", "}" ]
// ResetAll resets all counter values and clears all keys.
[ "ResetAll", "resets", "all", "counter", "values", "and", "clears", "all", "keys", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/stats/counters.go#L91-L95
train
vitessio/vitess
go/stats/counters.go
ZeroAll
func (c *counters) ZeroAll() { c.mu.Lock() defer c.mu.Unlock() for _, a := range c.counts { atomic.StoreInt64(a, int64(0)) } }
go
func (c *counters) ZeroAll() { c.mu.Lock() defer c.mu.Unlock() for _, a := range c.counts { atomic.StoreInt64(a, int64(0)) } }
[ "func", "(", "c", "*", "counters", ")", "ZeroAll", "(", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "for", "_", ",", "a", ":=", "range", "c", ".", "counts", "{", "atomic", ".", "StoreInt64", "(", "a", ",", "int64", "(", "0", ")", ")", "\n", "}", "\n", "}" ]
// ZeroAll resets all counter values to zero
[ "ZeroAll", "resets", "all", "counter", "values", "to", "zero" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/stats/counters.go#L98-L104
train
vitessio/vitess
go/stats/counters.go
Reset
func (c *counters) Reset(name string) { a := c.getValueAddr(name) atomic.StoreInt64(a, int64(0)) }
go
func (c *counters) Reset(name string) { a := c.getValueAddr(name) atomic.StoreInt64(a, int64(0)) }
[ "func", "(", "c", "*", "counters", ")", "Reset", "(", "name", "string", ")", "{", "a", ":=", "c", ".", "getValueAddr", "(", "name", ")", "\n", "atomic", ".", "StoreInt64", "(", "a", ",", "int64", "(", "0", ")", ")", "\n", "}" ]
// Reset resets a specific counter value to 0.
[ "Reset", "resets", "a", "specific", "counter", "value", "to", "0", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/stats/counters.go#L107-L110
train
vitessio/vitess
go/stats/counters.go
NewCountersWithSingleLabel
func NewCountersWithSingleLabel(name, help, label string, tags ...string) *CountersWithSingleLabel { c := &CountersWithSingleLabel{ counters: counters{ counts: make(map[string]*int64), help: help, }, label: label, } for _, tag := range tags { c.counts[tag] = new(int64) } if name != "" { publish(name, c) } return c }
go
func NewCountersWithSingleLabel(name, help, label string, tags ...string) *CountersWithSingleLabel { c := &CountersWithSingleLabel{ counters: counters{ counts: make(map[string]*int64), help: help, }, label: label, } for _, tag := range tags { c.counts[tag] = new(int64) } if name != "" { publish(name, c) } return c }
[ "func", "NewCountersWithSingleLabel", "(", "name", ",", "help", ",", "label", "string", ",", "tags", "...", "string", ")", "*", "CountersWithSingleLabel", "{", "c", ":=", "&", "CountersWithSingleLabel", "{", "counters", ":", "counters", "{", "counts", ":", "make", "(", "map", "[", "string", "]", "*", "int64", ")", ",", "help", ":", "help", ",", "}", ",", "label", ":", "label", ",", "}", "\n\n", "for", "_", ",", "tag", ":=", "range", "tags", "{", "c", ".", "counts", "[", "tag", "]", "=", "new", "(", "int64", ")", "\n", "}", "\n", "if", "name", "!=", "\"", "\"", "{", "publish", "(", "name", ",", "c", ")", "\n", "}", "\n", "return", "c", "\n", "}" ]
// NewCountersWithSingleLabel create a new Counters instance. // If name is set, the variable gets published. // The function also accepts an optional list of tags that pre-creates them // initialized to 0. // label is a category name used to organize the tags. It is currently only // used by Prometheus, but not by the expvar package.
[ "NewCountersWithSingleLabel", "create", "a", "new", "Counters", "instance", ".", "If", "name", "is", "set", "the", "variable", "gets", "published", ".", "The", "function", "also", "accepts", "an", "optional", "list", "of", "tags", "that", "pre", "-", "creates", "them", "initialized", "to", "0", ".", "label", "is", "a", "category", "name", "used", "to", "organize", "the", "tags", ".", "It", "is", "currently", "only", "used", "by", "Prometheus", "but", "not", "by", "the", "expvar", "package", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/stats/counters.go#L143-L159
train
vitessio/vitess
go/stats/counters.go
NewCountersWithMultiLabels
func NewCountersWithMultiLabels(name, help string, labels []string) *CountersWithMultiLabels { t := &CountersWithMultiLabels{ counters: counters{ counts: make(map[string]*int64), help: help}, labels: labels, } if name != "" { publish(name, t) } return t }
go
func NewCountersWithMultiLabels(name, help string, labels []string) *CountersWithMultiLabels { t := &CountersWithMultiLabels{ counters: counters{ counts: make(map[string]*int64), help: help}, labels: labels, } if name != "" { publish(name, t) } return t }
[ "func", "NewCountersWithMultiLabels", "(", "name", ",", "help", "string", ",", "labels", "[", "]", "string", ")", "*", "CountersWithMultiLabels", "{", "t", ":=", "&", "CountersWithMultiLabels", "{", "counters", ":", "counters", "{", "counts", ":", "make", "(", "map", "[", "string", "]", "*", "int64", ")", ",", "help", ":", "help", "}", ",", "labels", ":", "labels", ",", "}", "\n", "if", "name", "!=", "\"", "\"", "{", "publish", "(", "name", ",", "t", ")", "\n", "}", "\n\n", "return", "t", "\n", "}" ]
// NewCountersWithMultiLabels creates a new CountersWithMultiLabels // instance, and publishes it if name is set.
[ "NewCountersWithMultiLabels", "creates", "a", "new", "CountersWithMultiLabels", "instance", "and", "publishes", "it", "if", "name", "is", "set", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/stats/counters.go#L190-L202
train
vitessio/vitess
go/stats/counters.go
NewCountersFuncWithMultiLabels
func NewCountersFuncWithMultiLabels(name, help string, labels []string, f func() map[string]int64) *CountersFuncWithMultiLabels { t := &CountersFuncWithMultiLabels{ f: f, help: help, labels: labels, } if name != "" { publish(name, t) } return t }
go
func NewCountersFuncWithMultiLabels(name, help string, labels []string, f func() map[string]int64) *CountersFuncWithMultiLabels { t := &CountersFuncWithMultiLabels{ f: f, help: help, labels: labels, } if name != "" { publish(name, t) } return t }
[ "func", "NewCountersFuncWithMultiLabels", "(", "name", ",", "help", "string", ",", "labels", "[", "]", "string", ",", "f", "func", "(", ")", "map", "[", "string", "]", "int64", ")", "*", "CountersFuncWithMultiLabels", "{", "t", ":=", "&", "CountersFuncWithMultiLabels", "{", "f", ":", "f", ",", "help", ":", "help", ",", "labels", ":", "labels", ",", "}", "\n", "if", "name", "!=", "\"", "\"", "{", "publish", "(", "name", ",", "t", ")", "\n", "}", "\n\n", "return", "t", "\n", "}" ]
// NewCountersFuncWithMultiLabels creates a new CountersFuncWithMultiLabels // mapping to the provided function.
[ "NewCountersFuncWithMultiLabels", "creates", "a", "new", "CountersFuncWithMultiLabels", "mapping", "to", "the", "provided", "function", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/stats/counters.go#L269-L280
train
vitessio/vitess
go/stats/counters.go
NewGaugesWithSingleLabel
func NewGaugesWithSingleLabel(name, help, label string, tags ...string) *GaugesWithSingleLabel { g := &GaugesWithSingleLabel{ CountersWithSingleLabel: CountersWithSingleLabel{ counters: counters{ counts: make(map[string]*int64), help: help, }, label: label, }, } for _, tag := range tags { g.counts[tag] = new(int64) } if name != "" { publish(name, g) } return g }
go
func NewGaugesWithSingleLabel(name, help, label string, tags ...string) *GaugesWithSingleLabel { g := &GaugesWithSingleLabel{ CountersWithSingleLabel: CountersWithSingleLabel{ counters: counters{ counts: make(map[string]*int64), help: help, }, label: label, }, } for _, tag := range tags { g.counts[tag] = new(int64) } if name != "" { publish(name, g) } return g }
[ "func", "NewGaugesWithSingleLabel", "(", "name", ",", "help", ",", "label", "string", ",", "tags", "...", "string", ")", "*", "GaugesWithSingleLabel", "{", "g", ":=", "&", "GaugesWithSingleLabel", "{", "CountersWithSingleLabel", ":", "CountersWithSingleLabel", "{", "counters", ":", "counters", "{", "counts", ":", "make", "(", "map", "[", "string", "]", "*", "int64", ")", ",", "help", ":", "help", ",", "}", ",", "label", ":", "label", ",", "}", ",", "}", "\n\n", "for", "_", ",", "tag", ":=", "range", "tags", "{", "g", ".", "counts", "[", "tag", "]", "=", "new", "(", "int64", ")", "\n", "}", "\n", "if", "name", "!=", "\"", "\"", "{", "publish", "(", "name", ",", "g", ")", "\n", "}", "\n", "return", "g", "\n", "}" ]
// NewGaugesWithSingleLabel creates a new GaugesWithSingleLabel and // publishes it if the name is set.
[ "NewGaugesWithSingleLabel", "creates", "a", "new", "GaugesWithSingleLabel", "and", "publishes", "it", "if", "the", "name", "is", "set", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/stats/counters.go#L316-L334
train
vitessio/vitess
go/stats/counters.go
Set
func (g *GaugesWithSingleLabel) Set(name string, value int64) { a := g.getValueAddr(name) atomic.StoreInt64(a, value) }
go
func (g *GaugesWithSingleLabel) Set(name string, value int64) { a := g.getValueAddr(name) atomic.StoreInt64(a, value) }
[ "func", "(", "g", "*", "GaugesWithSingleLabel", ")", "Set", "(", "name", "string", ",", "value", "int64", ")", "{", "a", ":=", "g", ".", "getValueAddr", "(", "name", ")", "\n", "atomic", ".", "StoreInt64", "(", "a", ",", "value", ")", "\n", "}" ]
// Set sets the value of a named gauge.
[ "Set", "sets", "the", "value", "of", "a", "named", "gauge", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/stats/counters.go#L337-L340
train
vitessio/vitess
go/stats/counters.go
Add
func (g *GaugesWithSingleLabel) Add(name string, value int64) { a := g.getValueAddr(name) atomic.AddInt64(a, value) }
go
func (g *GaugesWithSingleLabel) Add(name string, value int64) { a := g.getValueAddr(name) atomic.AddInt64(a, value) }
[ "func", "(", "g", "*", "GaugesWithSingleLabel", ")", "Add", "(", "name", "string", ",", "value", "int64", ")", "{", "a", ":=", "g", ".", "getValueAddr", "(", "name", ")", "\n", "atomic", ".", "AddInt64", "(", "a", ",", "value", ")", "\n", "}" ]
// Add adds a value to a named gauge.
[ "Add", "adds", "a", "value", "to", "a", "named", "gauge", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/stats/counters.go#L343-L346
train
vitessio/vitess
go/stats/counters.go
NewGaugesWithMultiLabels
func NewGaugesWithMultiLabels(name, help string, labels []string) *GaugesWithMultiLabels { t := &GaugesWithMultiLabels{ CountersWithMultiLabels: CountersWithMultiLabels{ counters: counters{ counts: make(map[string]*int64), help: help, }, labels: labels, }} if name != "" { publish(name, t) } return t }
go
func NewGaugesWithMultiLabels(name, help string, labels []string) *GaugesWithMultiLabels { t := &GaugesWithMultiLabels{ CountersWithMultiLabels: CountersWithMultiLabels{ counters: counters{ counts: make(map[string]*int64), help: help, }, labels: labels, }} if name != "" { publish(name, t) } return t }
[ "func", "NewGaugesWithMultiLabels", "(", "name", ",", "help", "string", ",", "labels", "[", "]", "string", ")", "*", "GaugesWithMultiLabels", "{", "t", ":=", "&", "GaugesWithMultiLabels", "{", "CountersWithMultiLabels", ":", "CountersWithMultiLabels", "{", "counters", ":", "counters", "{", "counts", ":", "make", "(", "map", "[", "string", "]", "*", "int64", ")", ",", "help", ":", "help", ",", "}", ",", "labels", ":", "labels", ",", "}", "}", "\n", "if", "name", "!=", "\"", "\"", "{", "publish", "(", "name", ",", "t", ")", "\n", "}", "\n\n", "return", "t", "\n", "}" ]
// NewGaugesWithMultiLabels creates a new GaugesWithMultiLabels instance, // and publishes it if name is set.
[ "NewGaugesWithMultiLabels", "creates", "a", "new", "GaugesWithMultiLabels", "instance", "and", "publishes", "it", "if", "name", "is", "set", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/stats/counters.go#L356-L370
train
vitessio/vitess
go/stats/counters.go
NewGaugesFuncWithMultiLabels
func NewGaugesFuncWithMultiLabels(name, help string, labels []string, f func() map[string]int64) *GaugesFuncWithMultiLabels { t := &GaugesFuncWithMultiLabels{ CountersFuncWithMultiLabels: CountersFuncWithMultiLabels{ f: f, help: help, labels: labels, }} if name != "" { publish(name, t) } return t }
go
func NewGaugesFuncWithMultiLabels(name, help string, labels []string, f func() map[string]int64) *GaugesFuncWithMultiLabels { t := &GaugesFuncWithMultiLabels{ CountersFuncWithMultiLabels: CountersFuncWithMultiLabels{ f: f, help: help, labels: labels, }} if name != "" { publish(name, t) } return t }
[ "func", "NewGaugesFuncWithMultiLabels", "(", "name", ",", "help", "string", ",", "labels", "[", "]", "string", ",", "f", "func", "(", ")", "map", "[", "string", "]", "int64", ")", "*", "GaugesFuncWithMultiLabels", "{", "t", ":=", "&", "GaugesFuncWithMultiLabels", "{", "CountersFuncWithMultiLabels", ":", "CountersFuncWithMultiLabels", "{", "f", ":", "f", ",", "help", ":", "help", ",", "labels", ":", "labels", ",", "}", "}", "\n\n", "if", "name", "!=", "\"", "\"", "{", "publish", "(", "name", ",", "t", ")", "\n", "}", "\n\n", "return", "t", "\n", "}" ]
// NewGaugesFuncWithMultiLabels creates a new GaugesFuncWithMultiLabels // mapping to the provided function.
[ "NewGaugesFuncWithMultiLabels", "creates", "a", "new", "GaugesFuncWithMultiLabels", "mapping", "to", "the", "provided", "function", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/stats/counters.go#L401-L414
train
vitessio/vitess
go/vt/topotools/utils.go
FindTabletByHostAndPort
func FindTabletByHostAndPort(tabletMap map[string]*topo.TabletInfo, addr, portName string, port int32) (*topodatapb.TabletAlias, error) { for _, ti := range tabletMap { if ti.Hostname == addr && ti.PortMap[portName] == port { return ti.Alias, nil } } return nil, topo.NewError(topo.NoNode, addr+":"+portName) }
go
func FindTabletByHostAndPort(tabletMap map[string]*topo.TabletInfo, addr, portName string, port int32) (*topodatapb.TabletAlias, error) { for _, ti := range tabletMap { if ti.Hostname == addr && ti.PortMap[portName] == port { return ti.Alias, nil } } return nil, topo.NewError(topo.NoNode, addr+":"+portName) }
[ "func", "FindTabletByHostAndPort", "(", "tabletMap", "map", "[", "string", "]", "*", "topo", ".", "TabletInfo", ",", "addr", ",", "portName", "string", ",", "port", "int32", ")", "(", "*", "topodatapb", ".", "TabletAlias", ",", "error", ")", "{", "for", "_", ",", "ti", ":=", "range", "tabletMap", "{", "if", "ti", ".", "Hostname", "==", "addr", "&&", "ti", ".", "PortMap", "[", "portName", "]", "==", "port", "{", "return", "ti", ".", "Alias", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "topo", ".", "NewError", "(", "topo", ".", "NoNode", ",", "addr", "+", "\"", "\"", "+", "portName", ")", "\n", "}" ]
// FindTabletByHostAndPort searches within a tablet map for tablets.
[ "FindTabletByHostAndPort", "searches", "within", "a", "tablet", "map", "for", "tablets", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topotools/utils.go#L34-L41
train
vitessio/vitess
go/vt/topotools/utils.go
GetAllTablets
func GetAllTablets(ctx context.Context, ts *topo.Server, cell string) ([]*topo.TabletInfo, error) { aliases, err := ts.GetTabletsByCell(ctx, cell) if err != nil { return nil, err } sort.Sort(topoproto.TabletAliasList(aliases)) tabletMap, err := ts.GetTabletMap(ctx, aliases) if err != nil { // we got another error than topo.ErrNoNode return nil, err } tablets := make([]*topo.TabletInfo, 0, len(aliases)) for _, tabletAlias := range aliases { tabletInfo, ok := tabletMap[topoproto.TabletAliasString(tabletAlias)] if !ok { // tablet disappeared on us (GetTabletMap ignores // topo.ErrNoNode), just echo a warning log.Warningf("failed to load tablet %v", tabletAlias) } else { tablets = append(tablets, tabletInfo) } } return tablets, nil }
go
func GetAllTablets(ctx context.Context, ts *topo.Server, cell string) ([]*topo.TabletInfo, error) { aliases, err := ts.GetTabletsByCell(ctx, cell) if err != nil { return nil, err } sort.Sort(topoproto.TabletAliasList(aliases)) tabletMap, err := ts.GetTabletMap(ctx, aliases) if err != nil { // we got another error than topo.ErrNoNode return nil, err } tablets := make([]*topo.TabletInfo, 0, len(aliases)) for _, tabletAlias := range aliases { tabletInfo, ok := tabletMap[topoproto.TabletAliasString(tabletAlias)] if !ok { // tablet disappeared on us (GetTabletMap ignores // topo.ErrNoNode), just echo a warning log.Warningf("failed to load tablet %v", tabletAlias) } else { tablets = append(tablets, tabletInfo) } } return tablets, nil }
[ "func", "GetAllTablets", "(", "ctx", "context", ".", "Context", ",", "ts", "*", "topo", ".", "Server", ",", "cell", "string", ")", "(", "[", "]", "*", "topo", ".", "TabletInfo", ",", "error", ")", "{", "aliases", ",", "err", ":=", "ts", ".", "GetTabletsByCell", "(", "ctx", ",", "cell", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "sort", ".", "Sort", "(", "topoproto", ".", "TabletAliasList", "(", "aliases", ")", ")", "\n\n", "tabletMap", ",", "err", ":=", "ts", ".", "GetTabletMap", "(", "ctx", ",", "aliases", ")", "\n", "if", "err", "!=", "nil", "{", "// we got another error than topo.ErrNoNode", "return", "nil", ",", "err", "\n", "}", "\n", "tablets", ":=", "make", "(", "[", "]", "*", "topo", ".", "TabletInfo", ",", "0", ",", "len", "(", "aliases", ")", ")", "\n", "for", "_", ",", "tabletAlias", ":=", "range", "aliases", "{", "tabletInfo", ",", "ok", ":=", "tabletMap", "[", "topoproto", ".", "TabletAliasString", "(", "tabletAlias", ")", "]", "\n", "if", "!", "ok", "{", "// tablet disappeared on us (GetTabletMap ignores", "// topo.ErrNoNode), just echo a warning", "log", ".", "Warningf", "(", "\"", "\"", ",", "tabletAlias", ")", "\n", "}", "else", "{", "tablets", "=", "append", "(", "tablets", ",", "tabletInfo", ")", "\n", "}", "\n", "}", "\n\n", "return", "tablets", ",", "nil", "\n", "}" ]
// GetAllTablets returns a sorted list of tablets.
[ "GetAllTablets", "returns", "a", "sorted", "list", "of", "tablets", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topotools/utils.go#L44-L69
train
vitessio/vitess
go/vt/topotools/utils.go
GetAllTabletsAcrossCells
func GetAllTabletsAcrossCells(ctx context.Context, ts *topo.Server) ([]*topo.TabletInfo, error) { cells, err := ts.GetKnownCells(ctx) if err != nil { return nil, err } results := make([][]*topo.TabletInfo, len(cells)) errors := make([]error, len(cells)) wg := sync.WaitGroup{} wg.Add(len(cells)) for i, cell := range cells { go func(i int, cell string) { results[i], errors[i] = GetAllTablets(ctx, ts, cell) wg.Done() }(i, cell) } wg.Wait() err = nil var allTablets []*topo.TabletInfo for i := range cells { if errors[i] == nil { allTablets = append(allTablets, results[i]...) } else { err = topo.NewError(topo.PartialResult, "") } } return allTablets, err }
go
func GetAllTabletsAcrossCells(ctx context.Context, ts *topo.Server) ([]*topo.TabletInfo, error) { cells, err := ts.GetKnownCells(ctx) if err != nil { return nil, err } results := make([][]*topo.TabletInfo, len(cells)) errors := make([]error, len(cells)) wg := sync.WaitGroup{} wg.Add(len(cells)) for i, cell := range cells { go func(i int, cell string) { results[i], errors[i] = GetAllTablets(ctx, ts, cell) wg.Done() }(i, cell) } wg.Wait() err = nil var allTablets []*topo.TabletInfo for i := range cells { if errors[i] == nil { allTablets = append(allTablets, results[i]...) } else { err = topo.NewError(topo.PartialResult, "") } } return allTablets, err }
[ "func", "GetAllTabletsAcrossCells", "(", "ctx", "context", ".", "Context", ",", "ts", "*", "topo", ".", "Server", ")", "(", "[", "]", "*", "topo", ".", "TabletInfo", ",", "error", ")", "{", "cells", ",", "err", ":=", "ts", ".", "GetKnownCells", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "results", ":=", "make", "(", "[", "]", "[", "]", "*", "topo", ".", "TabletInfo", ",", "len", "(", "cells", ")", ")", "\n", "errors", ":=", "make", "(", "[", "]", "error", ",", "len", "(", "cells", ")", ")", "\n", "wg", ":=", "sync", ".", "WaitGroup", "{", "}", "\n", "wg", ".", "Add", "(", "len", "(", "cells", ")", ")", "\n", "for", "i", ",", "cell", ":=", "range", "cells", "{", "go", "func", "(", "i", "int", ",", "cell", "string", ")", "{", "results", "[", "i", "]", ",", "errors", "[", "i", "]", "=", "GetAllTablets", "(", "ctx", ",", "ts", ",", "cell", ")", "\n", "wg", ".", "Done", "(", ")", "\n", "}", "(", "i", ",", "cell", ")", "\n", "}", "\n", "wg", ".", "Wait", "(", ")", "\n\n", "err", "=", "nil", "\n", "var", "allTablets", "[", "]", "*", "topo", ".", "TabletInfo", "\n", "for", "i", ":=", "range", "cells", "{", "if", "errors", "[", "i", "]", "==", "nil", "{", "allTablets", "=", "append", "(", "allTablets", ",", "results", "[", "i", "]", "...", ")", "\n", "}", "else", "{", "err", "=", "topo", ".", "NewError", "(", "topo", ".", "PartialResult", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "allTablets", ",", "err", "\n", "}" ]
// GetAllTabletsAcrossCells returns all tablets from known cells. // If it returns topo.ErrPartialResult, then the list is valid, but partial.
[ "GetAllTabletsAcrossCells", "returns", "all", "tablets", "from", "known", "cells", ".", "If", "it", "returns", "topo", ".", "ErrPartialResult", "then", "the", "list", "is", "valid", "but", "partial", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topotools/utils.go#L73-L101
train
vitessio/vitess
go/vt/topotools/utils.go
CopyMapKeys
func CopyMapKeys(m interface{}, typeHint interface{}) interface{} { mapVal := reflect.ValueOf(m) keys := reflect.MakeSlice(reflect.TypeOf(typeHint), 0, mapVal.Len()) for _, k := range mapVal.MapKeys() { keys = reflect.Append(keys, k) } return keys.Interface() }
go
func CopyMapKeys(m interface{}, typeHint interface{}) interface{} { mapVal := reflect.ValueOf(m) keys := reflect.MakeSlice(reflect.TypeOf(typeHint), 0, mapVal.Len()) for _, k := range mapVal.MapKeys() { keys = reflect.Append(keys, k) } return keys.Interface() }
[ "func", "CopyMapKeys", "(", "m", "interface", "{", "}", ",", "typeHint", "interface", "{", "}", ")", "interface", "{", "}", "{", "mapVal", ":=", "reflect", ".", "ValueOf", "(", "m", ")", "\n", "keys", ":=", "reflect", ".", "MakeSlice", "(", "reflect", ".", "TypeOf", "(", "typeHint", ")", ",", "0", ",", "mapVal", ".", "Len", "(", ")", ")", "\n", "for", "_", ",", "k", ":=", "range", "mapVal", ".", "MapKeys", "(", ")", "{", "keys", "=", "reflect", ".", "Append", "(", "keys", ",", "k", ")", "\n", "}", "\n", "return", "keys", ".", "Interface", "(", ")", "\n", "}" ]
// CopyMapKeys copies keys from from map m into a new slice with the // type specified by typeHint. Reflection can't make a new slice type // just based on the key type AFAICT.
[ "CopyMapKeys", "copies", "keys", "from", "from", "map", "m", "into", "a", "new", "slice", "with", "the", "type", "specified", "by", "typeHint", ".", "Reflection", "can", "t", "make", "a", "new", "slice", "type", "just", "based", "on", "the", "key", "type", "AFAICT", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topotools/utils.go#L125-L132
train
vitessio/vitess
go/vt/topotools/utils.go
CopyMapValues
func CopyMapValues(m interface{}, typeHint interface{}) interface{} { mapVal := reflect.ValueOf(m) vals := reflect.MakeSlice(reflect.TypeOf(typeHint), 0, mapVal.Len()) for _, k := range mapVal.MapKeys() { vals = reflect.Append(vals, mapVal.MapIndex(k)) } return vals.Interface() }
go
func CopyMapValues(m interface{}, typeHint interface{}) interface{} { mapVal := reflect.ValueOf(m) vals := reflect.MakeSlice(reflect.TypeOf(typeHint), 0, mapVal.Len()) for _, k := range mapVal.MapKeys() { vals = reflect.Append(vals, mapVal.MapIndex(k)) } return vals.Interface() }
[ "func", "CopyMapValues", "(", "m", "interface", "{", "}", ",", "typeHint", "interface", "{", "}", ")", "interface", "{", "}", "{", "mapVal", ":=", "reflect", ".", "ValueOf", "(", "m", ")", "\n", "vals", ":=", "reflect", ".", "MakeSlice", "(", "reflect", ".", "TypeOf", "(", "typeHint", ")", ",", "0", ",", "mapVal", ".", "Len", "(", ")", ")", "\n", "for", "_", ",", "k", ":=", "range", "mapVal", ".", "MapKeys", "(", ")", "{", "vals", "=", "reflect", ".", "Append", "(", "vals", ",", "mapVal", ".", "MapIndex", "(", "k", ")", ")", "\n", "}", "\n", "return", "vals", ".", "Interface", "(", ")", "\n", "}" ]
// CopyMapValues copies values from from map m into a new slice with the // type specified by typeHint. Reflection can't make a new slice type // just based on the key type AFAICT.
[ "CopyMapValues", "copies", "values", "from", "from", "map", "m", "into", "a", "new", "slice", "with", "the", "type", "specified", "by", "typeHint", ".", "Reflection", "can", "t", "make", "a", "new", "slice", "type", "just", "based", "on", "the", "key", "type", "AFAICT", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topotools/utils.go#L137-L144
train
vitessio/vitess
go/vt/topotools/utils.go
MapKeys
func MapKeys(m interface{}) []interface{} { keys := make([]interface{}, 0, 16) mapVal := reflect.ValueOf(m) for _, kv := range mapVal.MapKeys() { keys = append(keys, kv.Interface()) } return keys }
go
func MapKeys(m interface{}) []interface{} { keys := make([]interface{}, 0, 16) mapVal := reflect.ValueOf(m) for _, kv := range mapVal.MapKeys() { keys = append(keys, kv.Interface()) } return keys }
[ "func", "MapKeys", "(", "m", "interface", "{", "}", ")", "[", "]", "interface", "{", "}", "{", "keys", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "0", ",", "16", ")", "\n", "mapVal", ":=", "reflect", ".", "ValueOf", "(", "m", ")", "\n", "for", "_", ",", "kv", ":=", "range", "mapVal", ".", "MapKeys", "(", ")", "{", "keys", "=", "append", "(", "keys", ",", "kv", ".", "Interface", "(", ")", ")", "\n", "}", "\n", "return", "keys", "\n", "}" ]
// MapKeys returns an array with th provided map keys.
[ "MapKeys", "returns", "an", "array", "with", "th", "provided", "map", "keys", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topotools/utils.go#L147-L154
train
vitessio/vitess
go/vt/vttablet/tabletmanager/vreplication/engine.go
NewEngine
func NewEngine(ts *topo.Server, cell string, mysqld mysqlctl.MysqlDaemon, dbClientFactory func() binlogplayer.DBClient, dbName string) *Engine { vre := &Engine{ controllers: make(map[int]*controller), ts: ts, cell: cell, mysqld: mysqld, dbClientFactory: dbClientFactory, dbName: dbName, } return vre }
go
func NewEngine(ts *topo.Server, cell string, mysqld mysqlctl.MysqlDaemon, dbClientFactory func() binlogplayer.DBClient, dbName string) *Engine { vre := &Engine{ controllers: make(map[int]*controller), ts: ts, cell: cell, mysqld: mysqld, dbClientFactory: dbClientFactory, dbName: dbName, } return vre }
[ "func", "NewEngine", "(", "ts", "*", "topo", ".", "Server", ",", "cell", "string", ",", "mysqld", "mysqlctl", ".", "MysqlDaemon", ",", "dbClientFactory", "func", "(", ")", "binlogplayer", ".", "DBClient", ",", "dbName", "string", ")", "*", "Engine", "{", "vre", ":=", "&", "Engine", "{", "controllers", ":", "make", "(", "map", "[", "int", "]", "*", "controller", ")", ",", "ts", ":", "ts", ",", "cell", ":", "cell", ",", "mysqld", ":", "mysqld", ",", "dbClientFactory", ":", "dbClientFactory", ",", "dbName", ":", "dbName", ",", "}", "\n", "return", "vre", "\n", "}" ]
// NewEngine creates a new Engine. // A nil ts means that the Engine is disabled.
[ "NewEngine", "creates", "a", "new", "Engine", ".", "A", "nil", "ts", "means", "that", "the", "Engine", "is", "disabled", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/vreplication/engine.go#L69-L79
train
vitessio/vitess
go/vt/vttablet/tabletmanager/vreplication/engine.go
executeFetchMaybeCreateTable
func (vre *Engine) executeFetchMaybeCreateTable(dbClient binlogplayer.DBClient, query string, maxrows int) (qr *sqltypes.Result, err error) { qr, err = dbClient.ExecuteFetch(query, maxrows) if err == nil { return } // If it's a bad table or db, it could be because _vt.vreplication wasn't created. // In that case we can try creating it again. merr, isSQLErr := err.(*mysql.SQLError) if !isSQLErr || !(merr.Num == mysql.ERNoSuchTable || merr.Num == mysql.ERBadDb || merr.Num == mysql.ERBadFieldError) { return qr, err } log.Info("Looks like _vt.vreplication table may not exist. Trying to recreate... ") if merr.Num == mysql.ERNoSuchTable || merr.Num == mysql.ERBadDb { for _, query := range binlogplayer.CreateVReplicationTable() { if _, merr := dbClient.ExecuteFetch(query, 0); merr != nil { log.Warningf("Failed to ensure _vt.vreplication table exists: %v", merr) return nil, err } } } if merr.Num == mysql.ERBadFieldError { log.Info("Adding column to table _vt.vreplication") for _, query := range binlogplayer.AlterVReplicationTable() { if _, merr := dbClient.ExecuteFetch(query, 0); merr != nil { merr, isSQLErr := err.(*mysql.SQLError) if !isSQLErr || !(merr.Num == mysql.ERDupFieldName) { log.Warningf("Failed to alter _vt.vreplication table: %v", merr) return nil, err } } } } return dbClient.ExecuteFetch(query, maxrows) }
go
func (vre *Engine) executeFetchMaybeCreateTable(dbClient binlogplayer.DBClient, query string, maxrows int) (qr *sqltypes.Result, err error) { qr, err = dbClient.ExecuteFetch(query, maxrows) if err == nil { return } // If it's a bad table or db, it could be because _vt.vreplication wasn't created. // In that case we can try creating it again. merr, isSQLErr := err.(*mysql.SQLError) if !isSQLErr || !(merr.Num == mysql.ERNoSuchTable || merr.Num == mysql.ERBadDb || merr.Num == mysql.ERBadFieldError) { return qr, err } log.Info("Looks like _vt.vreplication table may not exist. Trying to recreate... ") if merr.Num == mysql.ERNoSuchTable || merr.Num == mysql.ERBadDb { for _, query := range binlogplayer.CreateVReplicationTable() { if _, merr := dbClient.ExecuteFetch(query, 0); merr != nil { log.Warningf("Failed to ensure _vt.vreplication table exists: %v", merr) return nil, err } } } if merr.Num == mysql.ERBadFieldError { log.Info("Adding column to table _vt.vreplication") for _, query := range binlogplayer.AlterVReplicationTable() { if _, merr := dbClient.ExecuteFetch(query, 0); merr != nil { merr, isSQLErr := err.(*mysql.SQLError) if !isSQLErr || !(merr.Num == mysql.ERDupFieldName) { log.Warningf("Failed to alter _vt.vreplication table: %v", merr) return nil, err } } } } return dbClient.ExecuteFetch(query, maxrows) }
[ "func", "(", "vre", "*", "Engine", ")", "executeFetchMaybeCreateTable", "(", "dbClient", "binlogplayer", ".", "DBClient", ",", "query", "string", ",", "maxrows", "int", ")", "(", "qr", "*", "sqltypes", ".", "Result", ",", "err", "error", ")", "{", "qr", ",", "err", "=", "dbClient", ".", "ExecuteFetch", "(", "query", ",", "maxrows", ")", "\n\n", "if", "err", "==", "nil", "{", "return", "\n", "}", "\n\n", "// If it's a bad table or db, it could be because _vt.vreplication wasn't created.", "// In that case we can try creating it again.", "merr", ",", "isSQLErr", ":=", "err", ".", "(", "*", "mysql", ".", "SQLError", ")", "\n", "if", "!", "isSQLErr", "||", "!", "(", "merr", ".", "Num", "==", "mysql", ".", "ERNoSuchTable", "||", "merr", ".", "Num", "==", "mysql", ".", "ERBadDb", "||", "merr", ".", "Num", "==", "mysql", ".", "ERBadFieldError", ")", "{", "return", "qr", ",", "err", "\n", "}", "\n\n", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "if", "merr", ".", "Num", "==", "mysql", ".", "ERNoSuchTable", "||", "merr", ".", "Num", "==", "mysql", ".", "ERBadDb", "{", "for", "_", ",", "query", ":=", "range", "binlogplayer", ".", "CreateVReplicationTable", "(", ")", "{", "if", "_", ",", "merr", ":=", "dbClient", ".", "ExecuteFetch", "(", "query", ",", "0", ")", ";", "merr", "!=", "nil", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "merr", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "merr", ".", "Num", "==", "mysql", ".", "ERBadFieldError", "{", "log", ".", "Info", "(", "\"", "\"", ")", "\n", "for", "_", ",", "query", ":=", "range", "binlogplayer", ".", "AlterVReplicationTable", "(", ")", "{", "if", "_", ",", "merr", ":=", "dbClient", ".", "ExecuteFetch", "(", "query", ",", "0", ")", ";", "merr", "!=", "nil", "{", "merr", ",", "isSQLErr", ":=", "err", ".", "(", "*", "mysql", ".", "SQLError", ")", "\n", "if", "!", "isSQLErr", "||", "!", "(", "merr", ".", "Num", "==", "mysql", ".", "ERDupFieldName", ")", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "merr", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "dbClient", ".", "ExecuteFetch", "(", "query", ",", "maxrows", ")", "\n", "}" ]
// executeFetchMaybeCreateTable calls DBClient.ExecuteFetch and does one retry if // there's a failure due to mysql.ERNoSuchTable or mysql.ERBadDb which can be fixed // by re-creating the _vt.vreplication table.
[ "executeFetchMaybeCreateTable", "calls", "DBClient", ".", "ExecuteFetch", "and", "does", "one", "retry", "if", "there", "s", "a", "failure", "due", "to", "mysql", ".", "ERNoSuchTable", "or", "mysql", ".", "ERBadDb", "which", "can", "be", "fixed", "by", "re", "-", "creating", "the", "_vt", ".", "vreplication", "table", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/vreplication/engine.go#L106-L142
train
vitessio/vitess
go/vt/vttablet/tabletmanager/vreplication/engine.go
IsOpen
func (vre *Engine) IsOpen() bool { vre.mu.Lock() defer vre.mu.Unlock() return vre.isOpen }
go
func (vre *Engine) IsOpen() bool { vre.mu.Lock() defer vre.mu.Unlock() return vre.isOpen }
[ "func", "(", "vre", "*", "Engine", ")", "IsOpen", "(", ")", "bool", "{", "vre", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "vre", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "vre", ".", "isOpen", "\n", "}" ]
// IsOpen returns true if Engine is open.
[ "IsOpen", "returns", "true", "if", "Engine", "is", "open", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/vreplication/engine.go#L176-L180
train
vitessio/vitess
go/vt/vttablet/tabletmanager/vreplication/engine.go
WaitForPos
func (vre *Engine) WaitForPos(ctx context.Context, id int, pos string) error { mPos, err := mysql.DecodePosition(pos) if err != nil { return err } if err := func() error { vre.mu.Lock() defer vre.mu.Unlock() if !vre.isOpen { return errors.New("vreplication engine is closed") } // Ensure that the engine won't be closed while this is running. vre.wg.Add(1) return nil }(); err != nil { return err } defer vre.wg.Done() dbClient := vre.dbClientFactory() if err := dbClient.Connect(); err != nil { return err } defer dbClient.Close() for { qr, err := dbClient.ExecuteFetch(binlogplayer.ReadVReplicationStatus(uint32(id)), 10) switch { case err != nil: return err case len(qr.Rows) == 0: return fmt.Errorf("vreplication stream %d not found", id) case len(qr.Rows) > 1 || len(qr.Rows[0]) != 3: return fmt.Errorf("unexpected result: %v", qr) } current, err := mysql.DecodePosition(qr.Rows[0][0].ToString()) if err != nil { return err } if current.AtLeast(mPos) { return nil } if qr.Rows[0][1].ToString() == binlogplayer.BlpStopped { return fmt.Errorf("replication has stopped at %v before reaching position %v, message: %s", current, mPos, qr.Rows[0][2].ToString()) } select { case <-ctx.Done(): return ctx.Err() case <-vre.ctx.Done(): return fmt.Errorf("vreplication is closing: %v", vre.ctx.Err()) case <-time.After(waitRetryTime): } } }
go
func (vre *Engine) WaitForPos(ctx context.Context, id int, pos string) error { mPos, err := mysql.DecodePosition(pos) if err != nil { return err } if err := func() error { vre.mu.Lock() defer vre.mu.Unlock() if !vre.isOpen { return errors.New("vreplication engine is closed") } // Ensure that the engine won't be closed while this is running. vre.wg.Add(1) return nil }(); err != nil { return err } defer vre.wg.Done() dbClient := vre.dbClientFactory() if err := dbClient.Connect(); err != nil { return err } defer dbClient.Close() for { qr, err := dbClient.ExecuteFetch(binlogplayer.ReadVReplicationStatus(uint32(id)), 10) switch { case err != nil: return err case len(qr.Rows) == 0: return fmt.Errorf("vreplication stream %d not found", id) case len(qr.Rows) > 1 || len(qr.Rows[0]) != 3: return fmt.Errorf("unexpected result: %v", qr) } current, err := mysql.DecodePosition(qr.Rows[0][0].ToString()) if err != nil { return err } if current.AtLeast(mPos) { return nil } if qr.Rows[0][1].ToString() == binlogplayer.BlpStopped { return fmt.Errorf("replication has stopped at %v before reaching position %v, message: %s", current, mPos, qr.Rows[0][2].ToString()) } select { case <-ctx.Done(): return ctx.Err() case <-vre.ctx.Done(): return fmt.Errorf("vreplication is closing: %v", vre.ctx.Err()) case <-time.After(waitRetryTime): } } }
[ "func", "(", "vre", "*", "Engine", ")", "WaitForPos", "(", "ctx", "context", ".", "Context", ",", "id", "int", ",", "pos", "string", ")", "error", "{", "mPos", ",", "err", ":=", "mysql", ".", "DecodePosition", "(", "pos", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "func", "(", ")", "error", "{", "vre", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "vre", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "!", "vre", ".", "isOpen", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Ensure that the engine won't be closed while this is running.", "vre", ".", "wg", ".", "Add", "(", "1", ")", "\n", "return", "nil", "\n", "}", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "vre", ".", "wg", ".", "Done", "(", ")", "\n\n", "dbClient", ":=", "vre", ".", "dbClientFactory", "(", ")", "\n", "if", "err", ":=", "dbClient", ".", "Connect", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "dbClient", ".", "Close", "(", ")", "\n\n", "for", "{", "qr", ",", "err", ":=", "dbClient", ".", "ExecuteFetch", "(", "binlogplayer", ".", "ReadVReplicationStatus", "(", "uint32", "(", "id", ")", ")", ",", "10", ")", "\n", "switch", "{", "case", "err", "!=", "nil", ":", "return", "err", "\n", "case", "len", "(", "qr", ".", "Rows", ")", "==", "0", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "id", ")", "\n", "case", "len", "(", "qr", ".", "Rows", ")", ">", "1", "||", "len", "(", "qr", ".", "Rows", "[", "0", "]", ")", "!=", "3", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "qr", ")", "\n", "}", "\n", "current", ",", "err", ":=", "mysql", ".", "DecodePosition", "(", "qr", ".", "Rows", "[", "0", "]", "[", "0", "]", ".", "ToString", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "current", ".", "AtLeast", "(", "mPos", ")", "{", "return", "nil", "\n", "}", "\n\n", "if", "qr", ".", "Rows", "[", "0", "]", "[", "1", "]", ".", "ToString", "(", ")", "==", "binlogplayer", ".", "BlpStopped", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "current", ",", "mPos", ",", "qr", ".", "Rows", "[", "0", "]", "[", "2", "]", ".", "ToString", "(", ")", ")", "\n", "}", "\n\n", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "case", "<-", "vre", ".", "ctx", ".", "Done", "(", ")", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "vre", ".", "ctx", ".", "Err", "(", ")", ")", "\n", "case", "<-", "time", ".", "After", "(", "waitRetryTime", ")", ":", "}", "\n", "}", "\n", "}" ]
// WaitForPos waits for the replication to reach the specified position.
[ "WaitForPos", "waits", "for", "the", "replication", "to", "reach", "the", "specified", "position", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/vreplication/engine.go#L298-L356
train
vitessio/vitess
go/vt/vttablet/tabletmanager/vreplication/engine.go
updateStats
func (vre *Engine) updateStats() { globalStats.mu.Lock() defer globalStats.mu.Unlock() globalStats.isOpen = vre.isOpen globalStats.controllers = make(map[int]*controller, len(vre.controllers)) for id, ct := range vre.controllers { globalStats.controllers[id] = ct } }
go
func (vre *Engine) updateStats() { globalStats.mu.Lock() defer globalStats.mu.Unlock() globalStats.isOpen = vre.isOpen globalStats.controllers = make(map[int]*controller, len(vre.controllers)) for id, ct := range vre.controllers { globalStats.controllers[id] = ct } }
[ "func", "(", "vre", "*", "Engine", ")", "updateStats", "(", ")", "{", "globalStats", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "globalStats", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "globalStats", ".", "isOpen", "=", "vre", ".", "isOpen", "\n", "globalStats", ".", "controllers", "=", "make", "(", "map", "[", "int", "]", "*", "controller", ",", "len", "(", "vre", ".", "controllers", ")", ")", "\n", "for", "id", ",", "ct", ":=", "range", "vre", ".", "controllers", "{", "globalStats", ".", "controllers", "[", "id", "]", "=", "ct", "\n", "}", "\n", "}" ]
// UpdateStats must be called with lock held.
[ "UpdateStats", "must", "be", "called", "with", "lock", "held", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/vreplication/engine.go#L359-L368
train
vitessio/vitess
go/vt/vttablet/tabletmanager/vreplication/engine.go
rowToMap
func rowToMap(qr *sqltypes.Result, rownum int) (map[string]string, error) { row := qr.Rows[rownum] m := make(map[string]string, len(row)) for i, fld := range qr.Fields { if row[i].IsNull() { continue } m[fld.Name] = row[i].ToString() } return m, nil }
go
func rowToMap(qr *sqltypes.Result, rownum int) (map[string]string, error) { row := qr.Rows[rownum] m := make(map[string]string, len(row)) for i, fld := range qr.Fields { if row[i].IsNull() { continue } m[fld.Name] = row[i].ToString() } return m, nil }
[ "func", "rowToMap", "(", "qr", "*", "sqltypes", ".", "Result", ",", "rownum", "int", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "row", ":=", "qr", ".", "Rows", "[", "rownum", "]", "\n", "m", ":=", "make", "(", "map", "[", "string", "]", "string", ",", "len", "(", "row", ")", ")", "\n", "for", "i", ",", "fld", ":=", "range", "qr", ".", "Fields", "{", "if", "row", "[", "i", "]", ".", "IsNull", "(", ")", "{", "continue", "\n", "}", "\n", "m", "[", "fld", ".", "Name", "]", "=", "row", "[", "i", "]", ".", "ToString", "(", ")", "\n", "}", "\n", "return", "m", ",", "nil", "\n", "}" ]
// rowToMap converts a row into a map for easier processing.
[ "rowToMap", "converts", "a", "row", "into", "a", "map", "for", "easier", "processing", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/vreplication/engine.go#L401-L411
train
vitessio/vitess
go/vt/vtgate/engine/insert.go
NewQueryInsert
func NewQueryInsert(opcode InsertOpcode, keyspace *vindexes.Keyspace, query string) *Insert { return &Insert{ Opcode: opcode, Keyspace: keyspace, Query: query, } }
go
func NewQueryInsert(opcode InsertOpcode, keyspace *vindexes.Keyspace, query string) *Insert { return &Insert{ Opcode: opcode, Keyspace: keyspace, Query: query, } }
[ "func", "NewQueryInsert", "(", "opcode", "InsertOpcode", ",", "keyspace", "*", "vindexes", ".", "Keyspace", ",", "query", "string", ")", "*", "Insert", "{", "return", "&", "Insert", "{", "Opcode", ":", "opcode", ",", "Keyspace", ":", "keyspace", ",", "Query", ":", "query", ",", "}", "\n", "}" ]
// NewQueryInsert creates an Insert with a query string.
[ "NewQueryInsert", "creates", "an", "Insert", "with", "a", "query", "string", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/engine/insert.go#L86-L92
train
vitessio/vitess
go/vt/vtgate/engine/insert.go
NewSimpleInsert
func NewSimpleInsert(opcode InsertOpcode, table *vindexes.Table, keyspace *vindexes.Keyspace) *Insert { return &Insert{ Opcode: opcode, Table: table, Keyspace: keyspace, } }
go
func NewSimpleInsert(opcode InsertOpcode, table *vindexes.Table, keyspace *vindexes.Keyspace) *Insert { return &Insert{ Opcode: opcode, Table: table, Keyspace: keyspace, } }
[ "func", "NewSimpleInsert", "(", "opcode", "InsertOpcode", ",", "table", "*", "vindexes", ".", "Table", ",", "keyspace", "*", "vindexes", ".", "Keyspace", ")", "*", "Insert", "{", "return", "&", "Insert", "{", "Opcode", ":", "opcode", ",", "Table", ":", "table", ",", "Keyspace", ":", "keyspace", ",", "}", "\n", "}" ]
// NewSimpleInsert creates an Insert for a Table.
[ "NewSimpleInsert", "creates", "an", "Insert", "for", "a", "Table", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/engine/insert.go#L95-L101
train
vitessio/vitess
go/vt/vtgate/engine/insert.go
NewInsert
func NewInsert(opcode InsertOpcode, keyspace *vindexes.Keyspace, vindexValues []sqltypes.PlanValue, table *vindexes.Table, prefix string, mid []string, suffix string) *Insert { return &Insert{ Opcode: opcode, Keyspace: keyspace, VindexValues: vindexValues, Table: table, Prefix: prefix, Mid: mid, Suffix: suffix, } }
go
func NewInsert(opcode InsertOpcode, keyspace *vindexes.Keyspace, vindexValues []sqltypes.PlanValue, table *vindexes.Table, prefix string, mid []string, suffix string) *Insert { return &Insert{ Opcode: opcode, Keyspace: keyspace, VindexValues: vindexValues, Table: table, Prefix: prefix, Mid: mid, Suffix: suffix, } }
[ "func", "NewInsert", "(", "opcode", "InsertOpcode", ",", "keyspace", "*", "vindexes", ".", "Keyspace", ",", "vindexValues", "[", "]", "sqltypes", ".", "PlanValue", ",", "table", "*", "vindexes", ".", "Table", ",", "prefix", "string", ",", "mid", "[", "]", "string", ",", "suffix", "string", ")", "*", "Insert", "{", "return", "&", "Insert", "{", "Opcode", ":", "opcode", ",", "Keyspace", ":", "keyspace", ",", "VindexValues", ":", "vindexValues", ",", "Table", ":", "table", ",", "Prefix", ":", "prefix", ",", "Mid", ":", "mid", ",", "Suffix", ":", "suffix", ",", "}", "\n", "}" ]
// NewInsert creates a new Insert.
[ "NewInsert", "creates", "a", "new", "Insert", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/engine/insert.go#L104-L114
train
vitessio/vitess
go/vt/vtgate/engine/insert.go
MarshalJSON
func (ins *Insert) MarshalJSON() ([]byte, error) { var tname string if ins.Table != nil { tname = ins.Table.Name.String() } marshalInsert := struct { Opcode InsertOpcode Keyspace *vindexes.Keyspace `json:",omitempty"` Query string `json:",omitempty"` Values []sqltypes.PlanValue `json:",omitempty"` Table string `json:",omitempty"` Generate *Generate `json:",omitempty"` Prefix string `json:",omitempty"` Mid []string `json:",omitempty"` Suffix string `json:",omitempty"` MultiShardAutocommit bool `json:",omitempty"` QueryTimeout int `json:",omitempty"` }{ Opcode: ins.Opcode, Keyspace: ins.Keyspace, Query: ins.Query, Values: ins.VindexValues, Table: tname, Generate: ins.Generate, Prefix: ins.Prefix, Mid: ins.Mid, Suffix: ins.Suffix, MultiShardAutocommit: ins.MultiShardAutocommit, QueryTimeout: ins.QueryTimeout, } return jsonutil.MarshalNoEscape(marshalInsert) }
go
func (ins *Insert) MarshalJSON() ([]byte, error) { var tname string if ins.Table != nil { tname = ins.Table.Name.String() } marshalInsert := struct { Opcode InsertOpcode Keyspace *vindexes.Keyspace `json:",omitempty"` Query string `json:",omitempty"` Values []sqltypes.PlanValue `json:",omitempty"` Table string `json:",omitempty"` Generate *Generate `json:",omitempty"` Prefix string `json:",omitempty"` Mid []string `json:",omitempty"` Suffix string `json:",omitempty"` MultiShardAutocommit bool `json:",omitempty"` QueryTimeout int `json:",omitempty"` }{ Opcode: ins.Opcode, Keyspace: ins.Keyspace, Query: ins.Query, Values: ins.VindexValues, Table: tname, Generate: ins.Generate, Prefix: ins.Prefix, Mid: ins.Mid, Suffix: ins.Suffix, MultiShardAutocommit: ins.MultiShardAutocommit, QueryTimeout: ins.QueryTimeout, } return jsonutil.MarshalNoEscape(marshalInsert) }
[ "func", "(", "ins", "*", "Insert", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "tname", "string", "\n", "if", "ins", ".", "Table", "!=", "nil", "{", "tname", "=", "ins", ".", "Table", ".", "Name", ".", "String", "(", ")", "\n", "}", "\n", "marshalInsert", ":=", "struct", "{", "Opcode", "InsertOpcode", "\n", "Keyspace", "*", "vindexes", ".", "Keyspace", "`json:\",omitempty\"`", "\n", "Query", "string", "`json:\",omitempty\"`", "\n", "Values", "[", "]", "sqltypes", ".", "PlanValue", "`json:\",omitempty\"`", "\n", "Table", "string", "`json:\",omitempty\"`", "\n", "Generate", "*", "Generate", "`json:\",omitempty\"`", "\n", "Prefix", "string", "`json:\",omitempty\"`", "\n", "Mid", "[", "]", "string", "`json:\",omitempty\"`", "\n", "Suffix", "string", "`json:\",omitempty\"`", "\n", "MultiShardAutocommit", "bool", "`json:\",omitempty\"`", "\n", "QueryTimeout", "int", "`json:\",omitempty\"`", "\n", "}", "{", "Opcode", ":", "ins", ".", "Opcode", ",", "Keyspace", ":", "ins", ".", "Keyspace", ",", "Query", ":", "ins", ".", "Query", ",", "Values", ":", "ins", ".", "VindexValues", ",", "Table", ":", "tname", ",", "Generate", ":", "ins", ".", "Generate", ",", "Prefix", ":", "ins", ".", "Prefix", ",", "Mid", ":", "ins", ".", "Mid", ",", "Suffix", ":", "ins", ".", "Suffix", ",", "MultiShardAutocommit", ":", "ins", ".", "MultiShardAutocommit", ",", "QueryTimeout", ":", "ins", ".", "QueryTimeout", ",", "}", "\n", "return", "jsonutil", ".", "MarshalNoEscape", "(", "marshalInsert", ")", "\n", "}" ]
// MarshalJSON serializes the Insert into a JSON representation. // It's used for testing and diagnostics.
[ "MarshalJSON", "serializes", "the", "Insert", "into", "a", "JSON", "representation", ".", "It", "s", "used", "for", "testing", "and", "diagnostics", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/engine/insert.go#L118-L149
train
vitessio/vitess
go/vt/vtgate/engine/insert.go
processGenerate
func (ins *Insert) processGenerate(vcursor VCursor, bindVars map[string]*querypb.BindVariable) (insertID int64, err error) { if ins.Generate == nil { return 0, nil } // Scan input values to compute the number of values to generate, and // keep track of where they should be filled. resolved, err := ins.Generate.Values.ResolveList(bindVars) if err != nil { return 0, vterrors.Wrap(err, "processGenerate") } count := int64(0) for _, val := range resolved { if val.IsNull() { count++ } } // If generation is needed, generate the requested number of values (as one call). if count != 0 { rss, _, err := vcursor.ResolveDestinations(ins.Generate.Keyspace.Name, nil, []key.Destination{key.DestinationAnyShard{}}) if err != nil { return 0, vterrors.Wrap(err, "processGenerate") } if len(rss) != 1 { return 0, vterrors.Wrapf(err, "processGenerate len(rss)=%v", len(rss)) } bindVars := map[string]*querypb.BindVariable{"n": sqltypes.Int64BindVariable(count)} qr, err := vcursor.ExecuteStandalone(ins.Generate.Query, bindVars, rss[0]) if err != nil { return 0, err } // If no rows are returned, it's an internal error, and the code // must panic, which will be caught and reported. insertID, err = sqltypes.ToInt64(qr.Rows[0][0]) if err != nil { return 0, err } } // Fill the holes where no value was supplied. cur := insertID for i, v := range resolved { if v.IsNull() { bindVars[SeqVarName+strconv.Itoa(i)] = sqltypes.Int64BindVariable(cur) cur++ } else { bindVars[SeqVarName+strconv.Itoa(i)] = sqltypes.ValueBindVariable(v) } } return insertID, nil }
go
func (ins *Insert) processGenerate(vcursor VCursor, bindVars map[string]*querypb.BindVariable) (insertID int64, err error) { if ins.Generate == nil { return 0, nil } // Scan input values to compute the number of values to generate, and // keep track of where they should be filled. resolved, err := ins.Generate.Values.ResolveList(bindVars) if err != nil { return 0, vterrors.Wrap(err, "processGenerate") } count := int64(0) for _, val := range resolved { if val.IsNull() { count++ } } // If generation is needed, generate the requested number of values (as one call). if count != 0 { rss, _, err := vcursor.ResolveDestinations(ins.Generate.Keyspace.Name, nil, []key.Destination{key.DestinationAnyShard{}}) if err != nil { return 0, vterrors.Wrap(err, "processGenerate") } if len(rss) != 1 { return 0, vterrors.Wrapf(err, "processGenerate len(rss)=%v", len(rss)) } bindVars := map[string]*querypb.BindVariable{"n": sqltypes.Int64BindVariable(count)} qr, err := vcursor.ExecuteStandalone(ins.Generate.Query, bindVars, rss[0]) if err != nil { return 0, err } // If no rows are returned, it's an internal error, and the code // must panic, which will be caught and reported. insertID, err = sqltypes.ToInt64(qr.Rows[0][0]) if err != nil { return 0, err } } // Fill the holes where no value was supplied. cur := insertID for i, v := range resolved { if v.IsNull() { bindVars[SeqVarName+strconv.Itoa(i)] = sqltypes.Int64BindVariable(cur) cur++ } else { bindVars[SeqVarName+strconv.Itoa(i)] = sqltypes.ValueBindVariable(v) } } return insertID, nil }
[ "func", "(", "ins", "*", "Insert", ")", "processGenerate", "(", "vcursor", "VCursor", ",", "bindVars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "(", "insertID", "int64", ",", "err", "error", ")", "{", "if", "ins", ".", "Generate", "==", "nil", "{", "return", "0", ",", "nil", "\n", "}", "\n\n", "// Scan input values to compute the number of values to generate, and", "// keep track of where they should be filled.", "resolved", ",", "err", ":=", "ins", ".", "Generate", ".", "Values", ".", "ResolveList", "(", "bindVars", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "vterrors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "count", ":=", "int64", "(", "0", ")", "\n", "for", "_", ",", "val", ":=", "range", "resolved", "{", "if", "val", ".", "IsNull", "(", ")", "{", "count", "++", "\n", "}", "\n", "}", "\n\n", "// If generation is needed, generate the requested number of values (as one call).", "if", "count", "!=", "0", "{", "rss", ",", "_", ",", "err", ":=", "vcursor", ".", "ResolveDestinations", "(", "ins", ".", "Generate", ".", "Keyspace", ".", "Name", ",", "nil", ",", "[", "]", "key", ".", "Destination", "{", "key", ".", "DestinationAnyShard", "{", "}", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "vterrors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "rss", ")", "!=", "1", "{", "return", "0", ",", "vterrors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "len", "(", "rss", ")", ")", "\n", "}", "\n", "bindVars", ":=", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", "{", "\"", "\"", ":", "sqltypes", ".", "Int64BindVariable", "(", "count", ")", "}", "\n", "qr", ",", "err", ":=", "vcursor", ".", "ExecuteStandalone", "(", "ins", ".", "Generate", ".", "Query", ",", "bindVars", ",", "rss", "[", "0", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "// If no rows are returned, it's an internal error, and the code", "// must panic, which will be caught and reported.", "insertID", ",", "err", "=", "sqltypes", ".", "ToInt64", "(", "qr", ".", "Rows", "[", "0", "]", "[", "0", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "}", "\n\n", "// Fill the holes where no value was supplied.", "cur", ":=", "insertID", "\n", "for", "i", ",", "v", ":=", "range", "resolved", "{", "if", "v", ".", "IsNull", "(", ")", "{", "bindVars", "[", "SeqVarName", "+", "strconv", ".", "Itoa", "(", "i", ")", "]", "=", "sqltypes", ".", "Int64BindVariable", "(", "cur", ")", "\n", "cur", "++", "\n", "}", "else", "{", "bindVars", "[", "SeqVarName", "+", "strconv", ".", "Itoa", "(", "i", ")", "]", "=", "sqltypes", ".", "ValueBindVariable", "(", "v", ")", "\n", "}", "\n", "}", "\n", "return", "insertID", ",", "nil", "\n", "}" ]
// processGenerate generates new values using a sequence if necessary. // If no value was generated, it returns 0. Values are generated only // for cases where none are supplied.
[ "processGenerate", "generates", "new", "values", "using", "a", "sequence", "if", "necessary", ".", "If", "no", "value", "was", "generated", "it", "returns", "0", ".", "Values", "are", "generated", "only", "for", "cases", "where", "none", "are", "supplied", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/engine/insert.go#L279-L330
train
vitessio/vitess
go/vt/vtgate/engine/insert.go
processPrimary
func (ins *Insert) processPrimary(vcursor VCursor, vindexKeys [][]sqltypes.Value, colVindex *vindexes.ColumnVindex, bv map[string]*querypb.BindVariable) ([][]byte, error) { var flattenedVindexKeys []sqltypes.Value // TODO: @rafael - this will change once vindex Primary keys also support multicolumns for _, val := range vindexKeys { flattenedVindexKeys = append(flattenedVindexKeys, val...) } destinations, err := colVindex.Vindex.Map(vcursor, flattenedVindexKeys) if err != nil { return nil, err } keyspaceIDs := make([][]byte, len(destinations)) for i, destination := range destinations { switch d := destination.(type) { case key.DestinationKeyspaceID: // This is a single keyspace id, we're good. keyspaceIDs[i] = d case key.DestinationNone: // No valid keyspace id, we may return an error. if ins.Opcode != InsertShardedIgnore { return nil, fmt.Errorf("could not map %v to a keyspace id", flattenedVindexKeys[i]) } default: return nil, fmt.Errorf("could not map %v to a unique keyspace id: %v", flattenedVindexKeys[i], destination) } } for rowNum, vindexKey := range flattenedVindexKeys { if keyspaceIDs[rowNum] == nil { // InsertShardedIgnore: skip the row. continue } for _, col := range colVindex.Columns { bv[insertVarName(col, rowNum)] = sqltypes.ValueBindVariable(vindexKey) } } return keyspaceIDs, nil }
go
func (ins *Insert) processPrimary(vcursor VCursor, vindexKeys [][]sqltypes.Value, colVindex *vindexes.ColumnVindex, bv map[string]*querypb.BindVariable) ([][]byte, error) { var flattenedVindexKeys []sqltypes.Value // TODO: @rafael - this will change once vindex Primary keys also support multicolumns for _, val := range vindexKeys { flattenedVindexKeys = append(flattenedVindexKeys, val...) } destinations, err := colVindex.Vindex.Map(vcursor, flattenedVindexKeys) if err != nil { return nil, err } keyspaceIDs := make([][]byte, len(destinations)) for i, destination := range destinations { switch d := destination.(type) { case key.DestinationKeyspaceID: // This is a single keyspace id, we're good. keyspaceIDs[i] = d case key.DestinationNone: // No valid keyspace id, we may return an error. if ins.Opcode != InsertShardedIgnore { return nil, fmt.Errorf("could not map %v to a keyspace id", flattenedVindexKeys[i]) } default: return nil, fmt.Errorf("could not map %v to a unique keyspace id: %v", flattenedVindexKeys[i], destination) } } for rowNum, vindexKey := range flattenedVindexKeys { if keyspaceIDs[rowNum] == nil { // InsertShardedIgnore: skip the row. continue } for _, col := range colVindex.Columns { bv[insertVarName(col, rowNum)] = sqltypes.ValueBindVariable(vindexKey) } } return keyspaceIDs, nil }
[ "func", "(", "ins", "*", "Insert", ")", "processPrimary", "(", "vcursor", "VCursor", ",", "vindexKeys", "[", "]", "[", "]", "sqltypes", ".", "Value", ",", "colVindex", "*", "vindexes", ".", "ColumnVindex", ",", "bv", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ")", "(", "[", "]", "[", "]", "byte", ",", "error", ")", "{", "var", "flattenedVindexKeys", "[", "]", "sqltypes", ".", "Value", "\n", "// TODO: @rafael - this will change once vindex Primary keys also support multicolumns", "for", "_", ",", "val", ":=", "range", "vindexKeys", "{", "flattenedVindexKeys", "=", "append", "(", "flattenedVindexKeys", ",", "val", "...", ")", "\n", "}", "\n\n", "destinations", ",", "err", ":=", "colVindex", ".", "Vindex", ".", "Map", "(", "vcursor", ",", "flattenedVindexKeys", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "keyspaceIDs", ":=", "make", "(", "[", "]", "[", "]", "byte", ",", "len", "(", "destinations", ")", ")", "\n", "for", "i", ",", "destination", ":=", "range", "destinations", "{", "switch", "d", ":=", "destination", ".", "(", "type", ")", "{", "case", "key", ".", "DestinationKeyspaceID", ":", "// This is a single keyspace id, we're good.", "keyspaceIDs", "[", "i", "]", "=", "d", "\n", "case", "key", ".", "DestinationNone", ":", "// No valid keyspace id, we may return an error.", "if", "ins", ".", "Opcode", "!=", "InsertShardedIgnore", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "flattenedVindexKeys", "[", "i", "]", ")", "\n", "}", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "flattenedVindexKeys", "[", "i", "]", ",", "destination", ")", "\n", "}", "\n", "}", "\n\n", "for", "rowNum", ",", "vindexKey", ":=", "range", "flattenedVindexKeys", "{", "if", "keyspaceIDs", "[", "rowNum", "]", "==", "nil", "{", "// InsertShardedIgnore: skip the row.", "continue", "\n", "}", "\n", "for", "_", ",", "col", ":=", "range", "colVindex", ".", "Columns", "{", "bv", "[", "insertVarName", "(", "col", ",", "rowNum", ")", "]", "=", "sqltypes", ".", "ValueBindVariable", "(", "vindexKey", ")", "\n", "}", "\n", "}", "\n", "return", "keyspaceIDs", ",", "nil", "\n", "}" ]
// processPrimary maps the primary vindex values to the kesypace ids.
[ "processPrimary", "maps", "the", "primary", "vindex", "values", "to", "the", "kesypace", "ids", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/engine/insert.go#L455-L493
train
vitessio/vitess
go/vt/vtgate/engine/insert.go
processOwned
func (ins *Insert) processOwned(vcursor VCursor, vindexColumnsKeys [][]sqltypes.Value, colVindex *vindexes.ColumnVindex, bv map[string]*querypb.BindVariable, ksids [][]byte) error { for rowNum, rowColumnKeys := range vindexColumnsKeys { for colIdx, vindexKey := range rowColumnKeys { col := colVindex.Columns[colIdx] bv[insertVarName(col, rowNum)] = sqltypes.ValueBindVariable(vindexKey) } } return colVindex.Vindex.(vindexes.Lookup).Create(vcursor, vindexColumnsKeys, ksids, false /* ignoreMode */) }
go
func (ins *Insert) processOwned(vcursor VCursor, vindexColumnsKeys [][]sqltypes.Value, colVindex *vindexes.ColumnVindex, bv map[string]*querypb.BindVariable, ksids [][]byte) error { for rowNum, rowColumnKeys := range vindexColumnsKeys { for colIdx, vindexKey := range rowColumnKeys { col := colVindex.Columns[colIdx] bv[insertVarName(col, rowNum)] = sqltypes.ValueBindVariable(vindexKey) } } return colVindex.Vindex.(vindexes.Lookup).Create(vcursor, vindexColumnsKeys, ksids, false /* ignoreMode */) }
[ "func", "(", "ins", "*", "Insert", ")", "processOwned", "(", "vcursor", "VCursor", ",", "vindexColumnsKeys", "[", "]", "[", "]", "sqltypes", ".", "Value", ",", "colVindex", "*", "vindexes", ".", "ColumnVindex", ",", "bv", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "ksids", "[", "]", "[", "]", "byte", ")", "error", "{", "for", "rowNum", ",", "rowColumnKeys", ":=", "range", "vindexColumnsKeys", "{", "for", "colIdx", ",", "vindexKey", ":=", "range", "rowColumnKeys", "{", "col", ":=", "colVindex", ".", "Columns", "[", "colIdx", "]", "\n", "bv", "[", "insertVarName", "(", "col", ",", "rowNum", ")", "]", "=", "sqltypes", ".", "ValueBindVariable", "(", "vindexKey", ")", "\n", "}", "\n", "}", "\n", "return", "colVindex", ".", "Vindex", ".", "(", "vindexes", ".", "Lookup", ")", ".", "Create", "(", "vcursor", ",", "vindexColumnsKeys", ",", "ksids", ",", "false", "/* ignoreMode */", ")", "\n", "}" ]
// processOwned creates vindex entries for the values of an owned column for InsertSharded.
[ "processOwned", "creates", "vindex", "entries", "for", "the", "values", "of", "an", "owned", "column", "for", "InsertSharded", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/engine/insert.go#L496-L504
train
vitessio/vitess
go/vt/vtgate/engine/insert.go
processOwnedIgnore
func (ins *Insert) processOwnedIgnore(vcursor VCursor, vindexColumnsKeys [][]sqltypes.Value, colVindex *vindexes.ColumnVindex, bv map[string]*querypb.BindVariable, ksids [][]byte) error { var createIndexes []int var createKeys [][]sqltypes.Value var createKsids [][]byte for rowNum, rowColumnKeys := range vindexColumnsKeys { var rowKeys []sqltypes.Value if ksids[rowNum] == nil { continue } createIndexes = append(createIndexes, rowNum) createKsids = append(createKsids, ksids[rowNum]) for colIdx, vindexKey := range rowColumnKeys { rowKeys = append(rowKeys, vindexKey) col := colVindex.Columns[colIdx] bv[insertVarName(col, rowNum)] = sqltypes.ValueBindVariable(vindexKey) } createKeys = append(createKeys, rowKeys) } if createKeys == nil { return nil } err := colVindex.Vindex.(vindexes.Lookup).Create(vcursor, createKeys, createKsids, true /* ignoreMode */) if err != nil { return err } // After creation, verify that the keys map to the keyspace ids. If not, remove // those that don't map. // If values were supplied, we validate against keyspace id. var ids []sqltypes.Value for _, vindexValues := range createKeys { ids = append(ids, vindexValues[0]) } verified, err := colVindex.Vindex.Verify(vcursor, ids, createKsids) if err != nil { return err } for i, v := range verified { if !v { ksids[createIndexes[i]] = nil } } return nil }
go
func (ins *Insert) processOwnedIgnore(vcursor VCursor, vindexColumnsKeys [][]sqltypes.Value, colVindex *vindexes.ColumnVindex, bv map[string]*querypb.BindVariable, ksids [][]byte) error { var createIndexes []int var createKeys [][]sqltypes.Value var createKsids [][]byte for rowNum, rowColumnKeys := range vindexColumnsKeys { var rowKeys []sqltypes.Value if ksids[rowNum] == nil { continue } createIndexes = append(createIndexes, rowNum) createKsids = append(createKsids, ksids[rowNum]) for colIdx, vindexKey := range rowColumnKeys { rowKeys = append(rowKeys, vindexKey) col := colVindex.Columns[colIdx] bv[insertVarName(col, rowNum)] = sqltypes.ValueBindVariable(vindexKey) } createKeys = append(createKeys, rowKeys) } if createKeys == nil { return nil } err := colVindex.Vindex.(vindexes.Lookup).Create(vcursor, createKeys, createKsids, true /* ignoreMode */) if err != nil { return err } // After creation, verify that the keys map to the keyspace ids. If not, remove // those that don't map. // If values were supplied, we validate against keyspace id. var ids []sqltypes.Value for _, vindexValues := range createKeys { ids = append(ids, vindexValues[0]) } verified, err := colVindex.Vindex.Verify(vcursor, ids, createKsids) if err != nil { return err } for i, v := range verified { if !v { ksids[createIndexes[i]] = nil } } return nil }
[ "func", "(", "ins", "*", "Insert", ")", "processOwnedIgnore", "(", "vcursor", "VCursor", ",", "vindexColumnsKeys", "[", "]", "[", "]", "sqltypes", ".", "Value", ",", "colVindex", "*", "vindexes", ".", "ColumnVindex", ",", "bv", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "ksids", "[", "]", "[", "]", "byte", ")", "error", "{", "var", "createIndexes", "[", "]", "int", "\n", "var", "createKeys", "[", "]", "[", "]", "sqltypes", ".", "Value", "\n", "var", "createKsids", "[", "]", "[", "]", "byte", "\n\n", "for", "rowNum", ",", "rowColumnKeys", ":=", "range", "vindexColumnsKeys", "{", "var", "rowKeys", "[", "]", "sqltypes", ".", "Value", "\n", "if", "ksids", "[", "rowNum", "]", "==", "nil", "{", "continue", "\n", "}", "\n", "createIndexes", "=", "append", "(", "createIndexes", ",", "rowNum", ")", "\n", "createKsids", "=", "append", "(", "createKsids", ",", "ksids", "[", "rowNum", "]", ")", "\n\n", "for", "colIdx", ",", "vindexKey", ":=", "range", "rowColumnKeys", "{", "rowKeys", "=", "append", "(", "rowKeys", ",", "vindexKey", ")", "\n", "col", ":=", "colVindex", ".", "Columns", "[", "colIdx", "]", "\n", "bv", "[", "insertVarName", "(", "col", ",", "rowNum", ")", "]", "=", "sqltypes", ".", "ValueBindVariable", "(", "vindexKey", ")", "\n", "}", "\n", "createKeys", "=", "append", "(", "createKeys", ",", "rowKeys", ")", "\n", "}", "\n", "if", "createKeys", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "err", ":=", "colVindex", ".", "Vindex", ".", "(", "vindexes", ".", "Lookup", ")", ".", "Create", "(", "vcursor", ",", "createKeys", ",", "createKsids", ",", "true", "/* ignoreMode */", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// After creation, verify that the keys map to the keyspace ids. If not, remove", "// those that don't map.", "// If values were supplied, we validate against keyspace id.", "var", "ids", "[", "]", "sqltypes", ".", "Value", "\n", "for", "_", ",", "vindexValues", ":=", "range", "createKeys", "{", "ids", "=", "append", "(", "ids", ",", "vindexValues", "[", "0", "]", ")", "\n", "}", "\n", "verified", ",", "err", ":=", "colVindex", ".", "Vindex", ".", "Verify", "(", "vcursor", ",", "ids", ",", "createKsids", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "i", ",", "v", ":=", "range", "verified", "{", "if", "!", "v", "{", "ksids", "[", "createIndexes", "[", "i", "]", "]", "=", "nil", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// processOwnedIgnore creates vindex entries for the values of an owned column for InsertShardedIgnore.
[ "processOwnedIgnore", "creates", "vindex", "entries", "for", "the", "values", "of", "an", "owned", "column", "for", "InsertShardedIgnore", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/engine/insert.go#L507-L552
train
vitessio/vitess
go/vt/vtgate/engine/insert.go
processUnowned
func (ins *Insert) processUnowned(vcursor VCursor, vindexColumnsKeys [][]sqltypes.Value, colVindex *vindexes.ColumnVindex, bv map[string]*querypb.BindVariable, ksids [][]byte) error { var reverseIndexes []int var reverseKsids [][]byte var verifyIndexes []int var verifyKeys []sqltypes.Value var verifyKsids [][]byte for rowNum, rowColumnKeys := range vindexColumnsKeys { // Right now, we only validate against the first column of a colvindex. // TODO(sougou): address this when we add multicolumn Map support. vindexKey := rowColumnKeys[0] if ksids[rowNum] == nil { continue } if vindexKey.IsNull() { reverseIndexes = append(reverseIndexes, rowNum) reverseKsids = append(reverseKsids, ksids[rowNum]) } else { verifyIndexes = append(verifyIndexes, rowNum) verifyKeys = append(verifyKeys, vindexKey) verifyKsids = append(verifyKsids, ksids[rowNum]) } } // For cases where a value was not supplied, we reverse map it // from the keyspace id, if possible. if reverseKsids != nil { reversible, ok := colVindex.Vindex.(vindexes.Reversible) if !ok { return fmt.Errorf("value must be supplied for column %v", colVindex.Columns) } reverseKeys, err := reversible.ReverseMap(vcursor, reverseKsids) if err != nil { return err } for i, reverseKey := range reverseKeys { rowNum := reverseIndexes[i] for colIdx, col := range colVindex.Columns { if colIdx == 0 { // Fill the first column with the reverse-mapped value. bv[insertVarName(col, rowNum)] = sqltypes.ValueBindVariable(reverseKey) } else { // Fill other columns with supplied values. bv[insertVarName(col, rowNum)] = sqltypes.ValueBindVariable(vindexColumnsKeys[rowNum][colIdx]) } } } } if verifyKsids != nil { // If values were supplied, we validate against keyspace id. verified, err := colVindex.Vindex.Verify(vcursor, verifyKeys, verifyKsids) if err != nil { return err } for i, v := range verified { rowNum := verifyIndexes[i] if !v { if ins.Opcode != InsertShardedIgnore { return fmt.Errorf("values %v for column %v does not map to keyspace ids", vindexColumnsKeys, colVindex.Columns) } // InsertShardedIgnore: skip the row. ksids[rowNum] = nil continue } for colIdx, col := range colVindex.Columns { bv[insertVarName(col, rowNum)] = sqltypes.ValueBindVariable(vindexColumnsKeys[rowNum][colIdx]) } } } return nil }
go
func (ins *Insert) processUnowned(vcursor VCursor, vindexColumnsKeys [][]sqltypes.Value, colVindex *vindexes.ColumnVindex, bv map[string]*querypb.BindVariable, ksids [][]byte) error { var reverseIndexes []int var reverseKsids [][]byte var verifyIndexes []int var verifyKeys []sqltypes.Value var verifyKsids [][]byte for rowNum, rowColumnKeys := range vindexColumnsKeys { // Right now, we only validate against the first column of a colvindex. // TODO(sougou): address this when we add multicolumn Map support. vindexKey := rowColumnKeys[0] if ksids[rowNum] == nil { continue } if vindexKey.IsNull() { reverseIndexes = append(reverseIndexes, rowNum) reverseKsids = append(reverseKsids, ksids[rowNum]) } else { verifyIndexes = append(verifyIndexes, rowNum) verifyKeys = append(verifyKeys, vindexKey) verifyKsids = append(verifyKsids, ksids[rowNum]) } } // For cases where a value was not supplied, we reverse map it // from the keyspace id, if possible. if reverseKsids != nil { reversible, ok := colVindex.Vindex.(vindexes.Reversible) if !ok { return fmt.Errorf("value must be supplied for column %v", colVindex.Columns) } reverseKeys, err := reversible.ReverseMap(vcursor, reverseKsids) if err != nil { return err } for i, reverseKey := range reverseKeys { rowNum := reverseIndexes[i] for colIdx, col := range colVindex.Columns { if colIdx == 0 { // Fill the first column with the reverse-mapped value. bv[insertVarName(col, rowNum)] = sqltypes.ValueBindVariable(reverseKey) } else { // Fill other columns with supplied values. bv[insertVarName(col, rowNum)] = sqltypes.ValueBindVariable(vindexColumnsKeys[rowNum][colIdx]) } } } } if verifyKsids != nil { // If values were supplied, we validate against keyspace id. verified, err := colVindex.Vindex.Verify(vcursor, verifyKeys, verifyKsids) if err != nil { return err } for i, v := range verified { rowNum := verifyIndexes[i] if !v { if ins.Opcode != InsertShardedIgnore { return fmt.Errorf("values %v for column %v does not map to keyspace ids", vindexColumnsKeys, colVindex.Columns) } // InsertShardedIgnore: skip the row. ksids[rowNum] = nil continue } for colIdx, col := range colVindex.Columns { bv[insertVarName(col, rowNum)] = sqltypes.ValueBindVariable(vindexColumnsKeys[rowNum][colIdx]) } } } return nil }
[ "func", "(", "ins", "*", "Insert", ")", "processUnowned", "(", "vcursor", "VCursor", ",", "vindexColumnsKeys", "[", "]", "[", "]", "sqltypes", ".", "Value", ",", "colVindex", "*", "vindexes", ".", "ColumnVindex", ",", "bv", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "ksids", "[", "]", "[", "]", "byte", ")", "error", "{", "var", "reverseIndexes", "[", "]", "int", "\n", "var", "reverseKsids", "[", "]", "[", "]", "byte", "\n", "var", "verifyIndexes", "[", "]", "int", "\n", "var", "verifyKeys", "[", "]", "sqltypes", ".", "Value", "\n", "var", "verifyKsids", "[", "]", "[", "]", "byte", "\n\n", "for", "rowNum", ",", "rowColumnKeys", ":=", "range", "vindexColumnsKeys", "{", "// Right now, we only validate against the first column of a colvindex.", "// TODO(sougou): address this when we add multicolumn Map support.", "vindexKey", ":=", "rowColumnKeys", "[", "0", "]", "\n", "if", "ksids", "[", "rowNum", "]", "==", "nil", "{", "continue", "\n", "}", "\n", "if", "vindexKey", ".", "IsNull", "(", ")", "{", "reverseIndexes", "=", "append", "(", "reverseIndexes", ",", "rowNum", ")", "\n", "reverseKsids", "=", "append", "(", "reverseKsids", ",", "ksids", "[", "rowNum", "]", ")", "\n", "}", "else", "{", "verifyIndexes", "=", "append", "(", "verifyIndexes", ",", "rowNum", ")", "\n", "verifyKeys", "=", "append", "(", "verifyKeys", ",", "vindexKey", ")", "\n", "verifyKsids", "=", "append", "(", "verifyKsids", ",", "ksids", "[", "rowNum", "]", ")", "\n", "}", "\n", "}", "\n\n", "// For cases where a value was not supplied, we reverse map it", "// from the keyspace id, if possible.", "if", "reverseKsids", "!=", "nil", "{", "reversible", ",", "ok", ":=", "colVindex", ".", "Vindex", ".", "(", "vindexes", ".", "Reversible", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "colVindex", ".", "Columns", ")", "\n", "}", "\n", "reverseKeys", ",", "err", ":=", "reversible", ".", "ReverseMap", "(", "vcursor", ",", "reverseKsids", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "i", ",", "reverseKey", ":=", "range", "reverseKeys", "{", "rowNum", ":=", "reverseIndexes", "[", "i", "]", "\n", "for", "colIdx", ",", "col", ":=", "range", "colVindex", ".", "Columns", "{", "if", "colIdx", "==", "0", "{", "// Fill the first column with the reverse-mapped value.", "bv", "[", "insertVarName", "(", "col", ",", "rowNum", ")", "]", "=", "sqltypes", ".", "ValueBindVariable", "(", "reverseKey", ")", "\n", "}", "else", "{", "// Fill other columns with supplied values.", "bv", "[", "insertVarName", "(", "col", ",", "rowNum", ")", "]", "=", "sqltypes", ".", "ValueBindVariable", "(", "vindexColumnsKeys", "[", "rowNum", "]", "[", "colIdx", "]", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "verifyKsids", "!=", "nil", "{", "// If values were supplied, we validate against keyspace id.", "verified", ",", "err", ":=", "colVindex", ".", "Vindex", ".", "Verify", "(", "vcursor", ",", "verifyKeys", ",", "verifyKsids", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "i", ",", "v", ":=", "range", "verified", "{", "rowNum", ":=", "verifyIndexes", "[", "i", "]", "\n", "if", "!", "v", "{", "if", "ins", ".", "Opcode", "!=", "InsertShardedIgnore", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "vindexColumnsKeys", ",", "colVindex", ".", "Columns", ")", "\n", "}", "\n", "// InsertShardedIgnore: skip the row.", "ksids", "[", "rowNum", "]", "=", "nil", "\n", "continue", "\n", "}", "\n", "for", "colIdx", ",", "col", ":=", "range", "colVindex", ".", "Columns", "{", "bv", "[", "insertVarName", "(", "col", ",", "rowNum", ")", "]", "=", "sqltypes", ".", "ValueBindVariable", "(", "vindexColumnsKeys", "[", "rowNum", "]", "[", "colIdx", "]", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// processUnowned either reverse maps or validates the values for an unowned column.
[ "processUnowned", "either", "reverse", "maps", "or", "validates", "the", "values", "for", "an", "unowned", "column", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/engine/insert.go#L555-L626
train
vitessio/vitess
go/cmd/vtctl/vtctl.go
installSignalHandlers
func installSignalHandlers(cancel func()) { sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGTERM, syscall.SIGINT) go func() { <-sigChan // we got a signal, cancel the current ctx cancel() }() }
go
func installSignalHandlers(cancel func()) { sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGTERM, syscall.SIGINT) go func() { <-sigChan // we got a signal, cancel the current ctx cancel() }() }
[ "func", "installSignalHandlers", "(", "cancel", "func", "(", ")", ")", "{", "sigChan", ":=", "make", "(", "chan", "os", ".", "Signal", ",", "1", ")", "\n", "signal", ".", "Notify", "(", "sigChan", ",", "syscall", ".", "SIGTERM", ",", "syscall", ".", "SIGINT", ")", "\n", "go", "func", "(", ")", "{", "<-", "sigChan", "\n", "// we got a signal, cancel the current ctx", "cancel", "(", ")", "\n", "}", "(", ")", "\n", "}" ]
// signal handling, centralized here
[ "signal", "handling", "centralized", "here" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/cmd/vtctl/vtctl.go#L59-L67
train
vitessio/vitess
go/vt/topo/errors.go
NewError
func NewError(code ErrorCode, node string) error { var message string switch code { case NodeExists: message = fmt.Sprintf("node already exists: %s", node) case NoNode: message = fmt.Sprintf("node doesn't exist: %s", node) case NodeNotEmpty: message = fmt.Sprintf("node not empty: %s", node) case Timeout: message = fmt.Sprintf("deadline exceeded: %s", node) case Interrupted: message = fmt.Sprintf("interrupted: %s", node) case BadVersion: message = fmt.Sprintf("bad node version: %s", node) case PartialResult: message = fmt.Sprintf("partial result: %s", node) case NoUpdateNeeded: message = fmt.Sprintf("no update needed: %s", node) case NoImplementation: message = fmt.Sprintf("no such topology implementation %s", node) default: message = fmt.Sprintf("unknown code: %s", node) } return Error{ code: code, message: message, } }
go
func NewError(code ErrorCode, node string) error { var message string switch code { case NodeExists: message = fmt.Sprintf("node already exists: %s", node) case NoNode: message = fmt.Sprintf("node doesn't exist: %s", node) case NodeNotEmpty: message = fmt.Sprintf("node not empty: %s", node) case Timeout: message = fmt.Sprintf("deadline exceeded: %s", node) case Interrupted: message = fmt.Sprintf("interrupted: %s", node) case BadVersion: message = fmt.Sprintf("bad node version: %s", node) case PartialResult: message = fmt.Sprintf("partial result: %s", node) case NoUpdateNeeded: message = fmt.Sprintf("no update needed: %s", node) case NoImplementation: message = fmt.Sprintf("no such topology implementation %s", node) default: message = fmt.Sprintf("unknown code: %s", node) } return Error{ code: code, message: message, } }
[ "func", "NewError", "(", "code", "ErrorCode", ",", "node", "string", ")", "error", "{", "var", "message", "string", "\n", "switch", "code", "{", "case", "NodeExists", ":", "message", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "node", ")", "\n", "case", "NoNode", ":", "message", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "node", ")", "\n", "case", "NodeNotEmpty", ":", "message", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "node", ")", "\n", "case", "Timeout", ":", "message", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "node", ")", "\n", "case", "Interrupted", ":", "message", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "node", ")", "\n", "case", "BadVersion", ":", "message", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "node", ")", "\n", "case", "PartialResult", ":", "message", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "node", ")", "\n", "case", "NoUpdateNeeded", ":", "message", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "node", ")", "\n", "case", "NoImplementation", ":", "message", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "node", ")", "\n", "default", ":", "message", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "node", ")", "\n", "}", "\n", "return", "Error", "{", "code", ":", "code", ",", "message", ":", "message", ",", "}", "\n", "}" ]
// NewError creates a new topo error.
[ "NewError", "creates", "a", "new", "topo", "error", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/errors.go#L46-L74
train
vitessio/vitess
go/vt/topo/errors.go
IsErrType
func IsErrType(err error, code ErrorCode) bool { if e, ok := err.(Error); ok { return e.code == code } return false }
go
func IsErrType(err error, code ErrorCode) bool { if e, ok := err.(Error); ok { return e.code == code } return false }
[ "func", "IsErrType", "(", "err", "error", ",", "code", "ErrorCode", ")", "bool", "{", "if", "e", ",", "ok", ":=", "err", ".", "(", "Error", ")", ";", "ok", "{", "return", "e", ".", "code", "==", "code", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsErrType returns true if the error has the specified ErrorCode.
[ "IsErrType", "returns", "true", "if", "the", "error", "has", "the", "specified", "ErrorCode", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/errors.go#L82-L87
train
vitessio/vitess
go/vt/vtgate/planbuilder/join.go
newJoin
func newJoin(lpb, rpb *primitiveBuilder, ajoin *sqlparser.JoinTableExpr) error { // This function converts ON clauses to WHERE clauses. The WHERE clause // scope can see all tables, whereas the ON clause can only see the // participants of the JOIN. However, since the ON clause doesn't allow // external references, and the FROM clause doesn't allow duplicates, // it's safe to perform this conversion and still expect the same behavior. opcode := engine.NormalJoin if ajoin != nil { switch { case ajoin.Join == sqlparser.LeftJoinStr: opcode = engine.LeftJoin // For left joins, we have to push the ON clause into the RHS. // We do this before creating the join primitive. // However, variables of LHS need to be visible. To allow this, // we mark the LHS symtab as outer scope to the RHS, just like // a subquery. This make the RHS treat the LHS symbols as external. // This will prevent constructs from escaping out of the rpb scope. // At this point, the LHS symtab also contains symbols of the RHS. // But the RHS will hide those, as intended. rpb.st.Outer = lpb.st if err := rpb.pushFilter(ajoin.Condition.On, sqlparser.WhereStr); err != nil { return err } case ajoin.Condition.Using != nil: return errors.New("unsupported: join with USING(column_list) clause") } } lpb.bldr = &join{ Left: lpb.bldr, Right: rpb.bldr, ejoin: &engine.Join{ Opcode: opcode, Vars: make(map[string]int), }, } lpb.bldr.Reorder(0) if ajoin == nil || opcode == engine.LeftJoin { return nil } return lpb.pushFilter(ajoin.Condition.On, sqlparser.WhereStr) }
go
func newJoin(lpb, rpb *primitiveBuilder, ajoin *sqlparser.JoinTableExpr) error { // This function converts ON clauses to WHERE clauses. The WHERE clause // scope can see all tables, whereas the ON clause can only see the // participants of the JOIN. However, since the ON clause doesn't allow // external references, and the FROM clause doesn't allow duplicates, // it's safe to perform this conversion and still expect the same behavior. opcode := engine.NormalJoin if ajoin != nil { switch { case ajoin.Join == sqlparser.LeftJoinStr: opcode = engine.LeftJoin // For left joins, we have to push the ON clause into the RHS. // We do this before creating the join primitive. // However, variables of LHS need to be visible. To allow this, // we mark the LHS symtab as outer scope to the RHS, just like // a subquery. This make the RHS treat the LHS symbols as external. // This will prevent constructs from escaping out of the rpb scope. // At this point, the LHS symtab also contains symbols of the RHS. // But the RHS will hide those, as intended. rpb.st.Outer = lpb.st if err := rpb.pushFilter(ajoin.Condition.On, sqlparser.WhereStr); err != nil { return err } case ajoin.Condition.Using != nil: return errors.New("unsupported: join with USING(column_list) clause") } } lpb.bldr = &join{ Left: lpb.bldr, Right: rpb.bldr, ejoin: &engine.Join{ Opcode: opcode, Vars: make(map[string]int), }, } lpb.bldr.Reorder(0) if ajoin == nil || opcode == engine.LeftJoin { return nil } return lpb.pushFilter(ajoin.Condition.On, sqlparser.WhereStr) }
[ "func", "newJoin", "(", "lpb", ",", "rpb", "*", "primitiveBuilder", ",", "ajoin", "*", "sqlparser", ".", "JoinTableExpr", ")", "error", "{", "// This function converts ON clauses to WHERE clauses. The WHERE clause", "// scope can see all tables, whereas the ON clause can only see the", "// participants of the JOIN. However, since the ON clause doesn't allow", "// external references, and the FROM clause doesn't allow duplicates,", "// it's safe to perform this conversion and still expect the same behavior.", "opcode", ":=", "engine", ".", "NormalJoin", "\n", "if", "ajoin", "!=", "nil", "{", "switch", "{", "case", "ajoin", ".", "Join", "==", "sqlparser", ".", "LeftJoinStr", ":", "opcode", "=", "engine", ".", "LeftJoin", "\n\n", "// For left joins, we have to push the ON clause into the RHS.", "// We do this before creating the join primitive.", "// However, variables of LHS need to be visible. To allow this,", "// we mark the LHS symtab as outer scope to the RHS, just like", "// a subquery. This make the RHS treat the LHS symbols as external.", "// This will prevent constructs from escaping out of the rpb scope.", "// At this point, the LHS symtab also contains symbols of the RHS.", "// But the RHS will hide those, as intended.", "rpb", ".", "st", ".", "Outer", "=", "lpb", ".", "st", "\n", "if", "err", ":=", "rpb", ".", "pushFilter", "(", "ajoin", ".", "Condition", ".", "On", ",", "sqlparser", ".", "WhereStr", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "case", "ajoin", ".", "Condition", ".", "Using", "!=", "nil", ":", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "lpb", ".", "bldr", "=", "&", "join", "{", "Left", ":", "lpb", ".", "bldr", ",", "Right", ":", "rpb", ".", "bldr", ",", "ejoin", ":", "&", "engine", ".", "Join", "{", "Opcode", ":", "opcode", ",", "Vars", ":", "make", "(", "map", "[", "string", "]", "int", ")", ",", "}", ",", "}", "\n", "lpb", ".", "bldr", ".", "Reorder", "(", "0", ")", "\n", "if", "ajoin", "==", "nil", "||", "opcode", "==", "engine", ".", "LeftJoin", "{", "return", "nil", "\n", "}", "\n", "return", "lpb", ".", "pushFilter", "(", "ajoin", ".", "Condition", ".", "On", ",", "sqlparser", ".", "WhereStr", ")", "\n", "}" ]
// newJoin makes a new join using the two planBuilder. ajoin can be nil // if the join is on a ',' operator. lpb will contain the resulting join. // rpb will be discarded.
[ "newJoin", "makes", "a", "new", "join", "using", "the", "two", "planBuilder", ".", "ajoin", "can", "be", "nil", "if", "the", "join", "is", "on", "a", "operator", ".", "lpb", "will", "contain", "the", "resulting", "join", ".", "rpb", "will", "be", "discarded", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/join.go#L71-L113
train
vitessio/vitess
go/vt/workflow/manager.go
NewManager
func NewManager(ts *topo.Server) *Manager { return &Manager{ ts: ts, nodeManager: NewNodeManager(), started: make(chan struct{}), workflows: make(map[string]*runningWorkflow), } }
go
func NewManager(ts *topo.Server) *Manager { return &Manager{ ts: ts, nodeManager: NewNodeManager(), started: make(chan struct{}), workflows: make(map[string]*runningWorkflow), } }
[ "func", "NewManager", "(", "ts", "*", "topo", ".", "Server", ")", "*", "Manager", "{", "return", "&", "Manager", "{", "ts", ":", "ts", ",", "nodeManager", ":", "NewNodeManager", "(", ")", ",", "started", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "workflows", ":", "make", "(", "map", "[", "string", "]", "*", "runningWorkflow", ")", ",", "}", "\n", "}" ]
// NewManager creates an initialized Manager.
[ "NewManager", "creates", "an", "initialized", "Manager", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/manager.go#L127-L134
train
vitessio/vitess
go/vt/workflow/manager.go
Run
func (m *Manager) Run(ctx context.Context) { // Save the context for all other jobs usage, and to indicate // the manager is running. m.mu.Lock() if m.ctx != nil { m.mu.Unlock() panic("Manager is already running") } m.ctx = ctx m.loadAndStartJobsLocked() // Signal the successful startup. close(m.started) m.started = make(chan struct{}) m.mu.Unlock() // Wait for the context to be canceled. <-ctx.Done() // Clear context and get a copy of the running jobs. m.mu.Lock() m.ctx = nil runningWorkflows := m.workflows m.workflows = make(map[string]*runningWorkflow) m.mu.Unlock() // Abort the running jobs. They won't save their state as // m.ctx is nil and they know it means we're shutting down. for _, rw := range runningWorkflows { rw.cancel() } for _, rw := range runningWorkflows { <-rw.done } }
go
func (m *Manager) Run(ctx context.Context) { // Save the context for all other jobs usage, and to indicate // the manager is running. m.mu.Lock() if m.ctx != nil { m.mu.Unlock() panic("Manager is already running") } m.ctx = ctx m.loadAndStartJobsLocked() // Signal the successful startup. close(m.started) m.started = make(chan struct{}) m.mu.Unlock() // Wait for the context to be canceled. <-ctx.Done() // Clear context and get a copy of the running jobs. m.mu.Lock() m.ctx = nil runningWorkflows := m.workflows m.workflows = make(map[string]*runningWorkflow) m.mu.Unlock() // Abort the running jobs. They won't save their state as // m.ctx is nil and they know it means we're shutting down. for _, rw := range runningWorkflows { rw.cancel() } for _, rw := range runningWorkflows { <-rw.done } }
[ "func", "(", "m", "*", "Manager", ")", "Run", "(", "ctx", "context", ".", "Context", ")", "{", "// Save the context for all other jobs usage, and to indicate", "// the manager is running.", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "m", ".", "ctx", "!=", "nil", "{", "m", ".", "mu", ".", "Unlock", "(", ")", "\n", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "m", ".", "ctx", "=", "ctx", "\n", "m", ".", "loadAndStartJobsLocked", "(", ")", "\n", "// Signal the successful startup.", "close", "(", "m", ".", "started", ")", "\n", "m", ".", "started", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "m", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "// Wait for the context to be canceled.", "<-", "ctx", ".", "Done", "(", ")", "\n\n", "// Clear context and get a copy of the running jobs.", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "m", ".", "ctx", "=", "nil", "\n", "runningWorkflows", ":=", "m", ".", "workflows", "\n", "m", ".", "workflows", "=", "make", "(", "map", "[", "string", "]", "*", "runningWorkflow", ")", "\n", "m", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "// Abort the running jobs. They won't save their state as", "// m.ctx is nil and they know it means we're shutting down.", "for", "_", ",", "rw", ":=", "range", "runningWorkflows", "{", "rw", ".", "cancel", "(", ")", "\n", "}", "\n", "for", "_", ",", "rw", ":=", "range", "runningWorkflows", "{", "<-", "rw", ".", "done", "\n", "}", "\n", "}" ]
// Run is the main entry point for the Manager. It will read each // checkpoint from the topo Server, and for the ones that are in the // Running state, will load them in memory and run them. // It will not return until ctx is canceled.
[ "Run", "is", "the", "main", "entry", "point", "for", "the", "Manager", ".", "It", "will", "read", "each", "checkpoint", "from", "the", "topo", "Server", "and", "for", "the", "ones", "that", "are", "in", "the", "Running", "state", "will", "load", "them", "in", "memory", "and", "run", "them", ".", "It", "will", "not", "return", "until", "ctx", "is", "canceled", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/manager.go#L157-L190
train
vitessio/vitess
go/vt/workflow/manager.go
loadAndStartJobsLocked
func (m *Manager) loadAndStartJobsLocked() { uuids, err := m.ts.GetWorkflowNames(m.ctx) if err != nil { log.Errorf("GetWorkflowNames failed to find existing workflows: %v", err) return } for _, uuid := range uuids { // Load workflows from the topo server, only look at // 'Running' ones. wi, err := m.ts.GetWorkflow(m.ctx, uuid) if err != nil { log.Errorf("Failed to load workflow %v, will not start it: %v", uuid, err) continue } rw, err := m.instantiateWorkflow(wi.Workflow) if err != nil { log.Errorf("Failed to instantiate workflow %v from factory %v, will not start it: %v", uuid, wi.FactoryName, err) continue } rw.wi = wi if rw.wi.State == workflowpb.WorkflowState_Running { m.runWorkflow(rw) } } }
go
func (m *Manager) loadAndStartJobsLocked() { uuids, err := m.ts.GetWorkflowNames(m.ctx) if err != nil { log.Errorf("GetWorkflowNames failed to find existing workflows: %v", err) return } for _, uuid := range uuids { // Load workflows from the topo server, only look at // 'Running' ones. wi, err := m.ts.GetWorkflow(m.ctx, uuid) if err != nil { log.Errorf("Failed to load workflow %v, will not start it: %v", uuid, err) continue } rw, err := m.instantiateWorkflow(wi.Workflow) if err != nil { log.Errorf("Failed to instantiate workflow %v from factory %v, will not start it: %v", uuid, wi.FactoryName, err) continue } rw.wi = wi if rw.wi.State == workflowpb.WorkflowState_Running { m.runWorkflow(rw) } } }
[ "func", "(", "m", "*", "Manager", ")", "loadAndStartJobsLocked", "(", ")", "{", "uuids", ",", "err", ":=", "m", ".", "ts", ".", "GetWorkflowNames", "(", "m", ".", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "for", "_", ",", "uuid", ":=", "range", "uuids", "{", "// Load workflows from the topo server, only look at", "// 'Running' ones.", "wi", ",", "err", ":=", "m", ".", "ts", ".", "GetWorkflow", "(", "m", ".", "ctx", ",", "uuid", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "uuid", ",", "err", ")", "\n", "continue", "\n", "}", "\n\n", "rw", ",", "err", ":=", "m", ".", "instantiateWorkflow", "(", "wi", ".", "Workflow", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "uuid", ",", "wi", ".", "FactoryName", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "rw", ".", "wi", "=", "wi", "\n\n", "if", "rw", ".", "wi", ".", "State", "==", "workflowpb", ".", "WorkflowState_Running", "{", "m", ".", "runWorkflow", "(", "rw", ")", "\n", "}", "\n", "}", "\n", "}" ]
// loadAndStartJobsLocked will try to load and start all existing jobs // in the topo Server. It needs to be run holding m.mu.
[ "loadAndStartJobsLocked", "will", "try", "to", "load", "and", "start", "all", "existing", "jobs", "in", "the", "topo", "Server", ".", "It", "needs", "to", "be", "run", "holding", "m", ".", "mu", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/manager.go#L213-L240
train
vitessio/vitess
go/vt/workflow/manager.go
Create
func (m *Manager) Create(ctx context.Context, factoryName string, args []string) (string, error) { m.mu.Lock() defer m.mu.Unlock() // Find the factory. factory, ok := factories[factoryName] if !ok { return "", fmt.Errorf("no factory named %v is registered", factoryName) } // Create the initial workflowpb.Workflow object. w := &workflowpb.Workflow{ Uuid: gouuid.NewUUID().String(), CreateTime: time.Now().UnixNano(), FactoryName: factoryName, State: workflowpb.WorkflowState_NotStarted, } // Let the factory parse the parameters and initialize the // object. if err := factory.Init(m, w, args); err != nil { return "", err } rw, err := m.instantiateWorkflow(w) if err != nil { return "", err } // Now save the workflow in the topo server. rw.wi, err = m.ts.CreateWorkflow(ctx, w) if err != nil { return "", err } // And we're done. log.Infof("Created workflow %s (%s, %s)", w.Uuid, factoryName, w.Name) return w.Uuid, nil }
go
func (m *Manager) Create(ctx context.Context, factoryName string, args []string) (string, error) { m.mu.Lock() defer m.mu.Unlock() // Find the factory. factory, ok := factories[factoryName] if !ok { return "", fmt.Errorf("no factory named %v is registered", factoryName) } // Create the initial workflowpb.Workflow object. w := &workflowpb.Workflow{ Uuid: gouuid.NewUUID().String(), CreateTime: time.Now().UnixNano(), FactoryName: factoryName, State: workflowpb.WorkflowState_NotStarted, } // Let the factory parse the parameters and initialize the // object. if err := factory.Init(m, w, args); err != nil { return "", err } rw, err := m.instantiateWorkflow(w) if err != nil { return "", err } // Now save the workflow in the topo server. rw.wi, err = m.ts.CreateWorkflow(ctx, w) if err != nil { return "", err } // And we're done. log.Infof("Created workflow %s (%s, %s)", w.Uuid, factoryName, w.Name) return w.Uuid, nil }
[ "func", "(", "m", "*", "Manager", ")", "Create", "(", "ctx", "context", ".", "Context", ",", "factoryName", "string", ",", "args", "[", "]", "string", ")", "(", "string", ",", "error", ")", "{", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "// Find the factory.", "factory", ",", "ok", ":=", "factories", "[", "factoryName", "]", "\n", "if", "!", "ok", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "factoryName", ")", "\n", "}", "\n\n", "// Create the initial workflowpb.Workflow object.", "w", ":=", "&", "workflowpb", ".", "Workflow", "{", "Uuid", ":", "gouuid", ".", "NewUUID", "(", ")", ".", "String", "(", ")", ",", "CreateTime", ":", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ",", "FactoryName", ":", "factoryName", ",", "State", ":", "workflowpb", ".", "WorkflowState_NotStarted", ",", "}", "\n\n", "// Let the factory parse the parameters and initialize the", "// object.", "if", "err", ":=", "factory", ".", "Init", "(", "m", ",", "w", ",", "args", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "rw", ",", "err", ":=", "m", ".", "instantiateWorkflow", "(", "w", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// Now save the workflow in the topo server.", "rw", ".", "wi", ",", "err", "=", "m", ".", "ts", ".", "CreateWorkflow", "(", "ctx", ",", "w", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// And we're done.", "log", ".", "Infof", "(", "\"", "\"", ",", "w", ".", "Uuid", ",", "factoryName", ",", "w", ".", "Name", ")", "\n", "return", "w", ".", "Uuid", ",", "nil", "\n", "}" ]
// Create creates a workflow from the given factory name with the // provided args. Returns the unique UUID of the workflow. The // workflowpb.Workflow object is saved in the topo server after // creation.
[ "Create", "creates", "a", "workflow", "from", "the", "given", "factory", "name", "with", "the", "provided", "args", ".", "Returns", "the", "unique", "UUID", "of", "the", "workflow", ".", "The", "workflowpb", ".", "Workflow", "object", "is", "saved", "in", "the", "topo", "server", "after", "creation", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/manager.go#L246-L283
train
vitessio/vitess
go/vt/workflow/manager.go
Stop
func (m *Manager) Stop(ctx context.Context, uuid string) error { // Find the workflow, mark it as stopped. m.mu.Lock() rw, ok := m.workflows[uuid] if !ok { m.mu.Unlock() return fmt.Errorf("no running workflow with uuid %v", uuid) } rw.stopped = true m.mu.Unlock() // Cancel the running guy, and waits for it. rw.cancel() select { case <-rw.done: break case <-ctx.Done(): return ctx.Err() } return nil }
go
func (m *Manager) Stop(ctx context.Context, uuid string) error { // Find the workflow, mark it as stopped. m.mu.Lock() rw, ok := m.workflows[uuid] if !ok { m.mu.Unlock() return fmt.Errorf("no running workflow with uuid %v", uuid) } rw.stopped = true m.mu.Unlock() // Cancel the running guy, and waits for it. rw.cancel() select { case <-rw.done: break case <-ctx.Done(): return ctx.Err() } return nil }
[ "func", "(", "m", "*", "Manager", ")", "Stop", "(", "ctx", "context", ".", "Context", ",", "uuid", "string", ")", "error", "{", "// Find the workflow, mark it as stopped.", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "rw", ",", "ok", ":=", "m", ".", "workflows", "[", "uuid", "]", "\n", "if", "!", "ok", "{", "m", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "uuid", ")", "\n", "}", "\n", "rw", ".", "stopped", "=", "true", "\n", "m", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "// Cancel the running guy, and waits for it.", "rw", ".", "cancel", "(", ")", "\n", "select", "{", "case", "<-", "rw", ".", "done", ":", "break", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Stop stops the running workflow. It will cancel its context and // wait for it to exit.
[ "Stop", "stops", "the", "running", "workflow", ".", "It", "will", "cancel", "its", "context", "and", "wait", "for", "it", "to", "exit", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/manager.go#L416-L436
train
vitessio/vitess
go/vt/workflow/manager.go
Delete
func (m *Manager) Delete(ctx context.Context, uuid string) error { m.mu.Lock() defer m.mu.Unlock() rw, ok := m.workflows[uuid] if !ok { return fmt.Errorf("no workflow with uuid %v", uuid) } if rw.wi.State == workflowpb.WorkflowState_Running { return fmt.Errorf("cannot delete running workflow") } if err := m.ts.DeleteWorkflow(m.ctx, rw.wi); err != nil { log.Errorf("Could not delete workflow %v: %v", rw.wi, err) } m.nodeManager.RemoveRootNode(rw.rootNode) delete(m.workflows, uuid) return nil }
go
func (m *Manager) Delete(ctx context.Context, uuid string) error { m.mu.Lock() defer m.mu.Unlock() rw, ok := m.workflows[uuid] if !ok { return fmt.Errorf("no workflow with uuid %v", uuid) } if rw.wi.State == workflowpb.WorkflowState_Running { return fmt.Errorf("cannot delete running workflow") } if err := m.ts.DeleteWorkflow(m.ctx, rw.wi); err != nil { log.Errorf("Could not delete workflow %v: %v", rw.wi, err) } m.nodeManager.RemoveRootNode(rw.rootNode) delete(m.workflows, uuid) return nil }
[ "func", "(", "m", "*", "Manager", ")", "Delete", "(", "ctx", "context", ".", "Context", ",", "uuid", "string", ")", "error", "{", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "rw", ",", "ok", ":=", "m", ".", "workflows", "[", "uuid", "]", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "uuid", ")", "\n", "}", "\n", "if", "rw", ".", "wi", ".", "State", "==", "workflowpb", ".", "WorkflowState_Running", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "m", ".", "ts", ".", "DeleteWorkflow", "(", "m", ".", "ctx", ",", "rw", ".", "wi", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "rw", ".", "wi", ",", "err", ")", "\n", "}", "\n", "m", ".", "nodeManager", ".", "RemoveRootNode", "(", "rw", ".", "rootNode", ")", "\n", "delete", "(", "m", ".", "workflows", ",", "uuid", ")", "\n", "return", "nil", "\n", "}" ]
// Delete deletes the finished or not started workflow.
[ "Delete", "deletes", "the", "finished", "or", "not", "started", "workflow", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/manager.go#L439-L456
train
vitessio/vitess
go/vt/workflow/manager.go
Wait
func (m *Manager) Wait(ctx context.Context, uuid string) error { // Find the workflow. rw, err := m.runningWorkflow(uuid) if err != nil { return err } // Just wait for it. select { case <-rw.done: break case <-ctx.Done(): return ctx.Err() } return nil }
go
func (m *Manager) Wait(ctx context.Context, uuid string) error { // Find the workflow. rw, err := m.runningWorkflow(uuid) if err != nil { return err } // Just wait for it. select { case <-rw.done: break case <-ctx.Done(): return ctx.Err() } return nil }
[ "func", "(", "m", "*", "Manager", ")", "Wait", "(", "ctx", "context", ".", "Context", ",", "uuid", "string", ")", "error", "{", "// Find the workflow.", "rw", ",", "err", ":=", "m", ".", "runningWorkflow", "(", "uuid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Just wait for it.", "select", "{", "case", "<-", "rw", ".", "done", ":", "break", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Wait waits for the provided workflow to end.
[ "Wait", "waits", "for", "the", "provided", "workflow", "to", "end", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/manager.go#L459-L474
train
vitessio/vitess
go/vt/workflow/manager.go
runningWorkflow
func (m *Manager) runningWorkflow(uuid string) (*runningWorkflow, error) { m.mu.Lock() defer m.mu.Unlock() rw, ok := m.workflows[uuid] if !ok { return nil, fmt.Errorf("no running workflow with uuid %v", uuid) } return rw, nil }
go
func (m *Manager) runningWorkflow(uuid string) (*runningWorkflow, error) { m.mu.Lock() defer m.mu.Unlock() rw, ok := m.workflows[uuid] if !ok { return nil, fmt.Errorf("no running workflow with uuid %v", uuid) } return rw, nil }
[ "func", "(", "m", "*", "Manager", ")", "runningWorkflow", "(", "uuid", "string", ")", "(", "*", "runningWorkflow", ",", "error", ")", "{", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "rw", ",", "ok", ":=", "m", ".", "workflows", "[", "uuid", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "uuid", ")", "\n", "}", "\n", "return", "rw", ",", "nil", "\n", "}" ]
// runningWorkflow returns a runningWorkflow by uuid.
[ "runningWorkflow", "returns", "a", "runningWorkflow", "by", "uuid", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/manager.go#L498-L507
train
vitessio/vitess
go/vt/workflow/manager.go
Unregister
func Unregister(name string) { if _, ok := factories[name]; !ok { log.Warningf("workflow %v doesn't exist, cannot remove it", name) } else { delete(factories, name) } }
go
func Unregister(name string) { if _, ok := factories[name]; !ok { log.Warningf("workflow %v doesn't exist, cannot remove it", name) } else { delete(factories, name) } }
[ "func", "Unregister", "(", "name", "string", ")", "{", "if", "_", ",", "ok", ":=", "factories", "[", "name", "]", ";", "!", "ok", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "else", "{", "delete", "(", "factories", ",", "name", ")", "\n", "}", "\n", "}" ]
// Unregister removes a factory object. // Typically called from a flag to remove dangerous workflows.
[ "Unregister", "removes", "a", "factory", "object", ".", "Typically", "called", "from", "a", "flag", "to", "remove", "dangerous", "workflows", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/manager.go#L572-L578
train
vitessio/vitess
go/vt/workflow/manager.go
AvailableFactories
func AvailableFactories() map[string]bool { result := make(map[string]bool) for n := range factories { result[n] = true } return result }
go
func AvailableFactories() map[string]bool { result := make(map[string]bool) for n := range factories { result[n] = true } return result }
[ "func", "AvailableFactories", "(", ")", "map", "[", "string", "]", "bool", "{", "result", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "for", "n", ":=", "range", "factories", "{", "result", "[", "n", "]", "=", "true", "\n", "}", "\n", "return", "result", "\n", "}" ]
// AvailableFactories returns a map with the names of the available // factories as keys and 'true' as value.
[ "AvailableFactories", "returns", "a", "map", "with", "the", "names", "of", "the", "available", "factories", "as", "keys", "and", "true", "as", "value", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/manager.go#L582-L588
train
vitessio/vitess
go/vt/workflow/manager.go
StartManager
func StartManager(m *Manager) (*sync.WaitGroup, context.Context, context.CancelFunc) { ctx, cancel := context.WithCancel(context.Background()) wg := &sync.WaitGroup{} wg.Add(1) go func() { m.Run(ctx) wg.Done() }() m.WaitUntilRunning() return wg, ctx, cancel }
go
func StartManager(m *Manager) (*sync.WaitGroup, context.Context, context.CancelFunc) { ctx, cancel := context.WithCancel(context.Background()) wg := &sync.WaitGroup{} wg.Add(1) go func() { m.Run(ctx) wg.Done() }() m.WaitUntilRunning() return wg, ctx, cancel }
[ "func", "StartManager", "(", "m", "*", "Manager", ")", "(", "*", "sync", ".", "WaitGroup", ",", "context", ".", "Context", ",", "context", ".", "CancelFunc", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "context", ".", "Background", "(", ")", ")", "\n", "wg", ":=", "&", "sync", ".", "WaitGroup", "{", "}", "\n", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "m", ".", "Run", "(", "ctx", ")", "\n", "wg", ".", "Done", "(", ")", "\n", "}", "(", ")", "\n\n", "m", ".", "WaitUntilRunning", "(", ")", "\n\n", "return", "wg", ",", "ctx", ",", "cancel", "\n", "}" ]
// StartManager starts a manager. This function should only be used for tests purposes.
[ "StartManager", "starts", "a", "manager", ".", "This", "function", "should", "only", "be", "used", "for", "tests", "purposes", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/manager.go#L591-L603
train
vitessio/vitess
go/vt/worker/events/split_syslog.go
Syslog
func (ev *SplitClone) Syslog() (syslog.Priority, string) { return syslog.LOG_INFO, fmt.Sprintf("%s/%s/%s [split clone] %s", ev.Keyspace, ev.Shard, ev.Cell, ev.Status) }
go
func (ev *SplitClone) Syslog() (syslog.Priority, string) { return syslog.LOG_INFO, fmt.Sprintf("%s/%s/%s [split clone] %s", ev.Keyspace, ev.Shard, ev.Cell, ev.Status) }
[ "func", "(", "ev", "*", "SplitClone", ")", "Syslog", "(", ")", "(", "syslog", ".", "Priority", ",", "string", ")", "{", "return", "syslog", ".", "LOG_INFO", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ev", ".", "Keyspace", ",", "ev", ".", "Shard", ",", "ev", ".", "Cell", ",", "ev", ".", "Status", ")", "\n", "}" ]
// Syslog writes a SplitClone event to syslog.
[ "Syslog", "writes", "a", "SplitClone", "event", "to", "syslog", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/events/split_syslog.go#L27-L30
train
vitessio/vitess
go/vt/vttablet/tabletserver/query_executor.go
Stream
func (qre *QueryExecutor) Stream(callback func(*sqltypes.Result) error) error { qre.logStats.OriginalSQL = qre.query qre.logStats.PlanType = qre.plan.PlanID.String() defer func(start time.Time) { tabletenv.QueryStats.Record(qre.plan.PlanID.String(), start) tabletenv.RecordUserQuery(qre.ctx, qre.plan.TableName(), "Stream", int64(time.Since(start))) }(time.Now()) if err := qre.checkPermissions(); err != nil { return err } // if we have a transaction id, let's use the txPool for this query var conn *connpool.DBConn if qre.transactionID != 0 { txConn, err := qre.tsv.te.txPool.Get(qre.transactionID, "for streaming query") if err != nil { return err } defer txConn.Recycle() conn = txConn.DBConn } else { dbConn, err := qre.getStreamConn() if err != nil { return err } defer dbConn.Recycle() conn = dbConn } qd := NewQueryDetail(qre.logStats.Ctx, conn) qre.tsv.qe.streamQList.Add(qd) defer qre.tsv.qe.streamQList.Remove(qd) return qre.streamFetch(conn, qre.plan.FullQuery, qre.bindVars, "", callback) }
go
func (qre *QueryExecutor) Stream(callback func(*sqltypes.Result) error) error { qre.logStats.OriginalSQL = qre.query qre.logStats.PlanType = qre.plan.PlanID.String() defer func(start time.Time) { tabletenv.QueryStats.Record(qre.plan.PlanID.String(), start) tabletenv.RecordUserQuery(qre.ctx, qre.plan.TableName(), "Stream", int64(time.Since(start))) }(time.Now()) if err := qre.checkPermissions(); err != nil { return err } // if we have a transaction id, let's use the txPool for this query var conn *connpool.DBConn if qre.transactionID != 0 { txConn, err := qre.tsv.te.txPool.Get(qre.transactionID, "for streaming query") if err != nil { return err } defer txConn.Recycle() conn = txConn.DBConn } else { dbConn, err := qre.getStreamConn() if err != nil { return err } defer dbConn.Recycle() conn = dbConn } qd := NewQueryDetail(qre.logStats.Ctx, conn) qre.tsv.qe.streamQList.Add(qd) defer qre.tsv.qe.streamQList.Remove(qd) return qre.streamFetch(conn, qre.plan.FullQuery, qre.bindVars, "", callback) }
[ "func", "(", "qre", "*", "QueryExecutor", ")", "Stream", "(", "callback", "func", "(", "*", "sqltypes", ".", "Result", ")", "error", ")", "error", "{", "qre", ".", "logStats", ".", "OriginalSQL", "=", "qre", ".", "query", "\n", "qre", ".", "logStats", ".", "PlanType", "=", "qre", ".", "plan", ".", "PlanID", ".", "String", "(", ")", "\n\n", "defer", "func", "(", "start", "time", ".", "Time", ")", "{", "tabletenv", ".", "QueryStats", ".", "Record", "(", "qre", ".", "plan", ".", "PlanID", ".", "String", "(", ")", ",", "start", ")", "\n", "tabletenv", ".", "RecordUserQuery", "(", "qre", ".", "ctx", ",", "qre", ".", "plan", ".", "TableName", "(", ")", ",", "\"", "\"", ",", "int64", "(", "time", ".", "Since", "(", "start", ")", ")", ")", "\n", "}", "(", "time", ".", "Now", "(", ")", ")", "\n\n", "if", "err", ":=", "qre", ".", "checkPermissions", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// if we have a transaction id, let's use the txPool for this query", "var", "conn", "*", "connpool", ".", "DBConn", "\n", "if", "qre", ".", "transactionID", "!=", "0", "{", "txConn", ",", "err", ":=", "qre", ".", "tsv", ".", "te", ".", "txPool", ".", "Get", "(", "qre", ".", "transactionID", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "txConn", ".", "Recycle", "(", ")", "\n", "conn", "=", "txConn", ".", "DBConn", "\n", "}", "else", "{", "dbConn", ",", "err", ":=", "qre", ".", "getStreamConn", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "dbConn", ".", "Recycle", "(", ")", "\n", "conn", "=", "dbConn", "\n", "}", "\n\n", "qd", ":=", "NewQueryDetail", "(", "qre", ".", "logStats", ".", "Ctx", ",", "conn", ")", "\n", "qre", ".", "tsv", ".", "qe", ".", "streamQList", ".", "Add", "(", "qd", ")", "\n", "defer", "qre", ".", "tsv", ".", "qe", ".", "streamQList", ".", "Remove", "(", "qd", ")", "\n\n", "return", "qre", ".", "streamFetch", "(", "conn", ",", "qre", ".", "plan", ".", "FullQuery", ",", "qre", ".", "bindVars", ",", "\"", "\"", ",", "callback", ")", "\n", "}" ]
// Stream performs a streaming query execution.
[ "Stream", "performs", "a", "streaming", "query", "execution", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_executor.go#L204-L240
train
vitessio/vitess
go/vt/vttablet/tabletserver/query_executor.go
MessageStream
func (qre *QueryExecutor) MessageStream(callback func(*sqltypes.Result) error) error { qre.logStats.OriginalSQL = qre.query qre.logStats.PlanType = qre.plan.PlanID.String() defer func(start time.Time) { tabletenv.QueryStats.Record(qre.plan.PlanID.String(), start) tabletenv.RecordUserQuery(qre.ctx, qre.plan.TableName(), "MessageStream", int64(time.Since(start))) }(time.Now()) if err := qre.checkPermissions(); err != nil { return err } done, err := qre.tsv.messager.Subscribe(qre.ctx, qre.plan.TableName().String(), func(r *sqltypes.Result) error { select { case <-qre.ctx.Done(): return io.EOF default: } return callback(r) }) if err != nil { return err } <-done return nil }
go
func (qre *QueryExecutor) MessageStream(callback func(*sqltypes.Result) error) error { qre.logStats.OriginalSQL = qre.query qre.logStats.PlanType = qre.plan.PlanID.String() defer func(start time.Time) { tabletenv.QueryStats.Record(qre.plan.PlanID.String(), start) tabletenv.RecordUserQuery(qre.ctx, qre.plan.TableName(), "MessageStream", int64(time.Since(start))) }(time.Now()) if err := qre.checkPermissions(); err != nil { return err } done, err := qre.tsv.messager.Subscribe(qre.ctx, qre.plan.TableName().String(), func(r *sqltypes.Result) error { select { case <-qre.ctx.Done(): return io.EOF default: } return callback(r) }) if err != nil { return err } <-done return nil }
[ "func", "(", "qre", "*", "QueryExecutor", ")", "MessageStream", "(", "callback", "func", "(", "*", "sqltypes", ".", "Result", ")", "error", ")", "error", "{", "qre", ".", "logStats", ".", "OriginalSQL", "=", "qre", ".", "query", "\n", "qre", ".", "logStats", ".", "PlanType", "=", "qre", ".", "plan", ".", "PlanID", ".", "String", "(", ")", "\n\n", "defer", "func", "(", "start", "time", ".", "Time", ")", "{", "tabletenv", ".", "QueryStats", ".", "Record", "(", "qre", ".", "plan", ".", "PlanID", ".", "String", "(", ")", ",", "start", ")", "\n", "tabletenv", ".", "RecordUserQuery", "(", "qre", ".", "ctx", ",", "qre", ".", "plan", ".", "TableName", "(", ")", ",", "\"", "\"", ",", "int64", "(", "time", ".", "Since", "(", "start", ")", ")", ")", "\n", "}", "(", "time", ".", "Now", "(", ")", ")", "\n\n", "if", "err", ":=", "qre", ".", "checkPermissions", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "done", ",", "err", ":=", "qre", ".", "tsv", ".", "messager", ".", "Subscribe", "(", "qre", ".", "ctx", ",", "qre", ".", "plan", ".", "TableName", "(", ")", ".", "String", "(", ")", ",", "func", "(", "r", "*", "sqltypes", ".", "Result", ")", "error", "{", "select", "{", "case", "<-", "qre", ".", "ctx", ".", "Done", "(", ")", ":", "return", "io", ".", "EOF", "\n", "default", ":", "}", "\n", "return", "callback", "(", "r", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "<-", "done", "\n", "return", "nil", "\n", "}" ]
// MessageStream streams messages from a message table.
[ "MessageStream", "streams", "messages", "from", "a", "message", "table", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_executor.go#L243-L269
train
vitessio/vitess
go/vt/vttablet/tabletserver/query_executor.go
execDirect
func (qre *QueryExecutor) execDirect(conn *TxConnection) (*sqltypes.Result, error) { if qre.plan.Fields != nil { result, err := qre.txFetch(conn, qre.plan.FullQuery, qre.bindVars, nil, "", true, false) if err != nil { return nil, err } result.Fields = qre.plan.Fields return result, nil } return qre.txFetch(conn, qre.plan.FullQuery, qre.bindVars, nil, "", true, false) }
go
func (qre *QueryExecutor) execDirect(conn *TxConnection) (*sqltypes.Result, error) { if qre.plan.Fields != nil { result, err := qre.txFetch(conn, qre.plan.FullQuery, qre.bindVars, nil, "", true, false) if err != nil { return nil, err } result.Fields = qre.plan.Fields return result, nil } return qre.txFetch(conn, qre.plan.FullQuery, qre.bindVars, nil, "", true, false) }
[ "func", "(", "qre", "*", "QueryExecutor", ")", "execDirect", "(", "conn", "*", "TxConnection", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "if", "qre", ".", "plan", ".", "Fields", "!=", "nil", "{", "result", ",", "err", ":=", "qre", ".", "txFetch", "(", "conn", ",", "qre", ".", "plan", ".", "FullQuery", ",", "qre", ".", "bindVars", ",", "nil", ",", "\"", "\"", ",", "true", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "result", ".", "Fields", "=", "qre", ".", "plan", ".", "Fields", "\n", "return", "result", ",", "nil", "\n", "}", "\n", "return", "qre", ".", "txFetch", "(", "conn", ",", "qre", ".", "plan", ".", "FullQuery", ",", "qre", ".", "bindVars", ",", "nil", ",", "\"", "\"", ",", "true", ",", "false", ")", "\n", "}" ]
// execDirect is for reads inside transactions. Always send to MySQL.
[ "execDirect", "is", "for", "reads", "inside", "transactions", ".", "Always", "send", "to", "MySQL", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_executor.go#L523-L533
train
vitessio/vitess
go/vt/vttablet/tabletserver/query_executor.go
execSelect
func (qre *QueryExecutor) execSelect() (*sqltypes.Result, error) { if qre.plan.Fields != nil { result, err := qre.qFetch(qre.logStats, qre.plan.FullQuery, qre.bindVars) if err != nil { return nil, err } // result is read-only. So, let's copy it before modifying. newResult := *result newResult.Fields = qre.plan.Fields return &newResult, nil } conn, err := qre.getConn() if err != nil { return nil, err } defer conn.Recycle() return qre.dbConnFetch(conn, qre.plan.FullQuery, qre.bindVars, "", true) }
go
func (qre *QueryExecutor) execSelect() (*sqltypes.Result, error) { if qre.plan.Fields != nil { result, err := qre.qFetch(qre.logStats, qre.plan.FullQuery, qre.bindVars) if err != nil { return nil, err } // result is read-only. So, let's copy it before modifying. newResult := *result newResult.Fields = qre.plan.Fields return &newResult, nil } conn, err := qre.getConn() if err != nil { return nil, err } defer conn.Recycle() return qre.dbConnFetch(conn, qre.plan.FullQuery, qre.bindVars, "", true) }
[ "func", "(", "qre", "*", "QueryExecutor", ")", "execSelect", "(", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "if", "qre", ".", "plan", ".", "Fields", "!=", "nil", "{", "result", ",", "err", ":=", "qre", ".", "qFetch", "(", "qre", ".", "logStats", ",", "qre", ".", "plan", ".", "FullQuery", ",", "qre", ".", "bindVars", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// result is read-only. So, let's copy it before modifying.", "newResult", ":=", "*", "result", "\n", "newResult", ".", "Fields", "=", "qre", ".", "plan", ".", "Fields", "\n", "return", "&", "newResult", ",", "nil", "\n", "}", "\n", "conn", ",", "err", ":=", "qre", ".", "getConn", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "conn", ".", "Recycle", "(", ")", "\n", "return", "qre", ".", "dbConnFetch", "(", "conn", ",", "qre", ".", "plan", ".", "FullQuery", ",", "qre", ".", "bindVars", ",", "\"", "\"", ",", "true", ")", "\n", "}" ]
// execSelect sends a query to mysql only if another identical query is not running. Otherwise, it waits and // reuses the result. If the plan is missng field info, it sends the query to mysql requesting full info.
[ "execSelect", "sends", "a", "query", "to", "mysql", "only", "if", "another", "identical", "query", "is", "not", "running", ".", "Otherwise", "it", "waits", "and", "reuses", "the", "result", ".", "If", "the", "plan", "is", "missng", "field", "info", "it", "sends", "the", "query", "to", "mysql", "requesting", "full", "info", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_executor.go#L537-L554
train
vitessio/vitess
go/vt/vttablet/tabletserver/query_executor.go
txFetch
func (qre *QueryExecutor) txFetch(conn *TxConnection, parsedQuery *sqlparser.ParsedQuery, bindVars map[string]*querypb.BindVariable, extras map[string]sqlparser.Encodable, buildStreamComment string, wantfields, record bool) (*sqltypes.Result, error) { sql, _, err := qre.generateFinalSQL(parsedQuery, bindVars, extras, buildStreamComment) if err != nil { return nil, err } qr, err := qre.execSQL(conn, sql, wantfields) if err != nil { return nil, err } // Only record successful queries. if record { conn.RecordQuery(sql) } return qr, nil }
go
func (qre *QueryExecutor) txFetch(conn *TxConnection, parsedQuery *sqlparser.ParsedQuery, bindVars map[string]*querypb.BindVariable, extras map[string]sqlparser.Encodable, buildStreamComment string, wantfields, record bool) (*sqltypes.Result, error) { sql, _, err := qre.generateFinalSQL(parsedQuery, bindVars, extras, buildStreamComment) if err != nil { return nil, err } qr, err := qre.execSQL(conn, sql, wantfields) if err != nil { return nil, err } // Only record successful queries. if record { conn.RecordQuery(sql) } return qr, nil }
[ "func", "(", "qre", "*", "QueryExecutor", ")", "txFetch", "(", "conn", "*", "TxConnection", ",", "parsedQuery", "*", "sqlparser", ".", "ParsedQuery", ",", "bindVars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "extras", "map", "[", "string", "]", "sqlparser", ".", "Encodable", ",", "buildStreamComment", "string", ",", "wantfields", ",", "record", "bool", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "sql", ",", "_", ",", "err", ":=", "qre", ".", "generateFinalSQL", "(", "parsedQuery", ",", "bindVars", ",", "extras", ",", "buildStreamComment", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "qr", ",", "err", ":=", "qre", ".", "execSQL", "(", "conn", ",", "sql", ",", "wantfields", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// Only record successful queries.", "if", "record", "{", "conn", ".", "RecordQuery", "(", "sql", ")", "\n", "}", "\n", "return", "qr", ",", "nil", "\n", "}" ]
// txFetch fetches from a TxConnection.
[ "txFetch", "fetches", "from", "a", "TxConnection", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_executor.go#L861-L875
train
vitessio/vitess
go/vt/vttablet/tabletserver/query_executor.go
dbConnFetch
func (qre *QueryExecutor) dbConnFetch(conn *connpool.DBConn, parsedQuery *sqlparser.ParsedQuery, bindVars map[string]*querypb.BindVariable, buildStreamComment string, wantfields bool) (*sqltypes.Result, error) { sql, _, err := qre.generateFinalSQL(parsedQuery, bindVars, nil, buildStreamComment) if err != nil { return nil, err } return qre.execSQL(conn, sql, wantfields) }
go
func (qre *QueryExecutor) dbConnFetch(conn *connpool.DBConn, parsedQuery *sqlparser.ParsedQuery, bindVars map[string]*querypb.BindVariable, buildStreamComment string, wantfields bool) (*sqltypes.Result, error) { sql, _, err := qre.generateFinalSQL(parsedQuery, bindVars, nil, buildStreamComment) if err != nil { return nil, err } return qre.execSQL(conn, sql, wantfields) }
[ "func", "(", "qre", "*", "QueryExecutor", ")", "dbConnFetch", "(", "conn", "*", "connpool", ".", "DBConn", ",", "parsedQuery", "*", "sqlparser", ".", "ParsedQuery", ",", "bindVars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "buildStreamComment", "string", ",", "wantfields", "bool", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "sql", ",", "_", ",", "err", ":=", "qre", ".", "generateFinalSQL", "(", "parsedQuery", ",", "bindVars", ",", "nil", ",", "buildStreamComment", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "qre", ".", "execSQL", "(", "conn", ",", "sql", ",", "wantfields", ")", "\n", "}" ]
// dbConnFetch fetches from a connpool.DBConn.
[ "dbConnFetch", "fetches", "from", "a", "connpool", ".", "DBConn", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_executor.go#L878-L884
train
vitessio/vitess
go/vt/vttablet/tabletserver/query_executor.go
streamFetch
func (qre *QueryExecutor) streamFetch(conn *connpool.DBConn, parsedQuery *sqlparser.ParsedQuery, bindVars map[string]*querypb.BindVariable, buildStreamComment string, callback func(*sqltypes.Result) error) error { sql, _, err := qre.generateFinalSQL(parsedQuery, bindVars, nil, buildStreamComment) if err != nil { return err } return qre.execStreamSQL(conn, sql, callback) }
go
func (qre *QueryExecutor) streamFetch(conn *connpool.DBConn, parsedQuery *sqlparser.ParsedQuery, bindVars map[string]*querypb.BindVariable, buildStreamComment string, callback func(*sqltypes.Result) error) error { sql, _, err := qre.generateFinalSQL(parsedQuery, bindVars, nil, buildStreamComment) if err != nil { return err } return qre.execStreamSQL(conn, sql, callback) }
[ "func", "(", "qre", "*", "QueryExecutor", ")", "streamFetch", "(", "conn", "*", "connpool", ".", "DBConn", ",", "parsedQuery", "*", "sqlparser", ".", "ParsedQuery", ",", "bindVars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "buildStreamComment", "string", ",", "callback", "func", "(", "*", "sqltypes", ".", "Result", ")", "error", ")", "error", "{", "sql", ",", "_", ",", "err", ":=", "qre", ".", "generateFinalSQL", "(", "parsedQuery", ",", "bindVars", ",", "nil", ",", "buildStreamComment", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "qre", ".", "execStreamSQL", "(", "conn", ",", "sql", ",", "callback", ")", "\n", "}" ]
// streamFetch performs a streaming fetch.
[ "streamFetch", "performs", "a", "streaming", "fetch", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/query_executor.go#L887-L893
train
vitessio/vitess
go/vt/vtctl/fakevtctlclient/fakevtctlclient.go
FakeVtctlClientFactory
func (f *FakeVtctlClient) FakeVtctlClientFactory(addr string) (vtctlclient.VtctlClient, error) { return f, nil }
go
func (f *FakeVtctlClient) FakeVtctlClientFactory(addr string) (vtctlclient.VtctlClient, error) { return f, nil }
[ "func", "(", "f", "*", "FakeVtctlClient", ")", "FakeVtctlClientFactory", "(", "addr", "string", ")", "(", "vtctlclient", ".", "VtctlClient", ",", "error", ")", "{", "return", "f", ",", "nil", "\n", "}" ]
// FakeVtctlClientFactory always returns the current instance.
[ "FakeVtctlClientFactory", "always", "returns", "the", "current", "instance", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtctl/fakevtctlclient/fakevtctlclient.go#L41-L43
train
vitessio/vitess
go/vt/vtctl/fakevtctlclient/fakevtctlclient.go
ExecuteVtctlCommand
func (f *FakeVtctlClient) ExecuteVtctlCommand(ctx context.Context, args []string, actionTimeout time.Duration) (logutil.EventStream, error) { return f.FakeLoggerEventStreamingClient.StreamResult("" /* addr */, args) }
go
func (f *FakeVtctlClient) ExecuteVtctlCommand(ctx context.Context, args []string, actionTimeout time.Duration) (logutil.EventStream, error) { return f.FakeLoggerEventStreamingClient.StreamResult("" /* addr */, args) }
[ "func", "(", "f", "*", "FakeVtctlClient", ")", "ExecuteVtctlCommand", "(", "ctx", "context", ".", "Context", ",", "args", "[", "]", "string", ",", "actionTimeout", "time", ".", "Duration", ")", "(", "logutil", ".", "EventStream", ",", "error", ")", "{", "return", "f", ".", "FakeLoggerEventStreamingClient", ".", "StreamResult", "(", "\"", "\"", "/* addr */", ",", "args", ")", "\n", "}" ]
// ExecuteVtctlCommand is part of the vtctlclient interface.
[ "ExecuteVtctlCommand", "is", "part", "of", "the", "vtctlclient", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtctl/fakevtctlclient/fakevtctlclient.go#L46-L48
train
vitessio/vitess
go/vt/vttablet/tabletmanager/vreplication/replicator_plan.go
buildExecutionPlan
func (rp *ReplicatorPlan) buildExecutionPlan(fieldEvent *binlogdatapb.FieldEvent) (*TablePlan, error) { prelim := rp.TablePlans[fieldEvent.TableName] if prelim == nil { // Unreachable code. return nil, fmt.Errorf("plan not found for %s", fieldEvent.TableName) } if prelim.Insert != nil { tplanv := *prelim tplanv.Fields = fieldEvent.Fields return &tplanv, nil } // select * construct was used. We need to use the field names. tplan, err := rp.buildFromFields(prelim.TargetName, fieldEvent.Fields) if err != nil { return nil, err } tplan.Fields = fieldEvent.Fields return tplan, nil }
go
func (rp *ReplicatorPlan) buildExecutionPlan(fieldEvent *binlogdatapb.FieldEvent) (*TablePlan, error) { prelim := rp.TablePlans[fieldEvent.TableName] if prelim == nil { // Unreachable code. return nil, fmt.Errorf("plan not found for %s", fieldEvent.TableName) } if prelim.Insert != nil { tplanv := *prelim tplanv.Fields = fieldEvent.Fields return &tplanv, nil } // select * construct was used. We need to use the field names. tplan, err := rp.buildFromFields(prelim.TargetName, fieldEvent.Fields) if err != nil { return nil, err } tplan.Fields = fieldEvent.Fields return tplan, nil }
[ "func", "(", "rp", "*", "ReplicatorPlan", ")", "buildExecutionPlan", "(", "fieldEvent", "*", "binlogdatapb", ".", "FieldEvent", ")", "(", "*", "TablePlan", ",", "error", ")", "{", "prelim", ":=", "rp", ".", "TablePlans", "[", "fieldEvent", ".", "TableName", "]", "\n", "if", "prelim", "==", "nil", "{", "// Unreachable code.", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "fieldEvent", ".", "TableName", ")", "\n", "}", "\n", "if", "prelim", ".", "Insert", "!=", "nil", "{", "tplanv", ":=", "*", "prelim", "\n", "tplanv", ".", "Fields", "=", "fieldEvent", ".", "Fields", "\n", "return", "&", "tplanv", ",", "nil", "\n", "}", "\n", "// select * construct was used. We need to use the field names.", "tplan", ",", "err", ":=", "rp", ".", "buildFromFields", "(", "prelim", ".", "TargetName", ",", "fieldEvent", ".", "Fields", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "tplan", ".", "Fields", "=", "fieldEvent", ".", "Fields", "\n", "return", "tplan", ",", "nil", "\n", "}" ]
// buildExecution plan uses the field info as input and the partially built // TablePlan for that table to build a full plan.
[ "buildExecution", "plan", "uses", "the", "field", "info", "as", "input", "and", "the", "partially", "built", "TablePlan", "for", "that", "table", "to", "build", "a", "full", "plan", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/vreplication/replicator_plan.go#L47-L65
train
vitessio/vitess
go/vt/vttablet/tabletserver/queryz.go
MysqlTimePQ
func (qzs *queryzRow) MysqlTimePQ() string { val := float64(qzs.mysqlTime) / (1e9 * float64(qzs.Count)) return fmt.Sprintf("%.6f", val) }
go
func (qzs *queryzRow) MysqlTimePQ() string { val := float64(qzs.mysqlTime) / (1e9 * float64(qzs.Count)) return fmt.Sprintf("%.6f", val) }
[ "func", "(", "qzs", "*", "queryzRow", ")", "MysqlTimePQ", "(", ")", "string", "{", "val", ":=", "float64", "(", "qzs", ".", "mysqlTime", ")", "/", "(", "1e9", "*", "float64", "(", "qzs", ".", "Count", ")", ")", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "val", ")", "\n", "}" ]
// MysqlTimePQ returns the time per query as a string.
[ "MysqlTimePQ", "returns", "the", "time", "per", "query", "as", "a", "string", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/queryz.go#L106-L109
train
vitessio/vitess
go/vt/vttablet/tabletserver/queryz.go
RowsPQ
func (qzs *queryzRow) RowsPQ() string { val := float64(qzs.Rows) / float64(qzs.Count) return fmt.Sprintf("%.6f", val) }
go
func (qzs *queryzRow) RowsPQ() string { val := float64(qzs.Rows) / float64(qzs.Count) return fmt.Sprintf("%.6f", val) }
[ "func", "(", "qzs", "*", "queryzRow", ")", "RowsPQ", "(", ")", "string", "{", "val", ":=", "float64", "(", "qzs", ".", "Rows", ")", "/", "float64", "(", "qzs", ".", "Count", ")", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "val", ")", "\n", "}" ]
// RowsPQ returns the row count per query as a string.
[ "RowsPQ", "returns", "the", "row", "count", "per", "query", "as", "a", "string", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/queryz.go#L112-L115
train
vitessio/vitess
go/vt/vttablet/tabletserver/queryz.go
ErrorsPQ
func (qzs *queryzRow) ErrorsPQ() string { return fmt.Sprintf("%.6f", float64(qzs.Errors)/float64(qzs.Count)) }
go
func (qzs *queryzRow) ErrorsPQ() string { return fmt.Sprintf("%.6f", float64(qzs.Errors)/float64(qzs.Count)) }
[ "func", "(", "qzs", "*", "queryzRow", ")", "ErrorsPQ", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "float64", "(", "qzs", ".", "Errors", ")", "/", "float64", "(", "qzs", ".", "Count", ")", ")", "\n", "}" ]
// ErrorsPQ returns the error count per query as a string.
[ "ErrorsPQ", "returns", "the", "error", "count", "per", "query", "as", "a", "string", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/queryz.go#L118-L120
train
vitessio/vitess
go/vt/worker/table_status.go
format
func (t *tableStatusList) format() ([]string, time.Time) { if !t.isInitialized() { return nil, time.Now() } copiedRows := uint64(0) rowCount := uint64(0) result := make([]string, len(t.tableStatuses)) for i, ts := range t.tableStatuses { ts.mu.Lock() if ts.isView { // views are not copied result[i] = fmt.Sprintf("%v is a view", ts.name) } else if ts.threadsStarted == 0 { // we haven't started yet result[i] = fmt.Sprintf("%v: copy not started (estimating %v rows)", ts.name, ts.rowCount) } else if ts.threadsDone == ts.threadCount { // we are done with the copy result[i] = fmt.Sprintf("%v: copy done, processed %v rows", ts.name, ts.copiedRows) } else { // copy is running // Display 0% if rowCount is 0 because the actual number of rows can be > 0 // due to InnoDB's imperfect statistics. percentage := 0.0 if ts.rowCount > 0 { percentage = float64(ts.copiedRows) / float64(ts.rowCount) * 100.0 } result[i] = fmt.Sprintf("%v: copy running using %v threads (%v/%v rows processed, %.1f%%)", ts.name, ts.threadsStarted-ts.threadsDone, ts.copiedRows, ts.rowCount, percentage) } copiedRows += ts.copiedRows rowCount += ts.rowCount ts.mu.Unlock() } now := time.Now() if rowCount == 0 || copiedRows == 0 { return result, now } eta := now.Add(time.Duration(float64(now.Sub(t.startTime)) * float64(rowCount) / float64(copiedRows))) return result, eta }
go
func (t *tableStatusList) format() ([]string, time.Time) { if !t.isInitialized() { return nil, time.Now() } copiedRows := uint64(0) rowCount := uint64(0) result := make([]string, len(t.tableStatuses)) for i, ts := range t.tableStatuses { ts.mu.Lock() if ts.isView { // views are not copied result[i] = fmt.Sprintf("%v is a view", ts.name) } else if ts.threadsStarted == 0 { // we haven't started yet result[i] = fmt.Sprintf("%v: copy not started (estimating %v rows)", ts.name, ts.rowCount) } else if ts.threadsDone == ts.threadCount { // we are done with the copy result[i] = fmt.Sprintf("%v: copy done, processed %v rows", ts.name, ts.copiedRows) } else { // copy is running // Display 0% if rowCount is 0 because the actual number of rows can be > 0 // due to InnoDB's imperfect statistics. percentage := 0.0 if ts.rowCount > 0 { percentage = float64(ts.copiedRows) / float64(ts.rowCount) * 100.0 } result[i] = fmt.Sprintf("%v: copy running using %v threads (%v/%v rows processed, %.1f%%)", ts.name, ts.threadsStarted-ts.threadsDone, ts.copiedRows, ts.rowCount, percentage) } copiedRows += ts.copiedRows rowCount += ts.rowCount ts.mu.Unlock() } now := time.Now() if rowCount == 0 || copiedRows == 0 { return result, now } eta := now.Add(time.Duration(float64(now.Sub(t.startTime)) * float64(rowCount) / float64(copiedRows))) return result, eta }
[ "func", "(", "t", "*", "tableStatusList", ")", "format", "(", ")", "(", "[", "]", "string", ",", "time", ".", "Time", ")", "{", "if", "!", "t", ".", "isInitialized", "(", ")", "{", "return", "nil", ",", "time", ".", "Now", "(", ")", "\n", "}", "\n\n", "copiedRows", ":=", "uint64", "(", "0", ")", "\n", "rowCount", ":=", "uint64", "(", "0", ")", "\n", "result", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "t", ".", "tableStatuses", ")", ")", "\n", "for", "i", ",", "ts", ":=", "range", "t", ".", "tableStatuses", "{", "ts", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "ts", ".", "isView", "{", "// views are not copied", "result", "[", "i", "]", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ts", ".", "name", ")", "\n", "}", "else", "if", "ts", ".", "threadsStarted", "==", "0", "{", "// we haven't started yet", "result", "[", "i", "]", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ts", ".", "name", ",", "ts", ".", "rowCount", ")", "\n", "}", "else", "if", "ts", ".", "threadsDone", "==", "ts", ".", "threadCount", "{", "// we are done with the copy", "result", "[", "i", "]", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ts", ".", "name", ",", "ts", ".", "copiedRows", ")", "\n", "}", "else", "{", "// copy is running", "// Display 0% if rowCount is 0 because the actual number of rows can be > 0", "// due to InnoDB's imperfect statistics.", "percentage", ":=", "0.0", "\n", "if", "ts", ".", "rowCount", ">", "0", "{", "percentage", "=", "float64", "(", "ts", ".", "copiedRows", ")", "/", "float64", "(", "ts", ".", "rowCount", ")", "*", "100.0", "\n", "}", "\n", "result", "[", "i", "]", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ts", ".", "name", ",", "ts", ".", "threadsStarted", "-", "ts", ".", "threadsDone", ",", "ts", ".", "copiedRows", ",", "ts", ".", "rowCount", ",", "percentage", ")", "\n", "}", "\n", "copiedRows", "+=", "ts", ".", "copiedRows", "\n", "rowCount", "+=", "ts", ".", "rowCount", "\n", "ts", ".", "mu", ".", "Unlock", "(", ")", "\n", "}", "\n", "now", ":=", "time", ".", "Now", "(", ")", "\n", "if", "rowCount", "==", "0", "||", "copiedRows", "==", "0", "{", "return", "result", ",", "now", "\n", "}", "\n", "eta", ":=", "now", ".", "Add", "(", "time", ".", "Duration", "(", "float64", "(", "now", ".", "Sub", "(", "t", ".", "startTime", ")", ")", "*", "float64", "(", "rowCount", ")", "/", "float64", "(", "copiedRows", ")", ")", ")", "\n", "return", "result", ",", "eta", "\n", "}" ]
// format returns a status for each table and the overall ETA.
[ "format", "returns", "a", "status", "for", "each", "table", "and", "the", "overall", "ETA", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/table_status.go#L104-L143
train
vitessio/vitess
go/vt/workflow/checkpoint.go
NewCheckpointWriter
func NewCheckpointWriter(ts *topo.Server, checkpoint *workflowpb.WorkflowCheckpoint, wi *topo.WorkflowInfo) *CheckpointWriter { return &CheckpointWriter{ topoServer: ts, checkpoint: checkpoint, wi: wi, } }
go
func NewCheckpointWriter(ts *topo.Server, checkpoint *workflowpb.WorkflowCheckpoint, wi *topo.WorkflowInfo) *CheckpointWriter { return &CheckpointWriter{ topoServer: ts, checkpoint: checkpoint, wi: wi, } }
[ "func", "NewCheckpointWriter", "(", "ts", "*", "topo", ".", "Server", ",", "checkpoint", "*", "workflowpb", ".", "WorkflowCheckpoint", ",", "wi", "*", "topo", ".", "WorkflowInfo", ")", "*", "CheckpointWriter", "{", "return", "&", "CheckpointWriter", "{", "topoServer", ":", "ts", ",", "checkpoint", ":", "checkpoint", ",", "wi", ":", "wi", ",", "}", "\n", "}" ]
// NewCheckpointWriter creates a CheckpointWriter.
[ "NewCheckpointWriter", "creates", "a", "CheckpointWriter", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/checkpoint.go#L41-L47
train
vitessio/vitess
go/vt/workflow/checkpoint.go
UpdateTask
func (c *CheckpointWriter) UpdateTask(taskID string, status workflowpb.TaskState, err error) error { c.mu.Lock() defer c.mu.Unlock() errorMessage := "" if err != nil { errorMessage = err.Error() } t := c.checkpoint.Tasks[taskID] t.State = status t.Error = errorMessage return c.saveLocked() }
go
func (c *CheckpointWriter) UpdateTask(taskID string, status workflowpb.TaskState, err error) error { c.mu.Lock() defer c.mu.Unlock() errorMessage := "" if err != nil { errorMessage = err.Error() } t := c.checkpoint.Tasks[taskID] t.State = status t.Error = errorMessage return c.saveLocked() }
[ "func", "(", "c", "*", "CheckpointWriter", ")", "UpdateTask", "(", "taskID", "string", ",", "status", "workflowpb", ".", "TaskState", ",", "err", "error", ")", "error", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "errorMessage", ":=", "\"", "\"", "\n", "if", "err", "!=", "nil", "{", "errorMessage", "=", "err", ".", "Error", "(", ")", "\n", "}", "\n\n", "t", ":=", "c", ".", "checkpoint", ".", "Tasks", "[", "taskID", "]", "\n", "t", ".", "State", "=", "status", "\n", "t", ".", "Error", "=", "errorMessage", "\n", "return", "c", ".", "saveLocked", "(", ")", "\n", "}" ]
// UpdateTask updates the task status in the checkpointing copy and // saves the full checkpoint to the topology server.
[ "UpdateTask", "updates", "the", "task", "status", "in", "the", "checkpointing", "copy", "and", "saves", "the", "full", "checkpoint", "to", "the", "topology", "server", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/checkpoint.go#L51-L64
train
vitessio/vitess
go/vt/vttablet/customrule/topocustomrule/topocustomrule.go
activateTopoCustomRules
func activateTopoCustomRules(qsc tabletserver.Controller) { if *rulePath != "" { qsc.RegisterQueryRuleSource(topoCustomRuleSource) cr, err := newTopoCustomRule(qsc, *ruleCell, *rulePath) if err != nil { log.Fatalf("cannot start TopoCustomRule: %v", err) } cr.start() servenv.OnTerm(cr.stop) } }
go
func activateTopoCustomRules(qsc tabletserver.Controller) { if *rulePath != "" { qsc.RegisterQueryRuleSource(topoCustomRuleSource) cr, err := newTopoCustomRule(qsc, *ruleCell, *rulePath) if err != nil { log.Fatalf("cannot start TopoCustomRule: %v", err) } cr.start() servenv.OnTerm(cr.stop) } }
[ "func", "activateTopoCustomRules", "(", "qsc", "tabletserver", ".", "Controller", ")", "{", "if", "*", "rulePath", "!=", "\"", "\"", "{", "qsc", ".", "RegisterQueryRuleSource", "(", "topoCustomRuleSource", ")", "\n\n", "cr", ",", "err", ":=", "newTopoCustomRule", "(", "qsc", ",", "*", "ruleCell", ",", "*", "rulePath", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "cr", ".", "start", "(", ")", "\n\n", "servenv", ".", "OnTerm", "(", "cr", ".", "stop", ")", "\n", "}", "\n", "}" ]
// activateTopoCustomRules activates topo dynamic custom rule mechanism.
[ "activateTopoCustomRules", "activates", "topo", "dynamic", "custom", "rule", "mechanism", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/customrule/topocustomrule/topocustomrule.go#L189-L201
train
vitessio/vitess
go/vt/vtexplain/vtexplain_vttablet.go
CreateTransaction
func (t *explainTablet) CreateTransaction(ctx context.Context, target *querypb.Target, dtid string, participants []*querypb.Target) (err error) { t.mu.Lock() t.currentTime = batchTime.Wait() t.mu.Unlock() return t.tsv.CreateTransaction(ctx, target, dtid, participants) }
go
func (t *explainTablet) CreateTransaction(ctx context.Context, target *querypb.Target, dtid string, participants []*querypb.Target) (err error) { t.mu.Lock() t.currentTime = batchTime.Wait() t.mu.Unlock() return t.tsv.CreateTransaction(ctx, target, dtid, participants) }
[ "func", "(", "t", "*", "explainTablet", ")", "CreateTransaction", "(", "ctx", "context", ".", "Context", ",", "target", "*", "querypb", ".", "Target", ",", "dtid", "string", ",", "participants", "[", "]", "*", "querypb", ".", "Target", ")", "(", "err", "error", ")", "{", "t", ".", "mu", ".", "Lock", "(", ")", "\n", "t", ".", "currentTime", "=", "batchTime", ".", "Wait", "(", ")", "\n", "t", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "t", ".", "tsv", ".", "CreateTransaction", "(", "ctx", ",", "target", ",", "dtid", ",", "participants", ")", "\n", "}" ]
// CreateTransaction is part of the QueryService interface.
[ "CreateTransaction", "is", "part", "of", "the", "QueryService", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtexplain/vtexplain_vttablet.go#L186-L191
train
vitessio/vitess
go/vt/vtexplain/vtexplain_vttablet.go
Close
func (t *explainTablet) Close(ctx context.Context) error { return t.tsv.Close(ctx) }
go
func (t *explainTablet) Close(ctx context.Context) error { return t.tsv.Close(ctx) }
[ "func", "(", "t", "*", "explainTablet", ")", "Close", "(", "ctx", "context", ".", "Context", ")", "error", "{", "return", "t", ".", "tsv", ".", "Close", "(", "ctx", ")", "\n", "}" ]
// Close is part of the QueryService interface.
[ "Close", "is", "part", "of", "the", "QueryService", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtexplain/vtexplain_vttablet.go#L261-L263
train
vitessio/vitess
go/vt/discovery/topology_watcher.go
NewCellTabletsWatcher
func NewCellTabletsWatcher(ctx context.Context, topoServer *topo.Server, tr TabletRecorder, cell string, refreshInterval time.Duration, refreshKnownTablets bool, topoReadConcurrency int) *TopologyWatcher { return NewTopologyWatcher(ctx, topoServer, tr, cell, refreshInterval, refreshKnownTablets, topoReadConcurrency, func(tw *TopologyWatcher) ([]*topodatapb.TabletAlias, error) { return tw.topoServer.GetTabletsByCell(ctx, tw.cell) }) }
go
func NewCellTabletsWatcher(ctx context.Context, topoServer *topo.Server, tr TabletRecorder, cell string, refreshInterval time.Duration, refreshKnownTablets bool, topoReadConcurrency int) *TopologyWatcher { return NewTopologyWatcher(ctx, topoServer, tr, cell, refreshInterval, refreshKnownTablets, topoReadConcurrency, func(tw *TopologyWatcher) ([]*topodatapb.TabletAlias, error) { return tw.topoServer.GetTabletsByCell(ctx, tw.cell) }) }
[ "func", "NewCellTabletsWatcher", "(", "ctx", "context", ".", "Context", ",", "topoServer", "*", "topo", ".", "Server", ",", "tr", "TabletRecorder", ",", "cell", "string", ",", "refreshInterval", "time", ".", "Duration", ",", "refreshKnownTablets", "bool", ",", "topoReadConcurrency", "int", ")", "*", "TopologyWatcher", "{", "return", "NewTopologyWatcher", "(", "ctx", ",", "topoServer", ",", "tr", ",", "cell", ",", "refreshInterval", ",", "refreshKnownTablets", ",", "topoReadConcurrency", ",", "func", "(", "tw", "*", "TopologyWatcher", ")", "(", "[", "]", "*", "topodatapb", ".", "TabletAlias", ",", "error", ")", "{", "return", "tw", ".", "topoServer", ".", "GetTabletsByCell", "(", "ctx", ",", "tw", ".", "cell", ")", "\n", "}", ")", "\n", "}" ]
// NewCellTabletsWatcher returns a TopologyWatcher that monitors all // the tablets in a cell, and starts refreshing.
[ "NewCellTabletsWatcher", "returns", "a", "TopologyWatcher", "that", "monitors", "all", "the", "tablets", "in", "a", "cell", "and", "starts", "refreshing", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/topology_watcher.go#L72-L76
train
vitessio/vitess
go/vt/discovery/topology_watcher.go
NewTopologyWatcher
func NewTopologyWatcher(ctx context.Context, topoServer *topo.Server, tr TabletRecorder, cell string, refreshInterval time.Duration, refreshKnownTablets bool, topoReadConcurrency int, getTablets func(tw *TopologyWatcher) ([]*topodatapb.TabletAlias, error)) *TopologyWatcher { tw := &TopologyWatcher{ topoServer: topoServer, tr: tr, cell: cell, refreshInterval: refreshInterval, refreshKnownTablets: refreshKnownTablets, getTablets: getTablets, sem: make(chan int, topoReadConcurrency), tablets: make(map[string]*tabletInfo), } tw.firstLoadChan = make(chan struct{}) // We want the span from the context, but not the cancelation that comes with it spanContext := trace.CopySpan(context.Background(), ctx) tw.ctx, tw.cancelFunc = context.WithCancel(spanContext) tw.wg.Add(1) go tw.watch() return tw }
go
func NewTopologyWatcher(ctx context.Context, topoServer *topo.Server, tr TabletRecorder, cell string, refreshInterval time.Duration, refreshKnownTablets bool, topoReadConcurrency int, getTablets func(tw *TopologyWatcher) ([]*topodatapb.TabletAlias, error)) *TopologyWatcher { tw := &TopologyWatcher{ topoServer: topoServer, tr: tr, cell: cell, refreshInterval: refreshInterval, refreshKnownTablets: refreshKnownTablets, getTablets: getTablets, sem: make(chan int, topoReadConcurrency), tablets: make(map[string]*tabletInfo), } tw.firstLoadChan = make(chan struct{}) // We want the span from the context, but not the cancelation that comes with it spanContext := trace.CopySpan(context.Background(), ctx) tw.ctx, tw.cancelFunc = context.WithCancel(spanContext) tw.wg.Add(1) go tw.watch() return tw }
[ "func", "NewTopologyWatcher", "(", "ctx", "context", ".", "Context", ",", "topoServer", "*", "topo", ".", "Server", ",", "tr", "TabletRecorder", ",", "cell", "string", ",", "refreshInterval", "time", ".", "Duration", ",", "refreshKnownTablets", "bool", ",", "topoReadConcurrency", "int", ",", "getTablets", "func", "(", "tw", "*", "TopologyWatcher", ")", "(", "[", "]", "*", "topodatapb", ".", "TabletAlias", ",", "error", ")", ")", "*", "TopologyWatcher", "{", "tw", ":=", "&", "TopologyWatcher", "{", "topoServer", ":", "topoServer", ",", "tr", ":", "tr", ",", "cell", ":", "cell", ",", "refreshInterval", ":", "refreshInterval", ",", "refreshKnownTablets", ":", "refreshKnownTablets", ",", "getTablets", ":", "getTablets", ",", "sem", ":", "make", "(", "chan", "int", ",", "topoReadConcurrency", ")", ",", "tablets", ":", "make", "(", "map", "[", "string", "]", "*", "tabletInfo", ")", ",", "}", "\n", "tw", ".", "firstLoadChan", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n\n", "// We want the span from the context, but not the cancelation that comes with it", "spanContext", ":=", "trace", ".", "CopySpan", "(", "context", ".", "Background", "(", ")", ",", "ctx", ")", "\n", "tw", ".", "ctx", ",", "tw", ".", "cancelFunc", "=", "context", ".", "WithCancel", "(", "spanContext", ")", "\n", "tw", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "tw", ".", "watch", "(", ")", "\n", "return", "tw", "\n", "}" ]
// NewTopologyWatcher returns a TopologyWatcher that monitors all // the tablets in a cell, and starts refreshing.
[ "NewTopologyWatcher", "returns", "a", "TopologyWatcher", "that", "monitors", "all", "the", "tablets", "in", "a", "cell", "and", "starts", "refreshing", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/topology_watcher.go#L141-L160
train
vitessio/vitess
go/vt/discovery/topology_watcher.go
RefreshLag
func (tw *TopologyWatcher) RefreshLag() time.Duration { tw.mu.Lock() defer tw.mu.Unlock() return time.Since(tw.lastRefresh) }
go
func (tw *TopologyWatcher) RefreshLag() time.Duration { tw.mu.Lock() defer tw.mu.Unlock() return time.Since(tw.lastRefresh) }
[ "func", "(", "tw", "*", "TopologyWatcher", ")", "RefreshLag", "(", ")", "time", ".", "Duration", "{", "tw", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "tw", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "return", "time", ".", "Since", "(", "tw", ".", "lastRefresh", ")", "\n", "}" ]
// RefreshLag returns the time since the last refresh
[ "RefreshLag", "returns", "the", "time", "since", "the", "last", "refresh" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/topology_watcher.go#L323-L328
train
vitessio/vitess
go/vt/discovery/topology_watcher.go
TopoChecksum
func (tw *TopologyWatcher) TopoChecksum() uint32 { tw.mu.Lock() defer tw.mu.Unlock() return tw.topoChecksum }
go
func (tw *TopologyWatcher) TopoChecksum() uint32 { tw.mu.Lock() defer tw.mu.Unlock() return tw.topoChecksum }
[ "func", "(", "tw", "*", "TopologyWatcher", ")", "TopoChecksum", "(", ")", "uint32", "{", "tw", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "tw", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "return", "tw", ".", "topoChecksum", "\n", "}" ]
// TopoChecksum returns the checksum of the current state of the topo
[ "TopoChecksum", "returns", "the", "checksum", "of", "the", "current", "state", "of", "the", "topo" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/topology_watcher.go#L331-L336
train
vitessio/vitess
go/vt/discovery/topology_watcher.go
NewFilterByShard
func NewFilterByShard(tr TabletRecorder, filters []string) (*FilterByShard, error) { m := make(map[string][]*filterShard) for _, filter := range filters { parts := strings.Split(filter, "|") if len(parts) != 2 { return nil, fmt.Errorf("invalid FilterByShard parameter: %v", filter) } keyspace := parts[0] shard := parts[1] // extract keyrange if it's a range canonical, kr, err := topo.ValidateShardName(shard) if err != nil { return nil, fmt.Errorf("error parsing shard name %v: %v", shard, err) } // check for duplicates for _, c := range m[keyspace] { if c.shard == canonical { return nil, fmt.Errorf("duplicate %v/%v entry", keyspace, shard) } } m[keyspace] = append(m[keyspace], &filterShard{ keyspace: keyspace, shard: canonical, keyRange: kr, }) } return &FilterByShard{ tr: tr, filters: m, }, nil }
go
func NewFilterByShard(tr TabletRecorder, filters []string) (*FilterByShard, error) { m := make(map[string][]*filterShard) for _, filter := range filters { parts := strings.Split(filter, "|") if len(parts) != 2 { return nil, fmt.Errorf("invalid FilterByShard parameter: %v", filter) } keyspace := parts[0] shard := parts[1] // extract keyrange if it's a range canonical, kr, err := topo.ValidateShardName(shard) if err != nil { return nil, fmt.Errorf("error parsing shard name %v: %v", shard, err) } // check for duplicates for _, c := range m[keyspace] { if c.shard == canonical { return nil, fmt.Errorf("duplicate %v/%v entry", keyspace, shard) } } m[keyspace] = append(m[keyspace], &filterShard{ keyspace: keyspace, shard: canonical, keyRange: kr, }) } return &FilterByShard{ tr: tr, filters: m, }, nil }
[ "func", "NewFilterByShard", "(", "tr", "TabletRecorder", ",", "filters", "[", "]", "string", ")", "(", "*", "FilterByShard", ",", "error", ")", "{", "m", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "*", "filterShard", ")", "\n", "for", "_", ",", "filter", ":=", "range", "filters", "{", "parts", ":=", "strings", ".", "Split", "(", "filter", ",", "\"", "\"", ")", "\n", "if", "len", "(", "parts", ")", "!=", "2", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "filter", ")", "\n", "}", "\n\n", "keyspace", ":=", "parts", "[", "0", "]", "\n", "shard", ":=", "parts", "[", "1", "]", "\n\n", "// extract keyrange if it's a range", "canonical", ",", "kr", ",", "err", ":=", "topo", ".", "ValidateShardName", "(", "shard", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "shard", ",", "err", ")", "\n", "}", "\n\n", "// check for duplicates", "for", "_", ",", "c", ":=", "range", "m", "[", "keyspace", "]", "{", "if", "c", ".", "shard", "==", "canonical", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "keyspace", ",", "shard", ")", "\n", "}", "\n", "}", "\n\n", "m", "[", "keyspace", "]", "=", "append", "(", "m", "[", "keyspace", "]", ",", "&", "filterShard", "{", "keyspace", ":", "keyspace", ",", "shard", ":", "canonical", ",", "keyRange", ":", "kr", ",", "}", ")", "\n", "}", "\n\n", "return", "&", "FilterByShard", "{", "tr", ":", "tr", ",", "filters", ":", "m", ",", "}", ",", "nil", "\n", "}" ]
// NewFilterByShard creates a new FilterByShard on top of an existing // TabletRecorder. Each filter is a keyspace|shard entry, where shard // can either be a shard name, or a keyrange. All tablets that match // at least one keyspace|shard tuple will be forwarded to the // underlying TabletRecorder.
[ "NewFilterByShard", "creates", "a", "new", "FilterByShard", "on", "top", "of", "an", "existing", "TabletRecorder", ".", "Each", "filter", "is", "a", "keyspace|shard", "entry", "where", "shard", "can", "either", "be", "a", "shard", "name", "or", "a", "keyrange", ".", "All", "tablets", "that", "match", "at", "least", "one", "keyspace|shard", "tuple", "will", "be", "forwarded", "to", "the", "underlying", "TabletRecorder", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/topology_watcher.go#L361-L396
train
vitessio/vitess
go/vt/discovery/topology_watcher.go
AddTablet
func (fbs *FilterByShard) AddTablet(tablet *topodatapb.Tablet, name string) { if fbs.isIncluded(tablet) { fbs.tr.AddTablet(tablet, name) } }
go
func (fbs *FilterByShard) AddTablet(tablet *topodatapb.Tablet, name string) { if fbs.isIncluded(tablet) { fbs.tr.AddTablet(tablet, name) } }
[ "func", "(", "fbs", "*", "FilterByShard", ")", "AddTablet", "(", "tablet", "*", "topodatapb", ".", "Tablet", ",", "name", "string", ")", "{", "if", "fbs", ".", "isIncluded", "(", "tablet", ")", "{", "fbs", ".", "tr", ".", "AddTablet", "(", "tablet", ",", "name", ")", "\n", "}", "\n", "}" ]
// AddTablet is part of the TabletRecorder interface.
[ "AddTablet", "is", "part", "of", "the", "TabletRecorder", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/topology_watcher.go#L399-L403
train
vitessio/vitess
go/vt/discovery/topology_watcher.go
RemoveTablet
func (fbs *FilterByShard) RemoveTablet(tablet *topodatapb.Tablet) { if fbs.isIncluded(tablet) { fbs.tr.RemoveTablet(tablet) } }
go
func (fbs *FilterByShard) RemoveTablet(tablet *topodatapb.Tablet) { if fbs.isIncluded(tablet) { fbs.tr.RemoveTablet(tablet) } }
[ "func", "(", "fbs", "*", "FilterByShard", ")", "RemoveTablet", "(", "tablet", "*", "topodatapb", ".", "Tablet", ")", "{", "if", "fbs", ".", "isIncluded", "(", "tablet", ")", "{", "fbs", ".", "tr", ".", "RemoveTablet", "(", "tablet", ")", "\n", "}", "\n", "}" ]
// RemoveTablet is part of the TabletRecorder interface.
[ "RemoveTablet", "is", "part", "of", "the", "TabletRecorder", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/topology_watcher.go#L406-L410
train
vitessio/vitess
go/vt/discovery/topology_watcher.go
ReplaceTablet
func (fbs *FilterByShard) ReplaceTablet(old, new *topodatapb.Tablet, name string) { if fbs.isIncluded(old) && fbs.isIncluded(new) { fbs.tr.ReplaceTablet(old, new, name) } }
go
func (fbs *FilterByShard) ReplaceTablet(old, new *topodatapb.Tablet, name string) { if fbs.isIncluded(old) && fbs.isIncluded(new) { fbs.tr.ReplaceTablet(old, new, name) } }
[ "func", "(", "fbs", "*", "FilterByShard", ")", "ReplaceTablet", "(", "old", ",", "new", "*", "topodatapb", ".", "Tablet", ",", "name", "string", ")", "{", "if", "fbs", ".", "isIncluded", "(", "old", ")", "&&", "fbs", ".", "isIncluded", "(", "new", ")", "{", "fbs", ".", "tr", ".", "ReplaceTablet", "(", "old", ",", "new", ",", "name", ")", "\n", "}", "\n", "}" ]
// ReplaceTablet is part of the TabletRecorder interface.
[ "ReplaceTablet", "is", "part", "of", "the", "TabletRecorder", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/topology_watcher.go#L413-L417
train
vitessio/vitess
go/vt/discovery/topology_watcher.go
isIncluded
func (fbs *FilterByShard) isIncluded(tablet *topodatapb.Tablet) bool { canonical, kr, err := topo.ValidateShardName(tablet.Shard) if err != nil { log.Errorf("Error parsing shard name %v, will ignore tablet: %v", tablet.Shard, err) return false } for _, c := range fbs.filters[tablet.Keyspace] { if canonical == c.shard { // Exact match (probably a non-sharded keyspace). return true } if kr != nil && c.keyRange != nil && key.KeyRangeIncludes(c.keyRange, kr) { // Our filter's KeyRange includes the provided KeyRange return true } } return false }
go
func (fbs *FilterByShard) isIncluded(tablet *topodatapb.Tablet) bool { canonical, kr, err := topo.ValidateShardName(tablet.Shard) if err != nil { log.Errorf("Error parsing shard name %v, will ignore tablet: %v", tablet.Shard, err) return false } for _, c := range fbs.filters[tablet.Keyspace] { if canonical == c.shard { // Exact match (probably a non-sharded keyspace). return true } if kr != nil && c.keyRange != nil && key.KeyRangeIncludes(c.keyRange, kr) { // Our filter's KeyRange includes the provided KeyRange return true } } return false }
[ "func", "(", "fbs", "*", "FilterByShard", ")", "isIncluded", "(", "tablet", "*", "topodatapb", ".", "Tablet", ")", "bool", "{", "canonical", ",", "kr", ",", "err", ":=", "topo", ".", "ValidateShardName", "(", "tablet", ".", "Shard", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "tablet", ".", "Shard", ",", "err", ")", "\n", "return", "false", "\n", "}", "\n\n", "for", "_", ",", "c", ":=", "range", "fbs", ".", "filters", "[", "tablet", ".", "Keyspace", "]", "{", "if", "canonical", "==", "c", ".", "shard", "{", "// Exact match (probably a non-sharded keyspace).", "return", "true", "\n", "}", "\n", "if", "kr", "!=", "nil", "&&", "c", ".", "keyRange", "!=", "nil", "&&", "key", ".", "KeyRangeIncludes", "(", "c", ".", "keyRange", ",", "kr", ")", "{", "// Our filter's KeyRange includes the provided KeyRange", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isIncluded returns true iff the tablet's keyspace and shard should be // forwarded to the underlying TabletRecorder.
[ "isIncluded", "returns", "true", "iff", "the", "tablet", "s", "keyspace", "and", "shard", "should", "be", "forwarded", "to", "the", "underlying", "TabletRecorder", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/topology_watcher.go#L421-L439
train