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/bytes2/buffer.go
Write
func (buf *Buffer) Write(b []byte) (int, error) { buf.bytes = append(buf.bytes, b...) return len(b), nil }
go
func (buf *Buffer) Write(b []byte) (int, error) { buf.bytes = append(buf.bytes, b...) return len(b), nil }
[ "func", "(", "buf", "*", "Buffer", ")", "Write", "(", "b", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "buf", ".", "bytes", "=", "append", "(", "buf", ".", "bytes", ",", "b", "...", ")", "\n", "return", "len", "(", "b", ")", ",", "nil", "\n", "}" ]
// Write is equivalent to bytes.Buffer.Write.
[ "Write", "is", "equivalent", "to", "bytes", ".", "Buffer", ".", "Write", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/bytes2/buffer.go#L35-L38
train
vitessio/vitess
go/bytes2/buffer.go
WriteString
func (buf *Buffer) WriteString(s string) (int, error) { buf.bytes = append(buf.bytes, s...) return len(s), nil }
go
func (buf *Buffer) WriteString(s string) (int, error) { buf.bytes = append(buf.bytes, s...) return len(s), nil }
[ "func", "(", "buf", "*", "Buffer", ")", "WriteString", "(", "s", "string", ")", "(", "int", ",", "error", ")", "{", "buf", ".", "bytes", "=", "append", "(", "buf", ".", "bytes", ",", "s", "...", ")", "\n", "return", "len", "(", "s", ")", ",", "nil", "\n", "}" ]
// WriteString is equivalent to bytes.Buffer.WriteString.
[ "WriteString", "is", "equivalent", "to", "bytes", ".", "Buffer", ".", "WriteString", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/bytes2/buffer.go#L41-L44
train
vitessio/vitess
go/bytes2/buffer.go
WriteByte
func (buf *Buffer) WriteByte(b byte) error { buf.bytes = append(buf.bytes, b) return nil }
go
func (buf *Buffer) WriteByte(b byte) error { buf.bytes = append(buf.bytes, b) return nil }
[ "func", "(", "buf", "*", "Buffer", ")", "WriteByte", "(", "b", "byte", ")", "error", "{", "buf", ".", "bytes", "=", "append", "(", "buf", ".", "bytes", ",", "b", ")", "\n", "return", "nil", "\n", "}" ]
// WriteByte is equivalent to bytes.Buffer.WriteByte.
[ "WriteByte", "is", "equivalent", "to", "bytes", ".", "Buffer", ".", "WriteByte", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/bytes2/buffer.go#L47-L50
train
vitessio/vitess
go/vt/vterrors/vterrors.go
NewWithoutCode
func NewWithoutCode(message string) error { return &fundamental{ msg: message, code: vtrpcpb.Code_UNKNOWN, stack: callers(), } }
go
func NewWithoutCode(message string) error { return &fundamental{ msg: message, code: vtrpcpb.Code_UNKNOWN, stack: callers(), } }
[ "func", "NewWithoutCode", "(", "message", "string", ")", "error", "{", "return", "&", "fundamental", "{", "msg", ":", "message", ",", "code", ":", "vtrpcpb", ".", "Code_UNKNOWN", ",", "stack", ":", "callers", "(", ")", ",", "}", "\n", "}" ]
// NewWithoutCode returns an error when no applicable error code is available // It will record the stack trace when creating the error
[ "NewWithoutCode", "returns", "an", "error", "when", "no", "applicable", "error", "code", "is", "available", "It", "will", "record", "the", "stack", "trace", "when", "creating", "the", "error" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vterrors/vterrors.go#L101-L107
train
vitessio/vitess
go/vt/vterrors/vterrors.go
Code
func Code(err error) vtrpcpb.Code { if err == nil { return vtrpcpb.Code_OK } if err, ok := err.(*fundamental); ok { return err.code } cause := Cause(err) if cause != err && cause != nil { // If we did not find an error code at the outer level, let's find the cause and check it's code return Code(cause) } // Handle some special cases. switch err { case context.Canceled: return vtrpcpb.Code_CANCELED case context.DeadlineExceeded: return vtrpcpb.Code_DEADLINE_EXCEEDED } return vtrpcpb.Code_UNKNOWN }
go
func Code(err error) vtrpcpb.Code { if err == nil { return vtrpcpb.Code_OK } if err, ok := err.(*fundamental); ok { return err.code } cause := Cause(err) if cause != err && cause != nil { // If we did not find an error code at the outer level, let's find the cause and check it's code return Code(cause) } // Handle some special cases. switch err { case context.Canceled: return vtrpcpb.Code_CANCELED case context.DeadlineExceeded: return vtrpcpb.Code_DEADLINE_EXCEEDED } return vtrpcpb.Code_UNKNOWN }
[ "func", "Code", "(", "err", "error", ")", "vtrpcpb", ".", "Code", "{", "if", "err", "==", "nil", "{", "return", "vtrpcpb", ".", "Code_OK", "\n", "}", "\n", "if", "err", ",", "ok", ":=", "err", ".", "(", "*", "fundamental", ")", ";", "ok", "{", "return", "err", ".", "code", "\n", "}", "\n\n", "cause", ":=", "Cause", "(", "err", ")", "\n", "if", "cause", "!=", "err", "&&", "cause", "!=", "nil", "{", "// If we did not find an error code at the outer level, let's find the cause and check it's code", "return", "Code", "(", "cause", ")", "\n", "}", "\n\n", "// Handle some special cases.", "switch", "err", "{", "case", "context", ".", "Canceled", ":", "return", "vtrpcpb", ".", "Code_CANCELED", "\n", "case", "context", ".", "DeadlineExceeded", ":", "return", "vtrpcpb", ".", "Code_DEADLINE_EXCEEDED", "\n", "}", "\n", "return", "vtrpcpb", ".", "Code_UNKNOWN", "\n", "}" ]
// Code returns the error code if it's a vtError. // If err is nil, it returns ok.
[ "Code", "returns", "the", "error", "code", "if", "it", "s", "a", "vtError", ".", "If", "err", "is", "nil", "it", "returns", "ok", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vterrors/vterrors.go#L147-L169
train
vitessio/vitess
go/vt/vtgate/engine/pullout_subquery.go
Execute
func (ps *PulloutSubquery) Execute(vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool) (*sqltypes.Result, error) { combinedVars, err := ps.execSubquery(vcursor, bindVars) if err != nil { return nil, err } return ps.Underlying.Execute(vcursor, combinedVars, wantfields) }
go
func (ps *PulloutSubquery) Execute(vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool) (*sqltypes.Result, error) { combinedVars, err := ps.execSubquery(vcursor, bindVars) if err != nil { return nil, err } return ps.Underlying.Execute(vcursor, combinedVars, wantfields) }
[ "func", "(", "ps", "*", "PulloutSubquery", ")", "Execute", "(", "vcursor", "VCursor", ",", "bindVars", "map", "[", "string", "]", "*", "querypb", ".", "BindVariable", ",", "wantfields", "bool", ")", "(", "*", "sqltypes", ".", "Result", ",", "error", ")", "{", "combinedVars", ",", "err", ":=", "ps", ".", "execSubquery", "(", "vcursor", ",", "bindVars", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "ps", ".", "Underlying", ".", "Execute", "(", "vcursor", ",", "combinedVars", ",", "wantfields", ")", "\n", "}" ]
// Execute satisfies the Primitive interface.
[ "Execute", "satisfies", "the", "Primitive", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/engine/pullout_subquery.go#L47-L53
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
Init
func (*SwapWorkflowFactory) Init(_ *workflow.Manager, workflowProto *workflowpb.Workflow, args []string) error { subFlags := flag.NewFlagSet(workflowFactoryName, flag.ContinueOnError) keyspace := subFlags.String("keyspace", "", "Name of a keyspace to perform schema swap on") sql := subFlags.String("sql", "", "Query representing schema change being pushed by schema swap") if err := subFlags.Parse(args); err != nil { return err } if *keyspace == "" || *sql == "" { return fmt.Errorf("keyspace name and SQL query must be provided for schema swap") } workflowProto.Name = fmt.Sprintf("Schema swap on keyspace %s", *keyspace) data := &swapWorkflowData{ Keyspace: *keyspace, SQL: *sql, } var err error workflowProto.Data, err = json.Marshal(data) if err != nil { return err } return nil }
go
func (*SwapWorkflowFactory) Init(_ *workflow.Manager, workflowProto *workflowpb.Workflow, args []string) error { subFlags := flag.NewFlagSet(workflowFactoryName, flag.ContinueOnError) keyspace := subFlags.String("keyspace", "", "Name of a keyspace to perform schema swap on") sql := subFlags.String("sql", "", "Query representing schema change being pushed by schema swap") if err := subFlags.Parse(args); err != nil { return err } if *keyspace == "" || *sql == "" { return fmt.Errorf("keyspace name and SQL query must be provided for schema swap") } workflowProto.Name = fmt.Sprintf("Schema swap on keyspace %s", *keyspace) data := &swapWorkflowData{ Keyspace: *keyspace, SQL: *sql, } var err error workflowProto.Data, err = json.Marshal(data) if err != nil { return err } return nil }
[ "func", "(", "*", "SwapWorkflowFactory", ")", "Init", "(", "_", "*", "workflow", ".", "Manager", ",", "workflowProto", "*", "workflowpb", ".", "Workflow", ",", "args", "[", "]", "string", ")", "error", "{", "subFlags", ":=", "flag", ".", "NewFlagSet", "(", "workflowFactoryName", ",", "flag", ".", "ContinueOnError", ")", "\n\n", "keyspace", ":=", "subFlags", ".", "String", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "sql", ":=", "subFlags", ".", "String", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", ":=", "subFlags", ".", "Parse", "(", "args", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "*", "keyspace", "==", "\"", "\"", "||", "*", "sql", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "workflowProto", ".", "Name", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "*", "keyspace", ")", "\n", "data", ":=", "&", "swapWorkflowData", "{", "Keyspace", ":", "*", "keyspace", ",", "SQL", ":", "*", "sql", ",", "}", "\n", "var", "err", "error", "\n", "workflowProto", ".", "Data", ",", "err", "=", "json", ".", "Marshal", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Init is a part of workflow.Factory interface. It initializes a Workflow protobuf object.
[ "Init", "is", "a", "part", "of", "workflow", ".", "Factory", "interface", ".", "It", "initializes", "a", "Workflow", "protobuf", "object", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L182-L205
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
Instantiate
func (*SwapWorkflowFactory) Instantiate(_ *workflow.Manager, workflowProto *workflowpb.Workflow, rootNode *workflow.Node) (workflow.Workflow, error) { data := &swapWorkflowData{} if err := json.Unmarshal(workflowProto.Data, data); err != nil { return nil, err } rootNode.Message = fmt.Sprintf("Schema swap is executed on the keyspace %s", data.Keyspace) return &Swap{ keyspace: data.Keyspace, sql: data.SQL, rootUINode: rootNode, uiLogger: logutil.NewMemoryLogger(), }, nil }
go
func (*SwapWorkflowFactory) Instantiate(_ *workflow.Manager, workflowProto *workflowpb.Workflow, rootNode *workflow.Node) (workflow.Workflow, error) { data := &swapWorkflowData{} if err := json.Unmarshal(workflowProto.Data, data); err != nil { return nil, err } rootNode.Message = fmt.Sprintf("Schema swap is executed on the keyspace %s", data.Keyspace) return &Swap{ keyspace: data.Keyspace, sql: data.SQL, rootUINode: rootNode, uiLogger: logutil.NewMemoryLogger(), }, nil }
[ "func", "(", "*", "SwapWorkflowFactory", ")", "Instantiate", "(", "_", "*", "workflow", ".", "Manager", ",", "workflowProto", "*", "workflowpb", ".", "Workflow", ",", "rootNode", "*", "workflow", ".", "Node", ")", "(", "workflow", ".", "Workflow", ",", "error", ")", "{", "data", ":=", "&", "swapWorkflowData", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "workflowProto", ".", "Data", ",", "data", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "rootNode", ".", "Message", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "data", ".", "Keyspace", ")", "\n\n", "return", "&", "Swap", "{", "keyspace", ":", "data", ".", "Keyspace", ",", "sql", ":", "data", ".", "SQL", ",", "rootUINode", ":", "rootNode", ",", "uiLogger", ":", "logutil", ".", "NewMemoryLogger", "(", ")", ",", "}", ",", "nil", "\n", "}" ]
// Instantiate is a part of workflow.Factory interface. It instantiates workflow.Workflow object from // workflowpb.Workflow protobuf object.
[ "Instantiate", "is", "a", "part", "of", "workflow", ".", "Factory", "interface", ".", "It", "instantiates", "workflow", ".", "Workflow", "object", "from", "workflowpb", ".", "Workflow", "protobuf", "object", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L209-L222
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
Run
func (schemaSwap *Swap) Run(ctx context.Context, manager *workflow.Manager, workflowInfo *topo.WorkflowInfo) error { schemaSwap.ctx = ctx schemaSwap.workflowManager = manager schemaSwap.topoServer = manager.TopoServer() schemaSwap.tabletClient = tmclient.NewTabletManagerClient() log.Infof("Starting schema swap on keyspace %v with the following SQL: %v", schemaSwap.keyspace, schemaSwap.sql) for { err := schemaSwap.executeSwap() if err == nil { return nil } // If context is cancelled then return right away, otherwise move on to allow // user to retry. select { case <-schemaSwap.ctx.Done(): schemaSwap.setUIMessage(fmt.Sprintf("Error: %v", err)) return err default: } schemaSwap.retryMutex.Lock() retryAction := &workflow.Action{ Name: "Retry", State: workflow.ActionStateEnabled, Style: workflow.ActionStyleWaiting, } schemaSwap.rootUINode.Actions = []*workflow.Action{retryAction} schemaSwap.rootUINode.Listener = schemaSwap schemaSwap.retryChannel = make(chan struct{}) schemaSwap.retryMutex.Unlock() // setUIMessage broadcasts changes to rootUINode. schemaSwap.setUIMessage(fmt.Sprintf("Error: %v", err)) select { case <-schemaSwap.retryChannel: schemaSwap.setUIMessage("Retrying schema swap after an error") continue case <-schemaSwap.ctx.Done(): schemaSwap.closeRetryChannel() return schemaSwap.ctx.Err() } } }
go
func (schemaSwap *Swap) Run(ctx context.Context, manager *workflow.Manager, workflowInfo *topo.WorkflowInfo) error { schemaSwap.ctx = ctx schemaSwap.workflowManager = manager schemaSwap.topoServer = manager.TopoServer() schemaSwap.tabletClient = tmclient.NewTabletManagerClient() log.Infof("Starting schema swap on keyspace %v with the following SQL: %v", schemaSwap.keyspace, schemaSwap.sql) for { err := schemaSwap.executeSwap() if err == nil { return nil } // If context is cancelled then return right away, otherwise move on to allow // user to retry. select { case <-schemaSwap.ctx.Done(): schemaSwap.setUIMessage(fmt.Sprintf("Error: %v", err)) return err default: } schemaSwap.retryMutex.Lock() retryAction := &workflow.Action{ Name: "Retry", State: workflow.ActionStateEnabled, Style: workflow.ActionStyleWaiting, } schemaSwap.rootUINode.Actions = []*workflow.Action{retryAction} schemaSwap.rootUINode.Listener = schemaSwap schemaSwap.retryChannel = make(chan struct{}) schemaSwap.retryMutex.Unlock() // setUIMessage broadcasts changes to rootUINode. schemaSwap.setUIMessage(fmt.Sprintf("Error: %v", err)) select { case <-schemaSwap.retryChannel: schemaSwap.setUIMessage("Retrying schema swap after an error") continue case <-schemaSwap.ctx.Done(): schemaSwap.closeRetryChannel() return schemaSwap.ctx.Err() } } }
[ "func", "(", "schemaSwap", "*", "Swap", ")", "Run", "(", "ctx", "context", ".", "Context", ",", "manager", "*", "workflow", ".", "Manager", ",", "workflowInfo", "*", "topo", ".", "WorkflowInfo", ")", "error", "{", "schemaSwap", ".", "ctx", "=", "ctx", "\n", "schemaSwap", ".", "workflowManager", "=", "manager", "\n", "schemaSwap", ".", "topoServer", "=", "manager", ".", "TopoServer", "(", ")", "\n", "schemaSwap", ".", "tabletClient", "=", "tmclient", ".", "NewTabletManagerClient", "(", ")", "\n\n", "log", ".", "Infof", "(", "\"", "\"", ",", "schemaSwap", ".", "keyspace", ",", "schemaSwap", ".", "sql", ")", "\n\n", "for", "{", "err", ":=", "schemaSwap", ".", "executeSwap", "(", ")", "\n", "if", "err", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "// If context is cancelled then return right away, otherwise move on to allow", "// user to retry.", "select", "{", "case", "<-", "schemaSwap", ".", "ctx", ".", "Done", "(", ")", ":", "schemaSwap", ".", "setUIMessage", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "return", "err", "\n", "default", ":", "}", "\n\n", "schemaSwap", ".", "retryMutex", ".", "Lock", "(", ")", "\n", "retryAction", ":=", "&", "workflow", ".", "Action", "{", "Name", ":", "\"", "\"", ",", "State", ":", "workflow", ".", "ActionStateEnabled", ",", "Style", ":", "workflow", ".", "ActionStyleWaiting", ",", "}", "\n", "schemaSwap", ".", "rootUINode", ".", "Actions", "=", "[", "]", "*", "workflow", ".", "Action", "{", "retryAction", "}", "\n", "schemaSwap", ".", "rootUINode", ".", "Listener", "=", "schemaSwap", "\n", "schemaSwap", ".", "retryChannel", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "schemaSwap", ".", "retryMutex", ".", "Unlock", "(", ")", "\n", "// setUIMessage broadcasts changes to rootUINode.", "schemaSwap", ".", "setUIMessage", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n\n", "select", "{", "case", "<-", "schemaSwap", ".", "retryChannel", ":", "schemaSwap", ".", "setUIMessage", "(", "\"", "\"", ")", "\n", "continue", "\n", "case", "<-", "schemaSwap", ".", "ctx", ".", "Done", "(", ")", ":", "schemaSwap", ".", "closeRetryChannel", "(", ")", "\n", "return", "schemaSwap", ".", "ctx", ".", "Err", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Run is a part of workflow.Workflow interface. This is the main entrance point of the schema swap workflow.
[ "Run", "is", "a", "part", "of", "workflow", ".", "Workflow", "interface", ".", "This", "is", "the", "main", "entrance", "point", "of", "the", "schema", "swap", "workflow", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L225-L269
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
closeRetryChannel
func (schemaSwap *Swap) closeRetryChannel() { schemaSwap.retryMutex.Lock() defer schemaSwap.retryMutex.Unlock() if len(schemaSwap.rootUINode.Actions) != 0 { schemaSwap.rootUINode.Actions = []*workflow.Action{} close(schemaSwap.retryChannel) } }
go
func (schemaSwap *Swap) closeRetryChannel() { schemaSwap.retryMutex.Lock() defer schemaSwap.retryMutex.Unlock() if len(schemaSwap.rootUINode.Actions) != 0 { schemaSwap.rootUINode.Actions = []*workflow.Action{} close(schemaSwap.retryChannel) } }
[ "func", "(", "schemaSwap", "*", "Swap", ")", "closeRetryChannel", "(", ")", "{", "schemaSwap", ".", "retryMutex", ".", "Lock", "(", ")", "\n", "defer", "schemaSwap", ".", "retryMutex", ".", "Unlock", "(", ")", "\n\n", "if", "len", "(", "schemaSwap", ".", "rootUINode", ".", "Actions", ")", "!=", "0", "{", "schemaSwap", ".", "rootUINode", ".", "Actions", "=", "[", "]", "*", "workflow", ".", "Action", "{", "}", "\n", "close", "(", "schemaSwap", ".", "retryChannel", ")", "\n", "}", "\n", "}" ]
// closeRetryChannel closes the retryChannel and empties the Actions list in the rootUINode // to indicate that the channel is closed and Retry action is not waited for anymore.
[ "closeRetryChannel", "closes", "the", "retryChannel", "and", "empties", "the", "Actions", "list", "in", "the", "rootUINode", "to", "indicate", "that", "the", "channel", "is", "closed", "and", "Retry", "action", "is", "not", "waited", "for", "anymore", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L273-L281
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
Action
func (schemaSwap *Swap) Action(ctx context.Context, path, name string) error { if name != "Retry" { return fmt.Errorf("unknown action on schema swap: %v", name) } schemaSwap.closeRetryChannel() schemaSwap.rootUINode.BroadcastChanges(false /* updateChildren */) return nil }
go
func (schemaSwap *Swap) Action(ctx context.Context, path, name string) error { if name != "Retry" { return fmt.Errorf("unknown action on schema swap: %v", name) } schemaSwap.closeRetryChannel() schemaSwap.rootUINode.BroadcastChanges(false /* updateChildren */) return nil }
[ "func", "(", "schemaSwap", "*", "Swap", ")", "Action", "(", "ctx", "context", ".", "Context", ",", "path", ",", "name", "string", ")", "error", "{", "if", "name", "!=", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "schemaSwap", ".", "closeRetryChannel", "(", ")", "\n", "schemaSwap", ".", "rootUINode", ".", "BroadcastChanges", "(", "false", "/* updateChildren */", ")", "\n", "return", "nil", "\n", "}" ]
// Action is a part of workflow.ActionListener interface. It registers "Retry" actions // from UI.
[ "Action", "is", "a", "part", "of", "workflow", ".", "ActionListener", "interface", ".", "It", "registers", "Retry", "actions", "from", "UI", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L285-L292
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
executeSwap
func (schemaSwap *Swap) executeSwap() error { schemaSwap.setUIMessage("Initializing schema swap") if len(schemaSwap.allShards) == 0 { if err := schemaSwap.createShardObjects(); err != nil { return err } schemaSwap.rootUINode.BroadcastChanges(true /* updateChildren */) } if err := schemaSwap.initializeSwap(); err != nil { return err } errHealthWatchers := schemaSwap.runOnAllShards( func(shard *shardSchemaSwap) error { return shard.startHealthWatchers(schemaSwap.ctx) }) // Note: this defer statement is before the error is checked because some shards may // succeed while others fail. We should try to stop health watching on all shards no // matter if there was some failure or not. defer schemaSwap.stopAllHealthWatchers() if errHealthWatchers != nil { return errHealthWatchers } schemaSwap.setUIMessage("Applying schema change on seed tablets") err := schemaSwap.runOnAllShards( func(shard *shardSchemaSwap) error { shard.setShardInProgress(true) err := shard.applySeedSchemaChange() shard.setShardInProgress(false) return err }) if err != nil { return err } schemaSwap.setUIMessage("Taking seed backups") err = schemaSwap.runOnAllShards( func(shard *shardSchemaSwap) error { shard.setShardInProgress(true) err := shard.takeSeedBackup() shard.setShardInProgress(false) return err }) if err != nil { return err } schemaSwap.setUIMessage("Propagating backups to non-master tablets") err = schemaSwap.runOnAllShards( func(shard *shardSchemaSwap) error { shard.setShardInProgress(true) err := shard.propagateToAllTablets(false /* withMasterReparent */) shard.setShardInProgress(false) return err }) if err != nil { return err } schemaSwap.setUIMessage("Propagating backups to master tablets") err = schemaSwap.runOnAllShards( func(shard *shardSchemaSwap) error { shard.setShardInProgress(true) err := shard.propagateToAllTablets(true /* withMasterReparent */) shard.setShardInProgress(false) return err }) if err != nil { return err } schemaSwap.setUIMessage("Finalizing schema swap") err = schemaSwap.finalizeSwap() if err != nil { return err } for _, shard := range schemaSwap.allShards { shard.shardUINode.State = workflowpb.WorkflowState_Done } schemaSwap.rootUINode.BroadcastChanges(true /* updateChildren */) schemaSwap.setUIMessage("Schema swap is finished") return nil }
go
func (schemaSwap *Swap) executeSwap() error { schemaSwap.setUIMessage("Initializing schema swap") if len(schemaSwap.allShards) == 0 { if err := schemaSwap.createShardObjects(); err != nil { return err } schemaSwap.rootUINode.BroadcastChanges(true /* updateChildren */) } if err := schemaSwap.initializeSwap(); err != nil { return err } errHealthWatchers := schemaSwap.runOnAllShards( func(shard *shardSchemaSwap) error { return shard.startHealthWatchers(schemaSwap.ctx) }) // Note: this defer statement is before the error is checked because some shards may // succeed while others fail. We should try to stop health watching on all shards no // matter if there was some failure or not. defer schemaSwap.stopAllHealthWatchers() if errHealthWatchers != nil { return errHealthWatchers } schemaSwap.setUIMessage("Applying schema change on seed tablets") err := schemaSwap.runOnAllShards( func(shard *shardSchemaSwap) error { shard.setShardInProgress(true) err := shard.applySeedSchemaChange() shard.setShardInProgress(false) return err }) if err != nil { return err } schemaSwap.setUIMessage("Taking seed backups") err = schemaSwap.runOnAllShards( func(shard *shardSchemaSwap) error { shard.setShardInProgress(true) err := shard.takeSeedBackup() shard.setShardInProgress(false) return err }) if err != nil { return err } schemaSwap.setUIMessage("Propagating backups to non-master tablets") err = schemaSwap.runOnAllShards( func(shard *shardSchemaSwap) error { shard.setShardInProgress(true) err := shard.propagateToAllTablets(false /* withMasterReparent */) shard.setShardInProgress(false) return err }) if err != nil { return err } schemaSwap.setUIMessage("Propagating backups to master tablets") err = schemaSwap.runOnAllShards( func(shard *shardSchemaSwap) error { shard.setShardInProgress(true) err := shard.propagateToAllTablets(true /* withMasterReparent */) shard.setShardInProgress(false) return err }) if err != nil { return err } schemaSwap.setUIMessage("Finalizing schema swap") err = schemaSwap.finalizeSwap() if err != nil { return err } for _, shard := range schemaSwap.allShards { shard.shardUINode.State = workflowpb.WorkflowState_Done } schemaSwap.rootUINode.BroadcastChanges(true /* updateChildren */) schemaSwap.setUIMessage("Schema swap is finished") return nil }
[ "func", "(", "schemaSwap", "*", "Swap", ")", "executeSwap", "(", ")", "error", "{", "schemaSwap", ".", "setUIMessage", "(", "\"", "\"", ")", "\n", "if", "len", "(", "schemaSwap", ".", "allShards", ")", "==", "0", "{", "if", "err", ":=", "schemaSwap", ".", "createShardObjects", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "schemaSwap", ".", "rootUINode", ".", "BroadcastChanges", "(", "true", "/* updateChildren */", ")", "\n", "}", "\n", "if", "err", ":=", "schemaSwap", ".", "initializeSwap", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "errHealthWatchers", ":=", "schemaSwap", ".", "runOnAllShards", "(", "func", "(", "shard", "*", "shardSchemaSwap", ")", "error", "{", "return", "shard", ".", "startHealthWatchers", "(", "schemaSwap", ".", "ctx", ")", "\n", "}", ")", "\n", "// Note: this defer statement is before the error is checked because some shards may", "// succeed while others fail. We should try to stop health watching on all shards no", "// matter if there was some failure or not.", "defer", "schemaSwap", ".", "stopAllHealthWatchers", "(", ")", "\n", "if", "errHealthWatchers", "!=", "nil", "{", "return", "errHealthWatchers", "\n", "}", "\n\n", "schemaSwap", ".", "setUIMessage", "(", "\"", "\"", ")", "\n", "err", ":=", "schemaSwap", ".", "runOnAllShards", "(", "func", "(", "shard", "*", "shardSchemaSwap", ")", "error", "{", "shard", ".", "setShardInProgress", "(", "true", ")", "\n", "err", ":=", "shard", ".", "applySeedSchemaChange", "(", ")", "\n", "shard", ".", "setShardInProgress", "(", "false", ")", "\n", "return", "err", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "schemaSwap", ".", "setUIMessage", "(", "\"", "\"", ")", "\n", "err", "=", "schemaSwap", ".", "runOnAllShards", "(", "func", "(", "shard", "*", "shardSchemaSwap", ")", "error", "{", "shard", ".", "setShardInProgress", "(", "true", ")", "\n", "err", ":=", "shard", ".", "takeSeedBackup", "(", ")", "\n", "shard", ".", "setShardInProgress", "(", "false", ")", "\n", "return", "err", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "schemaSwap", ".", "setUIMessage", "(", "\"", "\"", ")", "\n", "err", "=", "schemaSwap", ".", "runOnAllShards", "(", "func", "(", "shard", "*", "shardSchemaSwap", ")", "error", "{", "shard", ".", "setShardInProgress", "(", "true", ")", "\n", "err", ":=", "shard", ".", "propagateToAllTablets", "(", "false", "/* withMasterReparent */", ")", "\n", "shard", ".", "setShardInProgress", "(", "false", ")", "\n", "return", "err", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "schemaSwap", ".", "setUIMessage", "(", "\"", "\"", ")", "\n", "err", "=", "schemaSwap", ".", "runOnAllShards", "(", "func", "(", "shard", "*", "shardSchemaSwap", ")", "error", "{", "shard", ".", "setShardInProgress", "(", "true", ")", "\n", "err", ":=", "shard", ".", "propagateToAllTablets", "(", "true", "/* withMasterReparent */", ")", "\n", "shard", ".", "setShardInProgress", "(", "false", ")", "\n", "return", "err", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "schemaSwap", ".", "setUIMessage", "(", "\"", "\"", ")", "\n", "err", "=", "schemaSwap", ".", "finalizeSwap", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "shard", ":=", "range", "schemaSwap", ".", "allShards", "{", "shard", ".", "shardUINode", ".", "State", "=", "workflowpb", ".", "WorkflowState_Done", "\n", "}", "\n", "schemaSwap", ".", "rootUINode", ".", "BroadcastChanges", "(", "true", "/* updateChildren */", ")", "\n", "schemaSwap", ".", "setUIMessage", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}" ]
// executeSwap is the main entry point of the schema swap process. It drives the process from start // to finish, including possible restart of already started process. In the latter case the // method should be just called again and it will pick up already started process. The only // input argument is the SQL statements that comprise the schema change that needs to be // pushed using the schema swap process.
[ "executeSwap", "is", "the", "main", "entry", "point", "of", "the", "schema", "swap", "process", ".", "It", "drives", "the", "process", "from", "start", "to", "finish", "including", "possible", "restart", "of", "already", "started", "process", ".", "In", "the", "latter", "case", "the", "method", "should", "be", "just", "called", "again", "and", "it", "will", "pick", "up", "already", "started", "process", ".", "The", "only", "input", "argument", "is", "the", "SQL", "statements", "that", "comprise", "the", "schema", "change", "that", "needs", "to", "be", "pushed", "using", "the", "schema", "swap", "process", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L299-L377
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
setUIMessage
func (schemaSwap *Swap) setUIMessage(message string) { log.Infof("Schema swap on keyspace %v: %v", schemaSwap.keyspace, message) schemaSwap.uiLogger.Infof(message) schemaSwap.rootUINode.Log = schemaSwap.uiLogger.String() schemaSwap.rootUINode.Message = message schemaSwap.rootUINode.BroadcastChanges(false /* updateChildren */) }
go
func (schemaSwap *Swap) setUIMessage(message string) { log.Infof("Schema swap on keyspace %v: %v", schemaSwap.keyspace, message) schemaSwap.uiLogger.Infof(message) schemaSwap.rootUINode.Log = schemaSwap.uiLogger.String() schemaSwap.rootUINode.Message = message schemaSwap.rootUINode.BroadcastChanges(false /* updateChildren */) }
[ "func", "(", "schemaSwap", "*", "Swap", ")", "setUIMessage", "(", "message", "string", ")", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "schemaSwap", ".", "keyspace", ",", "message", ")", "\n", "schemaSwap", ".", "uiLogger", ".", "Infof", "(", "message", ")", "\n", "schemaSwap", ".", "rootUINode", ".", "Log", "=", "schemaSwap", ".", "uiLogger", ".", "String", "(", ")", "\n", "schemaSwap", ".", "rootUINode", ".", "Message", "=", "message", "\n", "schemaSwap", ".", "rootUINode", ".", "BroadcastChanges", "(", "false", "/* updateChildren */", ")", "\n", "}" ]
// setUIMessage updates message on the schema swap's root UI node and broadcasts changes.
[ "setUIMessage", "updates", "message", "on", "the", "schema", "swap", "s", "root", "UI", "node", "and", "broadcasts", "changes", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L380-L386
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
runOnAllShards
func (schemaSwap *Swap) runOnAllShards(shardFunc func(shard *shardSchemaSwap) error) error { var errorRecorder concurrency.AllErrorRecorder var waitGroup sync.WaitGroup for _, shardSwap := range schemaSwap.allShards { waitGroup.Add(1) go func(shard *shardSchemaSwap) { defer waitGroup.Done() errorRecorder.RecordError(shardFunc(shard)) }(shardSwap) } waitGroup.Wait() return errorRecorder.Error() }
go
func (schemaSwap *Swap) runOnAllShards(shardFunc func(shard *shardSchemaSwap) error) error { var errorRecorder concurrency.AllErrorRecorder var waitGroup sync.WaitGroup for _, shardSwap := range schemaSwap.allShards { waitGroup.Add(1) go func(shard *shardSchemaSwap) { defer waitGroup.Done() errorRecorder.RecordError(shardFunc(shard)) }(shardSwap) } waitGroup.Wait() return errorRecorder.Error() }
[ "func", "(", "schemaSwap", "*", "Swap", ")", "runOnAllShards", "(", "shardFunc", "func", "(", "shard", "*", "shardSchemaSwap", ")", "error", ")", "error", "{", "var", "errorRecorder", "concurrency", ".", "AllErrorRecorder", "\n", "var", "waitGroup", "sync", ".", "WaitGroup", "\n", "for", "_", ",", "shardSwap", ":=", "range", "schemaSwap", ".", "allShards", "{", "waitGroup", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "shard", "*", "shardSchemaSwap", ")", "{", "defer", "waitGroup", ".", "Done", "(", ")", "\n", "errorRecorder", ".", "RecordError", "(", "shardFunc", "(", "shard", ")", ")", "\n", "}", "(", "shardSwap", ")", "\n", "}", "\n", "waitGroup", ".", "Wait", "(", ")", "\n", "return", "errorRecorder", ".", "Error", "(", ")", "\n", "}" ]
// runOnAllShards is a helper method that executes the passed function for all shards in parallel. // The method returns no error if the function succeeds on all shards. If on any of the shards // the function fails then the method returns error. If several shards return error then only one // of them is returned.
[ "runOnAllShards", "is", "a", "helper", "method", "that", "executes", "the", "passed", "function", "for", "all", "shards", "in", "parallel", ".", "The", "method", "returns", "no", "error", "if", "the", "function", "succeeds", "on", "all", "shards", ".", "If", "on", "any", "of", "the", "shards", "the", "function", "fails", "then", "the", "method", "returns", "error", ".", "If", "several", "shards", "return", "error", "then", "only", "one", "of", "them", "is", "returned", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L392-L404
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
createShardObjects
func (schemaSwap *Swap) createShardObjects() error { shardsList, err := schemaSwap.topoServer.FindAllShardsInKeyspace(schemaSwap.ctx, schemaSwap.keyspace) if err != nil { return err } for _, shardInfo := range shardsList { shardSwap := &shardSchemaSwap{ parent: schemaSwap, shardName: shardInfo.ShardName(), shardUINode: &workflow.Node{ Name: fmt.Sprintf("Shard %v", shardInfo.ShardName()), PathName: shardInfo.ShardName(), State: workflowpb.WorkflowState_Running, }, applySchemaUINode: &workflow.Node{ Name: "Apply schema on seed tablet", PathName: "apply_schema", }, backupUINode: &workflow.Node{ Name: "Take seed backup", PathName: "backup", }, propagationUINode: &workflow.Node{ Name: "Propagate backup", PathName: "propagate", }, reparentUINode: &workflow.Node{ Name: "Reparent from old master", PathName: "reparent", }, shardUILogger: logutil.NewMemoryLogger(), propagationUILogger: logutil.NewMemoryLogger(), } schemaSwap.rootUINode.Children = append(schemaSwap.rootUINode.Children, shardSwap.shardUINode) shardSwap.shardUINode.Children = []*workflow.Node{ shardSwap.applySchemaUINode, shardSwap.backupUINode, shardSwap.propagationUINode, shardSwap.reparentUINode, } schemaSwap.allShards = append(schemaSwap.allShards, shardSwap) } return nil }
go
func (schemaSwap *Swap) createShardObjects() error { shardsList, err := schemaSwap.topoServer.FindAllShardsInKeyspace(schemaSwap.ctx, schemaSwap.keyspace) if err != nil { return err } for _, shardInfo := range shardsList { shardSwap := &shardSchemaSwap{ parent: schemaSwap, shardName: shardInfo.ShardName(), shardUINode: &workflow.Node{ Name: fmt.Sprintf("Shard %v", shardInfo.ShardName()), PathName: shardInfo.ShardName(), State: workflowpb.WorkflowState_Running, }, applySchemaUINode: &workflow.Node{ Name: "Apply schema on seed tablet", PathName: "apply_schema", }, backupUINode: &workflow.Node{ Name: "Take seed backup", PathName: "backup", }, propagationUINode: &workflow.Node{ Name: "Propagate backup", PathName: "propagate", }, reparentUINode: &workflow.Node{ Name: "Reparent from old master", PathName: "reparent", }, shardUILogger: logutil.NewMemoryLogger(), propagationUILogger: logutil.NewMemoryLogger(), } schemaSwap.rootUINode.Children = append(schemaSwap.rootUINode.Children, shardSwap.shardUINode) shardSwap.shardUINode.Children = []*workflow.Node{ shardSwap.applySchemaUINode, shardSwap.backupUINode, shardSwap.propagationUINode, shardSwap.reparentUINode, } schemaSwap.allShards = append(schemaSwap.allShards, shardSwap) } return nil }
[ "func", "(", "schemaSwap", "*", "Swap", ")", "createShardObjects", "(", ")", "error", "{", "shardsList", ",", "err", ":=", "schemaSwap", ".", "topoServer", ".", "FindAllShardsInKeyspace", "(", "schemaSwap", ".", "ctx", ",", "schemaSwap", ".", "keyspace", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "shardInfo", ":=", "range", "shardsList", "{", "shardSwap", ":=", "&", "shardSchemaSwap", "{", "parent", ":", "schemaSwap", ",", "shardName", ":", "shardInfo", ".", "ShardName", "(", ")", ",", "shardUINode", ":", "&", "workflow", ".", "Node", "{", "Name", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "shardInfo", ".", "ShardName", "(", ")", ")", ",", "PathName", ":", "shardInfo", ".", "ShardName", "(", ")", ",", "State", ":", "workflowpb", ".", "WorkflowState_Running", ",", "}", ",", "applySchemaUINode", ":", "&", "workflow", ".", "Node", "{", "Name", ":", "\"", "\"", ",", "PathName", ":", "\"", "\"", ",", "}", ",", "backupUINode", ":", "&", "workflow", ".", "Node", "{", "Name", ":", "\"", "\"", ",", "PathName", ":", "\"", "\"", ",", "}", ",", "propagationUINode", ":", "&", "workflow", ".", "Node", "{", "Name", ":", "\"", "\"", ",", "PathName", ":", "\"", "\"", ",", "}", ",", "reparentUINode", ":", "&", "workflow", ".", "Node", "{", "Name", ":", "\"", "\"", ",", "PathName", ":", "\"", "\"", ",", "}", ",", "shardUILogger", ":", "logutil", ".", "NewMemoryLogger", "(", ")", ",", "propagationUILogger", ":", "logutil", ".", "NewMemoryLogger", "(", ")", ",", "}", "\n", "schemaSwap", ".", "rootUINode", ".", "Children", "=", "append", "(", "schemaSwap", ".", "rootUINode", ".", "Children", ",", "shardSwap", ".", "shardUINode", ")", "\n", "shardSwap", ".", "shardUINode", ".", "Children", "=", "[", "]", "*", "workflow", ".", "Node", "{", "shardSwap", ".", "applySchemaUINode", ",", "shardSwap", ".", "backupUINode", ",", "shardSwap", ".", "propagationUINode", ",", "shardSwap", ".", "reparentUINode", ",", "}", "\n", "schemaSwap", ".", "allShards", "=", "append", "(", "schemaSwap", ".", "allShards", ",", "shardSwap", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// createShardObjects creates per-shard swap objects for all shards in the keyspace.
[ "createShardObjects", "creates", "per", "-", "shard", "swap", "objects", "for", "all", "shards", "in", "the", "keyspace", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L407-L450
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
stopAllHealthWatchers
func (schemaSwap *Swap) stopAllHealthWatchers() { schemaSwap.runOnAllShards( func(shard *shardSchemaSwap) error { shard.stopHealthWatchers() return nil }) }
go
func (schemaSwap *Swap) stopAllHealthWatchers() { schemaSwap.runOnAllShards( func(shard *shardSchemaSwap) error { shard.stopHealthWatchers() return nil }) }
[ "func", "(", "schemaSwap", "*", "Swap", ")", "stopAllHealthWatchers", "(", ")", "{", "schemaSwap", ".", "runOnAllShards", "(", "func", "(", "shard", "*", "shardSchemaSwap", ")", "error", "{", "shard", ".", "stopHealthWatchers", "(", ")", "\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// stopAllHealthWatchers stops watching for health on each shard. It's separated into a separate // function mainly to make "defer" statement where it's used simpler.
[ "stopAllHealthWatchers", "stops", "watching", "for", "health", "on", "each", "shard", ".", "It", "s", "separated", "into", "a", "separate", "function", "mainly", "to", "make", "defer", "statement", "where", "it", "s", "used", "simpler", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L454-L460
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
initializeSwap
func (schemaSwap *Swap) initializeSwap() error { var waitGroup sync.WaitGroup metadataList := make([]shardSwapMetadata, len(schemaSwap.allShards)) for i, shard := range schemaSwap.allShards { waitGroup.Add(1) go shard.readShardMetadata(&metadataList[i], &waitGroup) } waitGroup.Wait() var recorder concurrency.AllErrorRecorder var lastFinishedSwapID uint64 for i, metadata := range metadataList { if metadata.err != nil { recorder.RecordError(metadata.err) } else if metadata.lastStartedSwap < metadata.lastFinishedSwap || metadata.lastStartedSwap > metadata.lastFinishedSwap+1 { recorder.RecordError(fmt.Errorf( "bad swap metadata on shard %v: LastFinishedSchemaSwap=%v, LastStartedSchemaSwap=%v", schemaSwap.allShards[i].shardName, metadata.lastFinishedSwap, metadata.lastStartedSwap)) } else if metadata.lastStartedSwap != metadata.lastFinishedSwap { if metadata.currentSQL != schemaSwap.sql { recorder.RecordError(fmt.Errorf( "shard %v has an already started schema swap with a different set of SQL statements", schemaSwap.allShards[i].shardName)) } } if lastFinishedSwapID == 0 || metadata.lastFinishedSwap < lastFinishedSwapID { lastFinishedSwapID = metadata.lastFinishedSwap } } if recorder.HasErrors() { return recorder.Error() } schemaSwap.swapID = lastFinishedSwapID + 1 var haveNotStartedSwap, haveFinishedSwap bool for i, metadata := range metadataList { if metadata.lastStartedSwap == metadata.lastFinishedSwap { // The shard doesn't have schema swap started yet or it's already finished. if schemaSwap.swapID != metadata.lastFinishedSwap && schemaSwap.swapID != metadata.lastFinishedSwap+1 { recorder.RecordError(fmt.Errorf( "shard %v has last finished swap id euqal to %v which doesn't align with swap id for the keyspace equal to %v", schemaSwap.allShards[i].shardName, metadata.lastFinishedSwap, schemaSwap.swapID)) } else if schemaSwap.swapID == metadata.lastFinishedSwap { haveFinishedSwap = true } else { haveNotStartedSwap = true } } else if schemaSwap.swapID != metadata.lastStartedSwap { recorder.RecordError(fmt.Errorf( "shard %v has an already started schema swap with an id %v, while for the keyspace it should be equal to %v", schemaSwap.allShards[i].shardName, metadata.lastStartedSwap, schemaSwap.swapID)) } } if haveNotStartedSwap && haveFinishedSwap { recorder.RecordError(errors.New("impossible state: there are shards with finished swap and shards where swap was not started")) } if recorder.HasErrors() { return recorder.Error() } if haveNotStartedSwap { return schemaSwap.runOnAllShards( func(shard *shardSchemaSwap) error { return shard.writeStartedSwap() }) } return nil }
go
func (schemaSwap *Swap) initializeSwap() error { var waitGroup sync.WaitGroup metadataList := make([]shardSwapMetadata, len(schemaSwap.allShards)) for i, shard := range schemaSwap.allShards { waitGroup.Add(1) go shard.readShardMetadata(&metadataList[i], &waitGroup) } waitGroup.Wait() var recorder concurrency.AllErrorRecorder var lastFinishedSwapID uint64 for i, metadata := range metadataList { if metadata.err != nil { recorder.RecordError(metadata.err) } else if metadata.lastStartedSwap < metadata.lastFinishedSwap || metadata.lastStartedSwap > metadata.lastFinishedSwap+1 { recorder.RecordError(fmt.Errorf( "bad swap metadata on shard %v: LastFinishedSchemaSwap=%v, LastStartedSchemaSwap=%v", schemaSwap.allShards[i].shardName, metadata.lastFinishedSwap, metadata.lastStartedSwap)) } else if metadata.lastStartedSwap != metadata.lastFinishedSwap { if metadata.currentSQL != schemaSwap.sql { recorder.RecordError(fmt.Errorf( "shard %v has an already started schema swap with a different set of SQL statements", schemaSwap.allShards[i].shardName)) } } if lastFinishedSwapID == 0 || metadata.lastFinishedSwap < lastFinishedSwapID { lastFinishedSwapID = metadata.lastFinishedSwap } } if recorder.HasErrors() { return recorder.Error() } schemaSwap.swapID = lastFinishedSwapID + 1 var haveNotStartedSwap, haveFinishedSwap bool for i, metadata := range metadataList { if metadata.lastStartedSwap == metadata.lastFinishedSwap { // The shard doesn't have schema swap started yet or it's already finished. if schemaSwap.swapID != metadata.lastFinishedSwap && schemaSwap.swapID != metadata.lastFinishedSwap+1 { recorder.RecordError(fmt.Errorf( "shard %v has last finished swap id euqal to %v which doesn't align with swap id for the keyspace equal to %v", schemaSwap.allShards[i].shardName, metadata.lastFinishedSwap, schemaSwap.swapID)) } else if schemaSwap.swapID == metadata.lastFinishedSwap { haveFinishedSwap = true } else { haveNotStartedSwap = true } } else if schemaSwap.swapID != metadata.lastStartedSwap { recorder.RecordError(fmt.Errorf( "shard %v has an already started schema swap with an id %v, while for the keyspace it should be equal to %v", schemaSwap.allShards[i].shardName, metadata.lastStartedSwap, schemaSwap.swapID)) } } if haveNotStartedSwap && haveFinishedSwap { recorder.RecordError(errors.New("impossible state: there are shards with finished swap and shards where swap was not started")) } if recorder.HasErrors() { return recorder.Error() } if haveNotStartedSwap { return schemaSwap.runOnAllShards( func(shard *shardSchemaSwap) error { return shard.writeStartedSwap() }) } return nil }
[ "func", "(", "schemaSwap", "*", "Swap", ")", "initializeSwap", "(", ")", "error", "{", "var", "waitGroup", "sync", ".", "WaitGroup", "\n", "metadataList", ":=", "make", "(", "[", "]", "shardSwapMetadata", ",", "len", "(", "schemaSwap", ".", "allShards", ")", ")", "\n", "for", "i", ",", "shard", ":=", "range", "schemaSwap", ".", "allShards", "{", "waitGroup", ".", "Add", "(", "1", ")", "\n", "go", "shard", ".", "readShardMetadata", "(", "&", "metadataList", "[", "i", "]", ",", "&", "waitGroup", ")", "\n", "}", "\n", "waitGroup", ".", "Wait", "(", ")", "\n\n", "var", "recorder", "concurrency", ".", "AllErrorRecorder", "\n", "var", "lastFinishedSwapID", "uint64", "\n", "for", "i", ",", "metadata", ":=", "range", "metadataList", "{", "if", "metadata", ".", "err", "!=", "nil", "{", "recorder", ".", "RecordError", "(", "metadata", ".", "err", ")", "\n", "}", "else", "if", "metadata", ".", "lastStartedSwap", "<", "metadata", ".", "lastFinishedSwap", "||", "metadata", ".", "lastStartedSwap", ">", "metadata", ".", "lastFinishedSwap", "+", "1", "{", "recorder", ".", "RecordError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "schemaSwap", ".", "allShards", "[", "i", "]", ".", "shardName", ",", "metadata", ".", "lastFinishedSwap", ",", "metadata", ".", "lastStartedSwap", ")", ")", "\n", "}", "else", "if", "metadata", ".", "lastStartedSwap", "!=", "metadata", ".", "lastFinishedSwap", "{", "if", "metadata", ".", "currentSQL", "!=", "schemaSwap", ".", "sql", "{", "recorder", ".", "RecordError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "schemaSwap", ".", "allShards", "[", "i", "]", ".", "shardName", ")", ")", "\n", "}", "\n", "}", "\n", "if", "lastFinishedSwapID", "==", "0", "||", "metadata", ".", "lastFinishedSwap", "<", "lastFinishedSwapID", "{", "lastFinishedSwapID", "=", "metadata", ".", "lastFinishedSwap", "\n", "}", "\n", "}", "\n", "if", "recorder", ".", "HasErrors", "(", ")", "{", "return", "recorder", ".", "Error", "(", ")", "\n", "}", "\n\n", "schemaSwap", ".", "swapID", "=", "lastFinishedSwapID", "+", "1", "\n", "var", "haveNotStartedSwap", ",", "haveFinishedSwap", "bool", "\n", "for", "i", ",", "metadata", ":=", "range", "metadataList", "{", "if", "metadata", ".", "lastStartedSwap", "==", "metadata", ".", "lastFinishedSwap", "{", "// The shard doesn't have schema swap started yet or it's already finished.", "if", "schemaSwap", ".", "swapID", "!=", "metadata", ".", "lastFinishedSwap", "&&", "schemaSwap", ".", "swapID", "!=", "metadata", ".", "lastFinishedSwap", "+", "1", "{", "recorder", ".", "RecordError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "schemaSwap", ".", "allShards", "[", "i", "]", ".", "shardName", ",", "metadata", ".", "lastFinishedSwap", ",", "schemaSwap", ".", "swapID", ")", ")", "\n", "}", "else", "if", "schemaSwap", ".", "swapID", "==", "metadata", ".", "lastFinishedSwap", "{", "haveFinishedSwap", "=", "true", "\n", "}", "else", "{", "haveNotStartedSwap", "=", "true", "\n", "}", "\n", "}", "else", "if", "schemaSwap", ".", "swapID", "!=", "metadata", ".", "lastStartedSwap", "{", "recorder", ".", "RecordError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "schemaSwap", ".", "allShards", "[", "i", "]", ".", "shardName", ",", "metadata", ".", "lastStartedSwap", ",", "schemaSwap", ".", "swapID", ")", ")", "\n", "}", "\n", "}", "\n", "if", "haveNotStartedSwap", "&&", "haveFinishedSwap", "{", "recorder", ".", "RecordError", "(", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "if", "recorder", ".", "HasErrors", "(", ")", "{", "return", "recorder", ".", "Error", "(", ")", "\n", "}", "\n\n", "if", "haveNotStartedSwap", "{", "return", "schemaSwap", ".", "runOnAllShards", "(", "func", "(", "shard", "*", "shardSchemaSwap", ")", "error", "{", "return", "shard", ".", "writeStartedSwap", "(", ")", "\n", "}", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// initializeSwap starts the schema swap process. If there is already a schema swap process started // the method just picks up that. Otherwise it starts a new one and writes into the database that // the process was started.
[ "initializeSwap", "starts", "the", "schema", "swap", "process", ".", "If", "there", "is", "already", "a", "schema", "swap", "process", "started", "the", "method", "just", "picks", "up", "that", ".", "Otherwise", "it", "starts", "a", "new", "one", "and", "writes", "into", "the", "database", "that", "the", "process", "was", "started", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L465-L532
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
finalizeSwap
func (schemaSwap *Swap) finalizeSwap() error { return schemaSwap.runOnAllShards( func(shard *shardSchemaSwap) error { return shard.writeFinishedSwap() }) }
go
func (schemaSwap *Swap) finalizeSwap() error { return schemaSwap.runOnAllShards( func(shard *shardSchemaSwap) error { return shard.writeFinishedSwap() }) }
[ "func", "(", "schemaSwap", "*", "Swap", ")", "finalizeSwap", "(", ")", "error", "{", "return", "schemaSwap", ".", "runOnAllShards", "(", "func", "(", "shard", "*", "shardSchemaSwap", ")", "error", "{", "return", "shard", ".", "writeFinishedSwap", "(", ")", "\n", "}", ")", "\n", "}" ]
// finalizeSwap finishes the completed swap process by modifying the database to register the completion.
[ "finalizeSwap", "finishes", "the", "completed", "swap", "process", "by", "modifying", "the", "database", "to", "register", "the", "completion", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L535-L540
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
markStepInProgress
func (shardSwap *shardSchemaSwap) markStepInProgress(uiNode *workflow.Node) { uiNode.Message = "" uiNode.State = workflowpb.WorkflowState_Running uiNode.Display = workflow.NodeDisplayIndeterminate uiNode.BroadcastChanges(false /* updateChildren */) }
go
func (shardSwap *shardSchemaSwap) markStepInProgress(uiNode *workflow.Node) { uiNode.Message = "" uiNode.State = workflowpb.WorkflowState_Running uiNode.Display = workflow.NodeDisplayIndeterminate uiNode.BroadcastChanges(false /* updateChildren */) }
[ "func", "(", "shardSwap", "*", "shardSchemaSwap", ")", "markStepInProgress", "(", "uiNode", "*", "workflow", ".", "Node", ")", "{", "uiNode", ".", "Message", "=", "\"", "\"", "\n", "uiNode", ".", "State", "=", "workflowpb", ".", "WorkflowState_Running", "\n", "uiNode", ".", "Display", "=", "workflow", ".", "NodeDisplayIndeterminate", "\n", "uiNode", ".", "BroadcastChanges", "(", "false", "/* updateChildren */", ")", "\n", "}" ]
// markStepInProgress marks one step of the shard schema swap workflow as running.
[ "markStepInProgress", "marks", "one", "step", "of", "the", "shard", "schema", "swap", "workflow", "as", "running", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L554-L559
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
addShardLog
func (shardSwap *shardSchemaSwap) addShardLog(message string) { log.Infof("Shard %v: %v", shardSwap.shardName, message) shardSwap.shardUILogger.Infof(message) shardSwap.shardUINode.Log = shardSwap.shardUILogger.String() shardSwap.shardUINode.BroadcastChanges(false /* updateChildren */) }
go
func (shardSwap *shardSchemaSwap) addShardLog(message string) { log.Infof("Shard %v: %v", shardSwap.shardName, message) shardSwap.shardUILogger.Infof(message) shardSwap.shardUINode.Log = shardSwap.shardUILogger.String() shardSwap.shardUINode.BroadcastChanges(false /* updateChildren */) }
[ "func", "(", "shardSwap", "*", "shardSchemaSwap", ")", "addShardLog", "(", "message", "string", ")", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "shardSwap", ".", "shardName", ",", "message", ")", "\n", "shardSwap", ".", "shardUILogger", ".", "Infof", "(", "message", ")", "\n", "shardSwap", ".", "shardUINode", ".", "Log", "=", "shardSwap", ".", "shardUILogger", ".", "String", "(", ")", "\n", "shardSwap", ".", "shardUINode", ".", "BroadcastChanges", "(", "false", "/* updateChildren */", ")", "\n", "}" ]
// addShardLog prints the message into logs and adds it into logs displayed in UI on the // shard node.
[ "addShardLog", "prints", "the", "message", "into", "logs", "and", "adds", "it", "into", "logs", "displayed", "in", "UI", "on", "the", "shard", "node", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L563-L568
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
markStepDone
func (shardSwap *shardSchemaSwap) markStepDone(uiNode *workflow.Node, err *error) { if *err != nil { msg := fmt.Sprintf("Error: %v", *err) shardSwap.addShardLog(msg) uiNode.Message = msg } uiNode.State = workflowpb.WorkflowState_Done uiNode.Display = workflow.NodeDisplayNone uiNode.BroadcastChanges(false /* updateChildren */) }
go
func (shardSwap *shardSchemaSwap) markStepDone(uiNode *workflow.Node, err *error) { if *err != nil { msg := fmt.Sprintf("Error: %v", *err) shardSwap.addShardLog(msg) uiNode.Message = msg } uiNode.State = workflowpb.WorkflowState_Done uiNode.Display = workflow.NodeDisplayNone uiNode.BroadcastChanges(false /* updateChildren */) }
[ "func", "(", "shardSwap", "*", "shardSchemaSwap", ")", "markStepDone", "(", "uiNode", "*", "workflow", ".", "Node", ",", "err", "*", "error", ")", "{", "if", "*", "err", "!=", "nil", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "*", "err", ")", "\n", "shardSwap", ".", "addShardLog", "(", "msg", ")", "\n", "uiNode", ".", "Message", "=", "msg", "\n", "}", "\n", "uiNode", ".", "State", "=", "workflowpb", ".", "WorkflowState_Done", "\n", "uiNode", ".", "Display", "=", "workflow", ".", "NodeDisplayNone", "\n", "uiNode", ".", "BroadcastChanges", "(", "false", "/* updateChildren */", ")", "\n", "}" ]
// markStepDone marks one step of the shard schema swap workflow as finished successfully // or with an error.
[ "markStepDone", "marks", "one", "step", "of", "the", "shard", "schema", "swap", "workflow", "as", "finished", "successfully", "or", "with", "an", "error", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L572-L581
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
getMasterTablet
func (shardSwap *shardSchemaSwap) getMasterTablet() (*topodatapb.Tablet, error) { topoServer := shardSwap.parent.topoServer shardInfo, err := topoServer.GetShard(shardSwap.parent.ctx, shardSwap.parent.keyspace, shardSwap.shardName) if err != nil { return nil, err } tabletInfo, err := topoServer.GetTablet(shardSwap.parent.ctx, shardInfo.MasterAlias) if err != nil { return nil, err } return tabletInfo.Tablet, nil }
go
func (shardSwap *shardSchemaSwap) getMasterTablet() (*topodatapb.Tablet, error) { topoServer := shardSwap.parent.topoServer shardInfo, err := topoServer.GetShard(shardSwap.parent.ctx, shardSwap.parent.keyspace, shardSwap.shardName) if err != nil { return nil, err } tabletInfo, err := topoServer.GetTablet(shardSwap.parent.ctx, shardInfo.MasterAlias) if err != nil { return nil, err } return tabletInfo.Tablet, nil }
[ "func", "(", "shardSwap", "*", "shardSchemaSwap", ")", "getMasterTablet", "(", ")", "(", "*", "topodatapb", ".", "Tablet", ",", "error", ")", "{", "topoServer", ":=", "shardSwap", ".", "parent", ".", "topoServer", "\n", "shardInfo", ",", "err", ":=", "topoServer", ".", "GetShard", "(", "shardSwap", ".", "parent", ".", "ctx", ",", "shardSwap", ".", "parent", ".", "keyspace", ",", "shardSwap", ".", "shardName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "tabletInfo", ",", "err", ":=", "topoServer", ".", "GetTablet", "(", "shardSwap", ".", "parent", ".", "ctx", ",", "shardInfo", ".", "MasterAlias", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "tabletInfo", ".", "Tablet", ",", "nil", "\n", "}" ]
// getMasterTablet returns the tablet that is currently master on the shard.
[ "getMasterTablet", "returns", "the", "tablet", "that", "is", "currently", "master", "on", "the", "shard", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L584-L595
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
readShardMetadata
func (shardSwap *shardSchemaSwap) readShardMetadata(metadata *shardSwapMetadata, waitGroup *sync.WaitGroup) { defer waitGroup.Done() tablet, err := shardSwap.getMasterTablet() if err != nil { metadata.err = err return } query := fmt.Sprintf( "SELECT name, value FROM _vt.shard_metadata WHERE db_name = '%s' and name in ('%s', '%s', '%s')", topoproto.TabletDbName(tablet), lastStartedMetadataName, lastFinishedMetadataName, currentSQLMetadataName) queryResult, err := shardSwap.executeAdminQuery(tablet, query, 3 /* maxRows */) if err != nil { metadata.err = err return } for _, row := range queryResult.Rows { switch row[0].ToString() { case lastStartedMetadataName: swapID, err := sqltypes.ToUint64(row[1]) if err != nil { log.Warningf("Could not parse value of last started schema swap id %v, ignoring the value: %v", row[1], err) } else { metadata.lastStartedSwap = swapID } case lastFinishedMetadataName: swapID, err := sqltypes.ToUint64(row[1]) if err != nil { log.Warningf("Could not parse value of last finished schema swap id %v, ignoring the value: %v", row[1], err) } else { metadata.lastFinishedSwap = swapID } case currentSQLMetadataName: metadata.currentSQL = row[1].ToString() } } }
go
func (shardSwap *shardSchemaSwap) readShardMetadata(metadata *shardSwapMetadata, waitGroup *sync.WaitGroup) { defer waitGroup.Done() tablet, err := shardSwap.getMasterTablet() if err != nil { metadata.err = err return } query := fmt.Sprintf( "SELECT name, value FROM _vt.shard_metadata WHERE db_name = '%s' and name in ('%s', '%s', '%s')", topoproto.TabletDbName(tablet), lastStartedMetadataName, lastFinishedMetadataName, currentSQLMetadataName) queryResult, err := shardSwap.executeAdminQuery(tablet, query, 3 /* maxRows */) if err != nil { metadata.err = err return } for _, row := range queryResult.Rows { switch row[0].ToString() { case lastStartedMetadataName: swapID, err := sqltypes.ToUint64(row[1]) if err != nil { log.Warningf("Could not parse value of last started schema swap id %v, ignoring the value: %v", row[1], err) } else { metadata.lastStartedSwap = swapID } case lastFinishedMetadataName: swapID, err := sqltypes.ToUint64(row[1]) if err != nil { log.Warningf("Could not parse value of last finished schema swap id %v, ignoring the value: %v", row[1], err) } else { metadata.lastFinishedSwap = swapID } case currentSQLMetadataName: metadata.currentSQL = row[1].ToString() } } }
[ "func", "(", "shardSwap", "*", "shardSchemaSwap", ")", "readShardMetadata", "(", "metadata", "*", "shardSwapMetadata", ",", "waitGroup", "*", "sync", ".", "WaitGroup", ")", "{", "defer", "waitGroup", ".", "Done", "(", ")", "\n\n", "tablet", ",", "err", ":=", "shardSwap", ".", "getMasterTablet", "(", ")", "\n", "if", "err", "!=", "nil", "{", "metadata", ".", "err", "=", "err", "\n", "return", "\n", "}", "\n", "query", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "topoproto", ".", "TabletDbName", "(", "tablet", ")", ",", "lastStartedMetadataName", ",", "lastFinishedMetadataName", ",", "currentSQLMetadataName", ")", "\n", "queryResult", ",", "err", ":=", "shardSwap", ".", "executeAdminQuery", "(", "tablet", ",", "query", ",", "3", "/* maxRows */", ")", "\n", "if", "err", "!=", "nil", "{", "metadata", ".", "err", "=", "err", "\n", "return", "\n", "}", "\n", "for", "_", ",", "row", ":=", "range", "queryResult", ".", "Rows", "{", "switch", "row", "[", "0", "]", ".", "ToString", "(", ")", "{", "case", "lastStartedMetadataName", ":", "swapID", ",", "err", ":=", "sqltypes", ".", "ToUint64", "(", "row", "[", "1", "]", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "row", "[", "1", "]", ",", "err", ")", "\n", "}", "else", "{", "metadata", ".", "lastStartedSwap", "=", "swapID", "\n", "}", "\n", "case", "lastFinishedMetadataName", ":", "swapID", ",", "err", ":=", "sqltypes", ".", "ToUint64", "(", "row", "[", "1", "]", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "row", "[", "1", "]", ",", "err", ")", "\n", "}", "else", "{", "metadata", ".", "lastFinishedSwap", "=", "swapID", "\n", "}", "\n", "case", "currentSQLMetadataName", ":", "metadata", ".", "currentSQL", "=", "row", "[", "1", "]", ".", "ToString", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// readShardMetadata reads info about schema swaps on this shard from _vt.shard_metadata table.
[ "readShardMetadata", "reads", "info", "about", "schema", "swaps", "on", "this", "shard", "from", "_vt", ".", "shard_metadata", "table", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L598-L634
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
writeStartedSwap
func (shardSwap *shardSchemaSwap) writeStartedSwap() error { tablet, err := shardSwap.getMasterTablet() if err != nil { return err } queryBuf := bytes.Buffer{} queryBuf.WriteString("INSERT INTO _vt.shard_metadata (db_name, name, value) VALUES ('") queryBuf.WriteString(topoproto.TabletDbName(tablet)) queryBuf.WriteString("',") queryBuf.WriteString(currentSQLMetadataName) queryBuf.WriteString("',") sqlValue := sqltypes.NewVarChar(shardSwap.parent.sql) sqlValue.EncodeSQL(&queryBuf) queryBuf.WriteString(") ON DUPLICATE KEY UPDATE value = ") sqlValue.EncodeSQL(&queryBuf) _, err = shardSwap.executeAdminQuery(tablet, queryBuf.String(), 0 /* maxRows */) if err != nil { return err } query := fmt.Sprintf( "INSERT INTO _vt.shard_metadata (name, value) VALUES ('%s', '%d') ON DUPLICATE KEY UPDATE value = '%d'", lastStartedMetadataName, shardSwap.parent.swapID, shardSwap.parent.swapID) _, err = shardSwap.executeAdminQuery(tablet, query, 0 /* maxRows */) return err }
go
func (shardSwap *shardSchemaSwap) writeStartedSwap() error { tablet, err := shardSwap.getMasterTablet() if err != nil { return err } queryBuf := bytes.Buffer{} queryBuf.WriteString("INSERT INTO _vt.shard_metadata (db_name, name, value) VALUES ('") queryBuf.WriteString(topoproto.TabletDbName(tablet)) queryBuf.WriteString("',") queryBuf.WriteString(currentSQLMetadataName) queryBuf.WriteString("',") sqlValue := sqltypes.NewVarChar(shardSwap.parent.sql) sqlValue.EncodeSQL(&queryBuf) queryBuf.WriteString(") ON DUPLICATE KEY UPDATE value = ") sqlValue.EncodeSQL(&queryBuf) _, err = shardSwap.executeAdminQuery(tablet, queryBuf.String(), 0 /* maxRows */) if err != nil { return err } query := fmt.Sprintf( "INSERT INTO _vt.shard_metadata (name, value) VALUES ('%s', '%d') ON DUPLICATE KEY UPDATE value = '%d'", lastStartedMetadataName, shardSwap.parent.swapID, shardSwap.parent.swapID) _, err = shardSwap.executeAdminQuery(tablet, query, 0 /* maxRows */) return err }
[ "func", "(", "shardSwap", "*", "shardSchemaSwap", ")", "writeStartedSwap", "(", ")", "error", "{", "tablet", ",", "err", ":=", "shardSwap", ".", "getMasterTablet", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "queryBuf", ":=", "bytes", ".", "Buffer", "{", "}", "\n", "queryBuf", ".", "WriteString", "(", "\"", "\"", ")", "\n", "queryBuf", ".", "WriteString", "(", "topoproto", ".", "TabletDbName", "(", "tablet", ")", ")", "\n", "queryBuf", ".", "WriteString", "(", "\"", "\"", ")", "\n", "queryBuf", ".", "WriteString", "(", "currentSQLMetadataName", ")", "\n", "queryBuf", ".", "WriteString", "(", "\"", "\"", ")", "\n", "sqlValue", ":=", "sqltypes", ".", "NewVarChar", "(", "shardSwap", ".", "parent", ".", "sql", ")", "\n", "sqlValue", ".", "EncodeSQL", "(", "&", "queryBuf", ")", "\n", "queryBuf", ".", "WriteString", "(", "\"", "\"", ")", "\n", "sqlValue", ".", "EncodeSQL", "(", "&", "queryBuf", ")", "\n", "_", ",", "err", "=", "shardSwap", ".", "executeAdminQuery", "(", "tablet", ",", "queryBuf", ".", "String", "(", ")", ",", "0", "/* maxRows */", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "query", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "lastStartedMetadataName", ",", "shardSwap", ".", "parent", ".", "swapID", ",", "shardSwap", ".", "parent", ".", "swapID", ")", "\n", "_", ",", "err", "=", "shardSwap", ".", "executeAdminQuery", "(", "tablet", ",", "query", ",", "0", "/* maxRows */", ")", "\n", "return", "err", "\n", "}" ]
// writeStartedSwap registers in the _vt.shard_metadata table in the database the information // about the new schema swap process being started.
[ "writeStartedSwap", "registers", "in", "the", "_vt", ".", "shard_metadata", "table", "in", "the", "database", "the", "information", "about", "the", "new", "schema", "swap", "process", "being", "started", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L638-L662
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
writeFinishedSwap
func (shardSwap *shardSchemaSwap) writeFinishedSwap() error { tablet, err := shardSwap.getMasterTablet() if err != nil { return err } query := fmt.Sprintf( "INSERT INTO _vt.shard_metadata (db_name, name, value) VALUES ('%s', '%s', '%d') ON DUPLICATE KEY UPDATE value = '%d'", topoproto.TabletDbName(tablet), lastFinishedMetadataName, shardSwap.parent.swapID, shardSwap.parent.swapID) _, err = shardSwap.executeAdminQuery(tablet, query, 0 /* maxRows */) if err != nil { return err } query = fmt.Sprintf("DELETE FROM _vt.shard_metadata WHERE db_name = '%s' AND name = '%s'", topoproto.TabletDbName(tablet), currentSQLMetadataName) _, err = shardSwap.executeAdminQuery(tablet, query, 0 /* maxRows */) return err }
go
func (shardSwap *shardSchemaSwap) writeFinishedSwap() error { tablet, err := shardSwap.getMasterTablet() if err != nil { return err } query := fmt.Sprintf( "INSERT INTO _vt.shard_metadata (db_name, name, value) VALUES ('%s', '%s', '%d') ON DUPLICATE KEY UPDATE value = '%d'", topoproto.TabletDbName(tablet), lastFinishedMetadataName, shardSwap.parent.swapID, shardSwap.parent.swapID) _, err = shardSwap.executeAdminQuery(tablet, query, 0 /* maxRows */) if err != nil { return err } query = fmt.Sprintf("DELETE FROM _vt.shard_metadata WHERE db_name = '%s' AND name = '%s'", topoproto.TabletDbName(tablet), currentSQLMetadataName) _, err = shardSwap.executeAdminQuery(tablet, query, 0 /* maxRows */) return err }
[ "func", "(", "shardSwap", "*", "shardSchemaSwap", ")", "writeFinishedSwap", "(", ")", "error", "{", "tablet", ",", "err", ":=", "shardSwap", ".", "getMasterTablet", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "query", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "topoproto", ".", "TabletDbName", "(", "tablet", ")", ",", "lastFinishedMetadataName", ",", "shardSwap", ".", "parent", ".", "swapID", ",", "shardSwap", ".", "parent", ".", "swapID", ")", "\n", "_", ",", "err", "=", "shardSwap", ".", "executeAdminQuery", "(", "tablet", ",", "query", ",", "0", "/* maxRows */", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "query", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "topoproto", ".", "TabletDbName", "(", "tablet", ")", ",", "currentSQLMetadataName", ")", "\n", "_", ",", "err", "=", "shardSwap", ".", "executeAdminQuery", "(", "tablet", ",", "query", ",", "0", "/* maxRows */", ")", "\n", "return", "err", "\n", "}" ]
// writeFinishedSwap registers in the _vt.shard_metadata table in the database that the schema // swap process has finished.
[ "writeFinishedSwap", "registers", "in", "the", "_vt", ".", "shard_metadata", "table", "in", "the", "database", "that", "the", "schema", "swap", "process", "has", "finished", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L666-L681
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
startHealthWatchers
func (shardSwap *shardSchemaSwap) startHealthWatchers(ctx context.Context) error { shardSwap.allTablets = make(map[string]*discovery.TabletStats) shardSwap.tabletHealthCheck = discovery.NewHealthCheck(*vtctl.HealthcheckRetryDelay, *vtctl.HealthCheckTimeout) shardSwap.tabletHealthCheck.SetListener(shardSwap, true /* sendDownEvents */) topoServer := shardSwap.parent.topoServer cellList, err := topoServer.GetKnownCells(shardSwap.parent.ctx) if err != nil { return err } for _, cell := range cellList { watcher := discovery.NewShardReplicationWatcher( ctx, topoServer, shardSwap.tabletHealthCheck, cell, shardSwap.parent.keyspace, shardSwap.shardName, *vtctl.HealthCheckTimeout, discovery.DefaultTopoReadConcurrency) shardSwap.tabletWatchers = append(shardSwap.tabletWatchers, watcher) } for _, watcher := range shardSwap.tabletWatchers { if err := watcher.WaitForInitialTopology(); err != nil { return err } } shardSwap.tabletHealthCheck.WaitForInitialStatsUpdates() // Wait for all health connections to be either established or get broken. waitHealthChecks: for { tabletList := shardSwap.getTabletList() for _, tabletStats := range tabletList { if tabletStats.Stats == nil && tabletStats.LastError == nil { select { case <-shardSwap.parent.ctx.Done(): return shardSwap.parent.ctx.Err() case <-time.After(100 * time.Millisecond): } continue waitHealthChecks } } break waitHealthChecks } return nil }
go
func (shardSwap *shardSchemaSwap) startHealthWatchers(ctx context.Context) error { shardSwap.allTablets = make(map[string]*discovery.TabletStats) shardSwap.tabletHealthCheck = discovery.NewHealthCheck(*vtctl.HealthcheckRetryDelay, *vtctl.HealthCheckTimeout) shardSwap.tabletHealthCheck.SetListener(shardSwap, true /* sendDownEvents */) topoServer := shardSwap.parent.topoServer cellList, err := topoServer.GetKnownCells(shardSwap.parent.ctx) if err != nil { return err } for _, cell := range cellList { watcher := discovery.NewShardReplicationWatcher( ctx, topoServer, shardSwap.tabletHealthCheck, cell, shardSwap.parent.keyspace, shardSwap.shardName, *vtctl.HealthCheckTimeout, discovery.DefaultTopoReadConcurrency) shardSwap.tabletWatchers = append(shardSwap.tabletWatchers, watcher) } for _, watcher := range shardSwap.tabletWatchers { if err := watcher.WaitForInitialTopology(); err != nil { return err } } shardSwap.tabletHealthCheck.WaitForInitialStatsUpdates() // Wait for all health connections to be either established or get broken. waitHealthChecks: for { tabletList := shardSwap.getTabletList() for _, tabletStats := range tabletList { if tabletStats.Stats == nil && tabletStats.LastError == nil { select { case <-shardSwap.parent.ctx.Done(): return shardSwap.parent.ctx.Err() case <-time.After(100 * time.Millisecond): } continue waitHealthChecks } } break waitHealthChecks } return nil }
[ "func", "(", "shardSwap", "*", "shardSchemaSwap", ")", "startHealthWatchers", "(", "ctx", "context", ".", "Context", ")", "error", "{", "shardSwap", ".", "allTablets", "=", "make", "(", "map", "[", "string", "]", "*", "discovery", ".", "TabletStats", ")", "\n\n", "shardSwap", ".", "tabletHealthCheck", "=", "discovery", ".", "NewHealthCheck", "(", "*", "vtctl", ".", "HealthcheckRetryDelay", ",", "*", "vtctl", ".", "HealthCheckTimeout", ")", "\n", "shardSwap", ".", "tabletHealthCheck", ".", "SetListener", "(", "shardSwap", ",", "true", "/* sendDownEvents */", ")", "\n\n", "topoServer", ":=", "shardSwap", ".", "parent", ".", "topoServer", "\n", "cellList", ",", "err", ":=", "topoServer", ".", "GetKnownCells", "(", "shardSwap", ".", "parent", ".", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "cell", ":=", "range", "cellList", "{", "watcher", ":=", "discovery", ".", "NewShardReplicationWatcher", "(", "ctx", ",", "topoServer", ",", "shardSwap", ".", "tabletHealthCheck", ",", "cell", ",", "shardSwap", ".", "parent", ".", "keyspace", ",", "shardSwap", ".", "shardName", ",", "*", "vtctl", ".", "HealthCheckTimeout", ",", "discovery", ".", "DefaultTopoReadConcurrency", ")", "\n", "shardSwap", ".", "tabletWatchers", "=", "append", "(", "shardSwap", ".", "tabletWatchers", ",", "watcher", ")", "\n", "}", "\n", "for", "_", ",", "watcher", ":=", "range", "shardSwap", ".", "tabletWatchers", "{", "if", "err", ":=", "watcher", ".", "WaitForInitialTopology", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "shardSwap", ".", "tabletHealthCheck", ".", "WaitForInitialStatsUpdates", "(", ")", "\n\n", "// Wait for all health connections to be either established or get broken.", "waitHealthChecks", ":", "for", "{", "tabletList", ":=", "shardSwap", ".", "getTabletList", "(", ")", "\n", "for", "_", ",", "tabletStats", ":=", "range", "tabletList", "{", "if", "tabletStats", ".", "Stats", "==", "nil", "&&", "tabletStats", ".", "LastError", "==", "nil", "{", "select", "{", "case", "<-", "shardSwap", ".", "parent", ".", "ctx", ".", "Done", "(", ")", ":", "return", "shardSwap", ".", "parent", ".", "ctx", ".", "Err", "(", ")", "\n", "case", "<-", "time", ".", "After", "(", "100", "*", "time", ".", "Millisecond", ")", ":", "}", "\n", "continue", "waitHealthChecks", "\n", "}", "\n", "}", "\n", "break", "waitHealthChecks", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// startHealthWatchers launches the topology watchers and health checking to monitor // all tablets on the shard. Function should be called before the start of the schema // swap process.
[ "startHealthWatchers", "launches", "the", "topology", "watchers", "and", "health", "checking", "to", "monitor", "all", "tablets", "on", "the", "shard", ".", "Function", "should", "be", "called", "before", "the", "start", "of", "the", "schema", "swap", "process", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L686-L733
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
isTabletHealthy
func isTabletHealthy(tabletStats *discovery.TabletStats) bool { return tabletStats.Stats.HealthError == "" && !discovery.IsReplicationLagHigh(tabletStats) }
go
func isTabletHealthy(tabletStats *discovery.TabletStats) bool { return tabletStats.Stats.HealthError == "" && !discovery.IsReplicationLagHigh(tabletStats) }
[ "func", "isTabletHealthy", "(", "tabletStats", "*", "discovery", ".", "TabletStats", ")", "bool", "{", "return", "tabletStats", ".", "Stats", ".", "HealthError", "==", "\"", "\"", "&&", "!", "discovery", ".", "IsReplicationLagHigh", "(", "tabletStats", ")", "\n", "}" ]
// isTabletHealthy verifies that the given TabletStats represents a healthy tablet that is // caught up with replication to a serving level.
[ "isTabletHealthy", "verifies", "that", "the", "given", "TabletStats", "represents", "a", "healthy", "tablet", "that", "is", "caught", "up", "with", "replication", "to", "a", "serving", "level", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L751-L753
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
checkWaitingTabletHealthiness
func (shardSwap *shardSchemaSwap) checkWaitingTabletHealthiness(tabletStats *discovery.TabletStats) { if shardSwap.healthWaitingTablet == tabletStats.Key && isTabletHealthy(tabletStats) { close(*shardSwap.healthWaitingChannel) shardSwap.healthWaitingChannel = nil shardSwap.healthWaitingTablet = "" } }
go
func (shardSwap *shardSchemaSwap) checkWaitingTabletHealthiness(tabletStats *discovery.TabletStats) { if shardSwap.healthWaitingTablet == tabletStats.Key && isTabletHealthy(tabletStats) { close(*shardSwap.healthWaitingChannel) shardSwap.healthWaitingChannel = nil shardSwap.healthWaitingTablet = "" } }
[ "func", "(", "shardSwap", "*", "shardSchemaSwap", ")", "checkWaitingTabletHealthiness", "(", "tabletStats", "*", "discovery", ".", "TabletStats", ")", "{", "if", "shardSwap", ".", "healthWaitingTablet", "==", "tabletStats", ".", "Key", "&&", "isTabletHealthy", "(", "tabletStats", ")", "{", "close", "(", "*", "shardSwap", ".", "healthWaitingChannel", ")", "\n", "shardSwap", ".", "healthWaitingChannel", "=", "nil", "\n", "shardSwap", ".", "healthWaitingTablet", "=", "\"", "\"", "\n", "}", "\n", "}" ]
// checkWaitingTabletHealthiness verifies whether the provided TabletStats represent the // tablet that is being waited to become healthy, and notifies the waiting go routine if // it is the tablet and if it is healthy now. // The function should be called with shardSwap.allTabletsLock mutex locked.
[ "checkWaitingTabletHealthiness", "verifies", "whether", "the", "provided", "TabletStats", "represent", "the", "tablet", "that", "is", "being", "waited", "to", "become", "healthy", "and", "notifies", "the", "waiting", "go", "routine", "if", "it", "is", "the", "tablet", "and", "if", "it", "is", "healthy", "now", ".", "The", "function", "should", "be", "called", "with", "shardSwap", ".", "allTabletsLock", "mutex", "locked", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L783-L789
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
StatsUpdate
func (shardSwap *shardSchemaSwap) StatsUpdate(newTabletStats *discovery.TabletStats) { shardSwap.allTabletsLock.Lock() defer shardSwap.allTabletsLock.Unlock() existingStats, found := shardSwap.allTablets[newTabletStats.Key] if newTabletStats.Up { if found { *existingStats = *newTabletStats } else { shardSwap.allTablets[newTabletStats.Key] = newTabletStats } shardSwap.checkWaitingTabletHealthiness(newTabletStats) } else { delete(shardSwap.allTablets, newTabletStats.Key) } }
go
func (shardSwap *shardSchemaSwap) StatsUpdate(newTabletStats *discovery.TabletStats) { shardSwap.allTabletsLock.Lock() defer shardSwap.allTabletsLock.Unlock() existingStats, found := shardSwap.allTablets[newTabletStats.Key] if newTabletStats.Up { if found { *existingStats = *newTabletStats } else { shardSwap.allTablets[newTabletStats.Key] = newTabletStats } shardSwap.checkWaitingTabletHealthiness(newTabletStats) } else { delete(shardSwap.allTablets, newTabletStats.Key) } }
[ "func", "(", "shardSwap", "*", "shardSchemaSwap", ")", "StatsUpdate", "(", "newTabletStats", "*", "discovery", ".", "TabletStats", ")", "{", "shardSwap", ".", "allTabletsLock", ".", "Lock", "(", ")", "\n", "defer", "shardSwap", ".", "allTabletsLock", ".", "Unlock", "(", ")", "\n\n", "existingStats", ",", "found", ":=", "shardSwap", ".", "allTablets", "[", "newTabletStats", ".", "Key", "]", "\n", "if", "newTabletStats", ".", "Up", "{", "if", "found", "{", "*", "existingStats", "=", "*", "newTabletStats", "\n", "}", "else", "{", "shardSwap", ".", "allTablets", "[", "newTabletStats", ".", "Key", "]", "=", "newTabletStats", "\n", "}", "\n", "shardSwap", ".", "checkWaitingTabletHealthiness", "(", "newTabletStats", ")", "\n", "}", "else", "{", "delete", "(", "shardSwap", ".", "allTablets", ",", "newTabletStats", ".", "Key", ")", "\n", "}", "\n", "}" ]
// StatsUpdate is the part of discovery.HealthCheckStatsListener interface. It makes sure // that when a change of tablet health happens it's recorded in allTablets list, and if // this is the tablet that is being waited for after restore, the function wakes up the // waiting go routine.
[ "StatsUpdate", "is", "the", "part", "of", "discovery", ".", "HealthCheckStatsListener", "interface", ".", "It", "makes", "sure", "that", "when", "a", "change", "of", "tablet", "health", "happens", "it", "s", "recorded", "in", "allTablets", "list", "and", "if", "this", "is", "the", "tablet", "that", "is", "being", "waited", "for", "after", "restore", "the", "function", "wakes", "up", "the", "waiting", "go", "routine", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L795-L810
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
getTabletList
func (shardSwap *shardSchemaSwap) getTabletList() []discovery.TabletStats { shardSwap.allTabletsLock.RLock() defer shardSwap.allTabletsLock.RUnlock() tabletList := make([]discovery.TabletStats, 0, len(shardSwap.allTablets)) for _, tabletStats := range shardSwap.allTablets { tabletList = append(tabletList, *tabletStats) } return tabletList }
go
func (shardSwap *shardSchemaSwap) getTabletList() []discovery.TabletStats { shardSwap.allTabletsLock.RLock() defer shardSwap.allTabletsLock.RUnlock() tabletList := make([]discovery.TabletStats, 0, len(shardSwap.allTablets)) for _, tabletStats := range shardSwap.allTablets { tabletList = append(tabletList, *tabletStats) } return tabletList }
[ "func", "(", "shardSwap", "*", "shardSchemaSwap", ")", "getTabletList", "(", ")", "[", "]", "discovery", ".", "TabletStats", "{", "shardSwap", ".", "allTabletsLock", ".", "RLock", "(", ")", "\n", "defer", "shardSwap", ".", "allTabletsLock", ".", "RUnlock", "(", ")", "\n\n", "tabletList", ":=", "make", "(", "[", "]", "discovery", ".", "TabletStats", ",", "0", ",", "len", "(", "shardSwap", ".", "allTablets", ")", ")", "\n", "for", "_", ",", "tabletStats", ":=", "range", "shardSwap", ".", "allTablets", "{", "tabletList", "=", "append", "(", "tabletList", ",", "*", "tabletStats", ")", "\n", "}", "\n", "return", "tabletList", "\n", "}" ]
// getTabletList returns the list of all known tablets in the shard so that the caller // could operate with it without holding the allTabletsLock.
[ "getTabletList", "returns", "the", "list", "of", "all", "known", "tablets", "in", "the", "shard", "so", "that", "the", "caller", "could", "operate", "with", "it", "without", "holding", "the", "allTabletsLock", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L814-L823
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
Swap
func (array orderTabletsForSwap) Swap(i, j int) { array[i], array[j] = array[j], array[i] }
go
func (array orderTabletsForSwap) Swap(i, j int) { array[i], array[j] = array[j], array[i] }
[ "func", "(", "array", "orderTabletsForSwap", ")", "Swap", "(", "i", ",", "j", "int", ")", "{", "array", "[", "i", "]", ",", "array", "[", "j", "]", "=", "array", "[", "j", "]", ",", "array", "[", "i", "]", "\n", "}" ]
// Swap is part of sort.Interface interface.
[ "Swap", "is", "part", "of", "sort", ".", "Interface", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L836-L838
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
getTabletTypeFromStats
func getTabletTypeFromStats(tabletStats *discovery.TabletStats) topodatapb.TabletType { if tabletStats.Target == nil || tabletStats.Target.TabletType == topodatapb.TabletType_UNKNOWN { return tabletStats.Tablet.Type } return tabletStats.Target.TabletType }
go
func getTabletTypeFromStats(tabletStats *discovery.TabletStats) topodatapb.TabletType { if tabletStats.Target == nil || tabletStats.Target.TabletType == topodatapb.TabletType_UNKNOWN { return tabletStats.Tablet.Type } return tabletStats.Target.TabletType }
[ "func", "getTabletTypeFromStats", "(", "tabletStats", "*", "discovery", ".", "TabletStats", ")", "topodatapb", ".", "TabletType", "{", "if", "tabletStats", ".", "Target", "==", "nil", "||", "tabletStats", ".", "Target", ".", "TabletType", "==", "topodatapb", ".", "TabletType_UNKNOWN", "{", "return", "tabletStats", ".", "Tablet", ".", "Type", "\n", "}", "\n", "return", "tabletStats", ".", "Target", ".", "TabletType", "\n", "}" ]
// getTabletTypeFromStats returns the tablet type saved in the TabletStats object. If there is Target // data in the TabletStats object then the function returns TabletType from it because it will be more // up-to-date. But if that's not available then it returns Tablet.Type which will contain data read // from the topology during initialization of health watchers.
[ "getTabletTypeFromStats", "returns", "the", "tablet", "type", "saved", "in", "the", "TabletStats", "object", ".", "If", "there", "is", "Target", "data", "in", "the", "TabletStats", "object", "then", "the", "function", "returns", "TabletType", "from", "it", "because", "it", "will", "be", "more", "up", "-", "to", "-", "date", ".", "But", "if", "that", "s", "not", "available", "then", "it", "returns", "Tablet", ".", "Type", "which", "will", "contain", "data", "read", "from", "the", "topology", "during", "initialization", "of", "health", "watchers", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L844-L849
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
Less
func (array orderTabletsForSwap) Less(i, j int) bool { return tabletSortIndex(&array[i]) < tabletSortIndex(&array[j]) }
go
func (array orderTabletsForSwap) Less(i, j int) bool { return tabletSortIndex(&array[i]) < tabletSortIndex(&array[j]) }
[ "func", "(", "array", "orderTabletsForSwap", ")", "Less", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "tabletSortIndex", "(", "&", "array", "[", "i", "]", ")", "<", "tabletSortIndex", "(", "&", "array", "[", "j", "]", ")", "\n", "}" ]
// Less is part of sort.Interface interface. It should compare too elements of the array.
[ "Less", "is", "part", "of", "sort", ".", "Interface", "interface", ".", "It", "should", "compare", "too", "elements", "of", "the", "array", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L875-L877
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
isSwapApplied
func (shardSwap *shardSchemaSwap) isSwapApplied(tablet *topodatapb.Tablet) (bool, error) { swapIDResult, err := shardSwap.executeAdminQuery( tablet, fmt.Sprintf("SELECT value FROM _vt.local_metadata WHERE db_name = '%s' AND name = '%s'", topoproto.TabletDbName(tablet), lastAppliedMetadataName), 1 /* maxRows */) if err != nil { return false, err } if len(swapIDResult.Rows) == 0 { // No such row means we need to apply the swap. return false, nil } swapID, err := sqltypes.ToUint64(swapIDResult.Rows[0][0]) if err != nil { return false, err } return swapID == shardSwap.parent.swapID, nil }
go
func (shardSwap *shardSchemaSwap) isSwapApplied(tablet *topodatapb.Tablet) (bool, error) { swapIDResult, err := shardSwap.executeAdminQuery( tablet, fmt.Sprintf("SELECT value FROM _vt.local_metadata WHERE db_name = '%s' AND name = '%s'", topoproto.TabletDbName(tablet), lastAppliedMetadataName), 1 /* maxRows */) if err != nil { return false, err } if len(swapIDResult.Rows) == 0 { // No such row means we need to apply the swap. return false, nil } swapID, err := sqltypes.ToUint64(swapIDResult.Rows[0][0]) if err != nil { return false, err } return swapID == shardSwap.parent.swapID, nil }
[ "func", "(", "shardSwap", "*", "shardSchemaSwap", ")", "isSwapApplied", "(", "tablet", "*", "topodatapb", ".", "Tablet", ")", "(", "bool", ",", "error", ")", "{", "swapIDResult", ",", "err", ":=", "shardSwap", ".", "executeAdminQuery", "(", "tablet", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "topoproto", ".", "TabletDbName", "(", "tablet", ")", ",", "lastAppliedMetadataName", ")", ",", "1", "/* maxRows */", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "if", "len", "(", "swapIDResult", ".", "Rows", ")", "==", "0", "{", "// No such row means we need to apply the swap.", "return", "false", ",", "nil", "\n", "}", "\n", "swapID", ",", "err", ":=", "sqltypes", ".", "ToUint64", "(", "swapIDResult", ".", "Rows", "[", "0", "]", "[", "0", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "return", "swapID", "==", "shardSwap", ".", "parent", ".", "swapID", ",", "nil", "\n", "}" ]
// isSwapApplied verifies whether the schema swap was already applied to the tablet. It's // considered to be applied if _vt.local_metadata table has the swap id in the row titled // 'LastAppliedSchemaSwap'.
[ "isSwapApplied", "verifies", "whether", "the", "schema", "swap", "was", "already", "applied", "to", "the", "tablet", ".", "It", "s", "considered", "to", "be", "applied", "if", "_vt", ".", "local_metadata", "table", "has", "the", "swap", "id", "in", "the", "row", "titled", "LastAppliedSchemaSwap", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L900-L917
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
undrainSeedTablet
func (shardSwap *shardSchemaSwap) undrainSeedTablet(seedTablet *topodatapb.Tablet, tabletType topodatapb.TabletType) error { _, err := shardSwap.parent.topoServer.UpdateTabletFields(shardSwap.parent.ctx, seedTablet.Alias, func(tablet *topodatapb.Tablet) error { delete(tablet.Tags, "drain_reason") return nil }) if err != nil { // This is not a critical error, we'll just log it. log.Errorf("Got error trying to set drain_reason on tablet %v: %v", seedTablet.Alias, err) } err = shardSwap.parent.tabletClient.ChangeType(shardSwap.parent.ctx, seedTablet, tabletType) if err != nil { return err } return nil }
go
func (shardSwap *shardSchemaSwap) undrainSeedTablet(seedTablet *topodatapb.Tablet, tabletType topodatapb.TabletType) error { _, err := shardSwap.parent.topoServer.UpdateTabletFields(shardSwap.parent.ctx, seedTablet.Alias, func(tablet *topodatapb.Tablet) error { delete(tablet.Tags, "drain_reason") return nil }) if err != nil { // This is not a critical error, we'll just log it. log.Errorf("Got error trying to set drain_reason on tablet %v: %v", seedTablet.Alias, err) } err = shardSwap.parent.tabletClient.ChangeType(shardSwap.parent.ctx, seedTablet, tabletType) if err != nil { return err } return nil }
[ "func", "(", "shardSwap", "*", "shardSchemaSwap", ")", "undrainSeedTablet", "(", "seedTablet", "*", "topodatapb", ".", "Tablet", ",", "tabletType", "topodatapb", ".", "TabletType", ")", "error", "{", "_", ",", "err", ":=", "shardSwap", ".", "parent", ".", "topoServer", ".", "UpdateTabletFields", "(", "shardSwap", ".", "parent", ".", "ctx", ",", "seedTablet", ".", "Alias", ",", "func", "(", "tablet", "*", "topodatapb", ".", "Tablet", ")", "error", "{", "delete", "(", "tablet", ".", "Tags", ",", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "// This is not a critical error, we'll just log it.", "log", ".", "Errorf", "(", "\"", "\"", ",", "seedTablet", ".", "Alias", ",", "err", ")", "\n", "}", "\n", "err", "=", "shardSwap", ".", "parent", ".", "tabletClient", ".", "ChangeType", "(", "shardSwap", ".", "parent", ".", "ctx", ",", "seedTablet", ",", "tabletType", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// undrainSeedTablet undrains the tablet that was used to apply seed schema change, // and returns it to the same type as it was before.
[ "undrainSeedTablet", "undrains", "the", "tablet", "that", "was", "used", "to", "apply", "seed", "schema", "change", "and", "returns", "it", "to", "the", "same", "type", "as", "it", "was", "before", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L964-L979
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
takeSeedBackup
func (shardSwap *shardSchemaSwap) takeSeedBackup() (err error) { shardSwap.markStepInProgress(shardSwap.backupUINode) defer shardSwap.markStepDone(shardSwap.backupUINode, &err) tabletList := shardSwap.getTabletList() sort.Sort(orderTabletsForSwap(tabletList)) var seedTablet *topodatapb.Tablet for seedTablet == nil { for _, tabletStats := range tabletList { swapApplied, err := shardSwap.isSwapApplied(tabletStats.Tablet) if err != nil { return err } if swapApplied && getTabletTypeFromStats(&tabletStats) != topodatapb.TabletType_MASTER { seedTablet = tabletStats.Tablet break } } if seedTablet == nil { shardSwap.addShardLog("Cannot find the seed tablet to take backup.") if err := shardSwap.applySeedSchemaChange(); err != nil { return err } } } shardSwap.addShardLog(fmt.Sprintf("Taking backup on the seed tablet %v", seedTablet.Alias)) eventStream, err := shardSwap.parent.tabletClient.Backup(shardSwap.parent.ctx, seedTablet, *backupConcurrency, false) if err != nil { return err } waitForBackup: for { event, err := eventStream.Recv() switch err { case nil: log.Infof("Backup process on tablet %v: %v", seedTablet.Alias, logutil.EventString(event)) case io.EOF: break waitForBackup default: return err } } shardSwap.addShardLog(fmt.Sprintf("Waiting for the seed tablet %v to become healthy", seedTablet.Alias)) return shardSwap.waitForTabletToBeHealthy(seedTablet) }
go
func (shardSwap *shardSchemaSwap) takeSeedBackup() (err error) { shardSwap.markStepInProgress(shardSwap.backupUINode) defer shardSwap.markStepDone(shardSwap.backupUINode, &err) tabletList := shardSwap.getTabletList() sort.Sort(orderTabletsForSwap(tabletList)) var seedTablet *topodatapb.Tablet for seedTablet == nil { for _, tabletStats := range tabletList { swapApplied, err := shardSwap.isSwapApplied(tabletStats.Tablet) if err != nil { return err } if swapApplied && getTabletTypeFromStats(&tabletStats) != topodatapb.TabletType_MASTER { seedTablet = tabletStats.Tablet break } } if seedTablet == nil { shardSwap.addShardLog("Cannot find the seed tablet to take backup.") if err := shardSwap.applySeedSchemaChange(); err != nil { return err } } } shardSwap.addShardLog(fmt.Sprintf("Taking backup on the seed tablet %v", seedTablet.Alias)) eventStream, err := shardSwap.parent.tabletClient.Backup(shardSwap.parent.ctx, seedTablet, *backupConcurrency, false) if err != nil { return err } waitForBackup: for { event, err := eventStream.Recv() switch err { case nil: log.Infof("Backup process on tablet %v: %v", seedTablet.Alias, logutil.EventString(event)) case io.EOF: break waitForBackup default: return err } } shardSwap.addShardLog(fmt.Sprintf("Waiting for the seed tablet %v to become healthy", seedTablet.Alias)) return shardSwap.waitForTabletToBeHealthy(seedTablet) }
[ "func", "(", "shardSwap", "*", "shardSchemaSwap", ")", "takeSeedBackup", "(", ")", "(", "err", "error", ")", "{", "shardSwap", ".", "markStepInProgress", "(", "shardSwap", ".", "backupUINode", ")", "\n", "defer", "shardSwap", ".", "markStepDone", "(", "shardSwap", ".", "backupUINode", ",", "&", "err", ")", "\n\n", "tabletList", ":=", "shardSwap", ".", "getTabletList", "(", ")", "\n", "sort", ".", "Sort", "(", "orderTabletsForSwap", "(", "tabletList", ")", ")", "\n", "var", "seedTablet", "*", "topodatapb", ".", "Tablet", "\n", "for", "seedTablet", "==", "nil", "{", "for", "_", ",", "tabletStats", ":=", "range", "tabletList", "{", "swapApplied", ",", "err", ":=", "shardSwap", ".", "isSwapApplied", "(", "tabletStats", ".", "Tablet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "swapApplied", "&&", "getTabletTypeFromStats", "(", "&", "tabletStats", ")", "!=", "topodatapb", ".", "TabletType_MASTER", "{", "seedTablet", "=", "tabletStats", ".", "Tablet", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "seedTablet", "==", "nil", "{", "shardSwap", ".", "addShardLog", "(", "\"", "\"", ")", "\n", "if", "err", ":=", "shardSwap", ".", "applySeedSchemaChange", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n\n", "shardSwap", ".", "addShardLog", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "seedTablet", ".", "Alias", ")", ")", "\n", "eventStream", ",", "err", ":=", "shardSwap", ".", "parent", ".", "tabletClient", ".", "Backup", "(", "shardSwap", ".", "parent", ".", "ctx", ",", "seedTablet", ",", "*", "backupConcurrency", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "waitForBackup", ":", "for", "{", "event", ",", "err", ":=", "eventStream", ".", "Recv", "(", ")", "\n", "switch", "err", "{", "case", "nil", ":", "log", ".", "Infof", "(", "\"", "\"", ",", "seedTablet", ".", "Alias", ",", "logutil", ".", "EventString", "(", "event", ")", ")", "\n", "case", "io", ".", "EOF", ":", "break", "waitForBackup", "\n", "default", ":", "return", "err", "\n", "}", "\n", "}", "\n\n", "shardSwap", ".", "addShardLog", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "seedTablet", ".", "Alias", ")", ")", "\n", "return", "shardSwap", ".", "waitForTabletToBeHealthy", "(", "seedTablet", ")", "\n", "}" ]
// takeSeedBackup takes backup on the seed tablet. The method assumes that the seed tablet is any tablet that // has info that schema swap was already applied on it. This way the function can be re-used if the seed backup // is lost somewhere half way through the schema swap process.
[ "takeSeedBackup", "takes", "backup", "on", "the", "seed", "tablet", ".", "The", "method", "assumes", "that", "the", "seed", "tablet", "is", "any", "tablet", "that", "has", "info", "that", "schema", "swap", "was", "already", "applied", "on", "it", ".", "This", "way", "the", "function", "can", "be", "re", "-", "used", "if", "the", "seed", "backup", "is", "lost", "somewhere", "half", "way", "through", "the", "schema", "swap", "process", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L1072-L1118
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
swapOnTablet
func (shardSwap *shardSchemaSwap) swapOnTablet(tablet *topodatapb.Tablet) error { shardSwap.addPropagationLog(fmt.Sprintf("Restoring tablet %v from backup", tablet.Alias)) eventStream, err := shardSwap.parent.tabletClient.RestoreFromBackup(shardSwap.parent.ctx, tablet) if err != nil { return err } waitForRestore: for { event, err := eventStream.Recv() switch err { case nil: log.Infof("Restore process on tablet %v: %v", tablet.Alias, logutil.EventString(event)) case io.EOF: break waitForRestore default: return err } } // Check if the tablet has restored from a backup with schema change applied. swapApplied, err := shardSwap.isSwapApplied(tablet) if err != nil { return err } if !swapApplied { shardSwap.addPropagationLog(fmt.Sprintf("Tablet %v is restored but doesn't have schema swap applied", tablet.Alias)) return errNoBackupWithSwap } shardSwap.addPropagationLog(fmt.Sprintf("Waiting for tablet %v to become healthy", tablet.Alias)) return shardSwap.waitForTabletToBeHealthy(tablet) }
go
func (shardSwap *shardSchemaSwap) swapOnTablet(tablet *topodatapb.Tablet) error { shardSwap.addPropagationLog(fmt.Sprintf("Restoring tablet %v from backup", tablet.Alias)) eventStream, err := shardSwap.parent.tabletClient.RestoreFromBackup(shardSwap.parent.ctx, tablet) if err != nil { return err } waitForRestore: for { event, err := eventStream.Recv() switch err { case nil: log.Infof("Restore process on tablet %v: %v", tablet.Alias, logutil.EventString(event)) case io.EOF: break waitForRestore default: return err } } // Check if the tablet has restored from a backup with schema change applied. swapApplied, err := shardSwap.isSwapApplied(tablet) if err != nil { return err } if !swapApplied { shardSwap.addPropagationLog(fmt.Sprintf("Tablet %v is restored but doesn't have schema swap applied", tablet.Alias)) return errNoBackupWithSwap } shardSwap.addPropagationLog(fmt.Sprintf("Waiting for tablet %v to become healthy", tablet.Alias)) return shardSwap.waitForTabletToBeHealthy(tablet) }
[ "func", "(", "shardSwap", "*", "shardSchemaSwap", ")", "swapOnTablet", "(", "tablet", "*", "topodatapb", ".", "Tablet", ")", "error", "{", "shardSwap", ".", "addPropagationLog", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "tablet", ".", "Alias", ")", ")", "\n", "eventStream", ",", "err", ":=", "shardSwap", ".", "parent", ".", "tabletClient", ".", "RestoreFromBackup", "(", "shardSwap", ".", "parent", ".", "ctx", ",", "tablet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "waitForRestore", ":", "for", "{", "event", ",", "err", ":=", "eventStream", ".", "Recv", "(", ")", "\n", "switch", "err", "{", "case", "nil", ":", "log", ".", "Infof", "(", "\"", "\"", ",", "tablet", ".", "Alias", ",", "logutil", ".", "EventString", "(", "event", ")", ")", "\n", "case", "io", ".", "EOF", ":", "break", "waitForRestore", "\n", "default", ":", "return", "err", "\n", "}", "\n", "}", "\n", "// Check if the tablet has restored from a backup with schema change applied.", "swapApplied", ",", "err", ":=", "shardSwap", ".", "isSwapApplied", "(", "tablet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "swapApplied", "{", "shardSwap", ".", "addPropagationLog", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "tablet", ".", "Alias", ")", ")", "\n", "return", "errNoBackupWithSwap", "\n", "}", "\n\n", "shardSwap", ".", "addPropagationLog", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "tablet", ".", "Alias", ")", ")", "\n", "return", "shardSwap", ".", "waitForTabletToBeHealthy", "(", "tablet", ")", "\n", "}" ]
// swapOnTablet performs the schema swap on the provided tablet and then waits for it // to become healthy and to catch up with replication.
[ "swapOnTablet", "performs", "the", "schema", "swap", "on", "the", "provided", "tablet", "and", "then", "waits", "for", "it", "to", "become", "healthy", "and", "to", "catch", "up", "with", "replication", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L1122-L1153
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
waitForTabletToBeHealthy
func (shardSwap *shardSchemaSwap) waitForTabletToBeHealthy(tablet *topodatapb.Tablet) error { waitChannel, err := shardSwap.startWaitingOnUnhealthyTablet(tablet) if err != nil { return err } if waitChannel != nil { select { case <-shardSwap.parent.ctx.Done(): return shardSwap.parent.ctx.Err() case <-*waitChannel: // Tablet has caught up, we can return successfully. } } return nil }
go
func (shardSwap *shardSchemaSwap) waitForTabletToBeHealthy(tablet *topodatapb.Tablet) error { waitChannel, err := shardSwap.startWaitingOnUnhealthyTablet(tablet) if err != nil { return err } if waitChannel != nil { select { case <-shardSwap.parent.ctx.Done(): return shardSwap.parent.ctx.Err() case <-*waitChannel: // Tablet has caught up, we can return successfully. } } return nil }
[ "func", "(", "shardSwap", "*", "shardSchemaSwap", ")", "waitForTabletToBeHealthy", "(", "tablet", "*", "topodatapb", ".", "Tablet", ")", "error", "{", "waitChannel", ",", "err", ":=", "shardSwap", ".", "startWaitingOnUnhealthyTablet", "(", "tablet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "waitChannel", "!=", "nil", "{", "select", "{", "case", "<-", "shardSwap", ".", "parent", ".", "ctx", ".", "Done", "(", ")", ":", "return", "shardSwap", ".", "parent", ".", "ctx", ".", "Err", "(", ")", "\n", "case", "<-", "*", "waitChannel", ":", "// Tablet has caught up, we can return successfully.", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// waitForTabletToBeHealthy waits until the given tablet becomes healthy and caught up with // replication. If the tablet is already healthy and caught up when this method is called then // it returns immediately.
[ "waitForTabletToBeHealthy", "waits", "until", "the", "given", "tablet", "becomes", "healthy", "and", "caught", "up", "with", "replication", ".", "If", "the", "tablet", "is", "already", "healthy", "and", "caught", "up", "when", "this", "method", "is", "called", "then", "it", "returns", "immediately", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L1158-L1172
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
updatePropagationProgressUI
func (shardSwap *shardSchemaSwap) updatePropagationProgressUI() { shardSwap.propagationUINode.ProgressMessage = fmt.Sprintf("%v/%v", shardSwap.numTabletsSwapped, shardSwap.numTabletsTotal) if shardSwap.numTabletsTotal == 0 { shardSwap.propagationUINode.Progress = 0 } else { shardSwap.propagationUINode.Progress = shardSwap.numTabletsSwapped * 100 / shardSwap.numTabletsTotal } shardSwap.propagationUINode.BroadcastChanges(false /* updateChildren */) }
go
func (shardSwap *shardSchemaSwap) updatePropagationProgressUI() { shardSwap.propagationUINode.ProgressMessage = fmt.Sprintf("%v/%v", shardSwap.numTabletsSwapped, shardSwap.numTabletsTotal) if shardSwap.numTabletsTotal == 0 { shardSwap.propagationUINode.Progress = 0 } else { shardSwap.propagationUINode.Progress = shardSwap.numTabletsSwapped * 100 / shardSwap.numTabletsTotal } shardSwap.propagationUINode.BroadcastChanges(false /* updateChildren */) }
[ "func", "(", "shardSwap", "*", "shardSchemaSwap", ")", "updatePropagationProgressUI", "(", ")", "{", "shardSwap", ".", "propagationUINode", ".", "ProgressMessage", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "shardSwap", ".", "numTabletsSwapped", ",", "shardSwap", ".", "numTabletsTotal", ")", "\n", "if", "shardSwap", ".", "numTabletsTotal", "==", "0", "{", "shardSwap", ".", "propagationUINode", ".", "Progress", "=", "0", "\n", "}", "else", "{", "shardSwap", ".", "propagationUINode", ".", "Progress", "=", "shardSwap", ".", "numTabletsSwapped", "*", "100", "/", "shardSwap", ".", "numTabletsTotal", "\n", "}", "\n", "shardSwap", ".", "propagationUINode", ".", "BroadcastChanges", "(", "false", "/* updateChildren */", ")", "\n", "}" ]
// updatePropagationProgressUI updates the progress bar in the workflow UI to reflect appropriate // percentage in line with how many tablets have schema swapped already.
[ "updatePropagationProgressUI", "updates", "the", "progress", "bar", "in", "the", "workflow", "UI", "to", "reflect", "appropriate", "percentage", "in", "line", "with", "how", "many", "tablets", "have", "schema", "swapped", "already", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L1176-L1184
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
markPropagationInProgress
func (shardSwap *shardSchemaSwap) markPropagationInProgress() { shardSwap.propagationUINode.Message = "" shardSwap.propagationUINode.State = workflowpb.WorkflowState_Running shardSwap.propagationUINode.Display = workflow.NodeDisplayDeterminate shardSwap.propagationUINode.BroadcastChanges(false /* updateChildren */) }
go
func (shardSwap *shardSchemaSwap) markPropagationInProgress() { shardSwap.propagationUINode.Message = "" shardSwap.propagationUINode.State = workflowpb.WorkflowState_Running shardSwap.propagationUINode.Display = workflow.NodeDisplayDeterminate shardSwap.propagationUINode.BroadcastChanges(false /* updateChildren */) }
[ "func", "(", "shardSwap", "*", "shardSchemaSwap", ")", "markPropagationInProgress", "(", ")", "{", "shardSwap", ".", "propagationUINode", ".", "Message", "=", "\"", "\"", "\n", "shardSwap", ".", "propagationUINode", ".", "State", "=", "workflowpb", ".", "WorkflowState_Running", "\n", "shardSwap", ".", "propagationUINode", ".", "Display", "=", "workflow", ".", "NodeDisplayDeterminate", "\n", "shardSwap", ".", "propagationUINode", ".", "BroadcastChanges", "(", "false", "/* updateChildren */", ")", "\n", "}" ]
// markPropagationInProgress marks the propagation step of the shard schema swap workflow as running.
[ "markPropagationInProgress", "marks", "the", "propagation", "step", "of", "the", "shard", "schema", "swap", "workflow", "as", "running", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L1187-L1192
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
addPropagationLog
func (shardSwap *shardSchemaSwap) addPropagationLog(message string) { shardSwap.propagationUILogger.Infof(message) shardSwap.propagationUINode.Log = shardSwap.propagationUILogger.String() shardSwap.propagationUINode.Message = message shardSwap.propagationUINode.BroadcastChanges(false /* updateChildren */) shardSwap.addShardLog(message) }
go
func (shardSwap *shardSchemaSwap) addPropagationLog(message string) { shardSwap.propagationUILogger.Infof(message) shardSwap.propagationUINode.Log = shardSwap.propagationUILogger.String() shardSwap.propagationUINode.Message = message shardSwap.propagationUINode.BroadcastChanges(false /* updateChildren */) shardSwap.addShardLog(message) }
[ "func", "(", "shardSwap", "*", "shardSchemaSwap", ")", "addPropagationLog", "(", "message", "string", ")", "{", "shardSwap", ".", "propagationUILogger", ".", "Infof", "(", "message", ")", "\n", "shardSwap", ".", "propagationUINode", ".", "Log", "=", "shardSwap", ".", "propagationUILogger", ".", "String", "(", ")", "\n", "shardSwap", ".", "propagationUINode", ".", "Message", "=", "message", "\n", "shardSwap", ".", "propagationUINode", ".", "BroadcastChanges", "(", "false", "/* updateChildren */", ")", "\n", "shardSwap", ".", "addShardLog", "(", "message", ")", "\n", "}" ]
// addPropagationLog prints the message to logs, adds it to logs displayed in the UI on the "Propagate to all tablets" // node and adds the message to the logs displayed on the overall shard node, so that everything happening to this // shard was visible in one log.
[ "addPropagationLog", "prints", "the", "message", "to", "logs", "adds", "it", "to", "logs", "displayed", "in", "the", "UI", "on", "the", "Propagate", "to", "all", "tablets", "node", "and", "adds", "the", "message", "to", "the", "logs", "displayed", "on", "the", "overall", "shard", "node", "so", "that", "everything", "happening", "to", "this", "shard", "was", "visible", "in", "one", "log", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L1197-L1203
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
markPropagationDone
func (shardSwap *shardSchemaSwap) markPropagationDone(err *error) { if *err != nil { msg := fmt.Sprintf("Error: %v", *err) shardSwap.addPropagationLog(msg) shardSwap.propagationUINode.Message = msg shardSwap.propagationUINode.State = workflowpb.WorkflowState_Done } else if shardSwap.numTabletsSwapped == shardSwap.numTabletsTotal { shardSwap.propagationUINode.State = workflowpb.WorkflowState_Done } shardSwap.propagationUINode.BroadcastChanges(false /* updateChildren */) }
go
func (shardSwap *shardSchemaSwap) markPropagationDone(err *error) { if *err != nil { msg := fmt.Sprintf("Error: %v", *err) shardSwap.addPropagationLog(msg) shardSwap.propagationUINode.Message = msg shardSwap.propagationUINode.State = workflowpb.WorkflowState_Done } else if shardSwap.numTabletsSwapped == shardSwap.numTabletsTotal { shardSwap.propagationUINode.State = workflowpb.WorkflowState_Done } shardSwap.propagationUINode.BroadcastChanges(false /* updateChildren */) }
[ "func", "(", "shardSwap", "*", "shardSchemaSwap", ")", "markPropagationDone", "(", "err", "*", "error", ")", "{", "if", "*", "err", "!=", "nil", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "*", "err", ")", "\n", "shardSwap", ".", "addPropagationLog", "(", "msg", ")", "\n", "shardSwap", ".", "propagationUINode", ".", "Message", "=", "msg", "\n", "shardSwap", ".", "propagationUINode", ".", "State", "=", "workflowpb", ".", "WorkflowState_Done", "\n", "}", "else", "if", "shardSwap", ".", "numTabletsSwapped", "==", "shardSwap", ".", "numTabletsTotal", "{", "shardSwap", ".", "propagationUINode", ".", "State", "=", "workflowpb", ".", "WorkflowState_Done", "\n", "}", "\n", "shardSwap", ".", "propagationUINode", ".", "BroadcastChanges", "(", "false", "/* updateChildren */", ")", "\n", "}" ]
// markPropagationDone marks the propagation step of the shard schema swap workflow as finished successfully // or with an error.
[ "markPropagationDone", "marks", "the", "propagation", "step", "of", "the", "shard", "schema", "swap", "workflow", "as", "finished", "successfully", "or", "with", "an", "error", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L1207-L1217
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
propagateToAllTablets
func (shardSwap *shardSchemaSwap) propagateToAllTablets(withMasterReparent bool) (err error) { shardSwap.markPropagationInProgress() defer shardSwap.markPropagationDone(&err) for { shardSwap.updatePropagationProgressUI() tablet, err := shardSwap.findNextTabletToSwap() // Update UI immediately after finding next tablet because the total number of tablets or // the number of tablets with swapped schema can change in it. shardSwap.updatePropagationProgressUI() if err == errOnlyMasterLeft { if withMasterReparent { err = shardSwap.reparentFromMaster(tablet) if err != nil { return err } } else { return nil } } if err == nil { if tablet == nil { shardSwap.propagationUINode.Message = "" shardSwap.propagationUINode.BroadcastChanges(false /* updateChildren */) return nil } err = shardSwap.swapOnTablet(tablet) if err == nil { shardSwap.numTabletsSwapped++ shardSwap.addPropagationLog(fmt.Sprintf("Schema is successfully swapped on tablet %v.", tablet.Alias)) continue } if err == errNoBackupWithSwap { if err := shardSwap.takeSeedBackup(); err != nil { return err } continue } shardSwap.addPropagationLog(fmt.Sprintf("Error swapping schema on tablet %v: %v", tablet.Alias, err)) } else { shardSwap.addPropagationLog(fmt.Sprintf("Error searching for next tablet to swap schema on: %v.", err)) } shardSwap.addPropagationLog(fmt.Sprintf("Sleeping for %v.", *delayBetweenErrors)) select { case <-shardSwap.parent.ctx.Done(): return shardSwap.parent.ctx.Err() case <-time.After(*delayBetweenErrors): // Waiting is done going to the next loop. } shardSwap.propagationUINode.Message = "" shardSwap.propagationUINode.BroadcastChanges(false /* updateChildren */) } }
go
func (shardSwap *shardSchemaSwap) propagateToAllTablets(withMasterReparent bool) (err error) { shardSwap.markPropagationInProgress() defer shardSwap.markPropagationDone(&err) for { shardSwap.updatePropagationProgressUI() tablet, err := shardSwap.findNextTabletToSwap() // Update UI immediately after finding next tablet because the total number of tablets or // the number of tablets with swapped schema can change in it. shardSwap.updatePropagationProgressUI() if err == errOnlyMasterLeft { if withMasterReparent { err = shardSwap.reparentFromMaster(tablet) if err != nil { return err } } else { return nil } } if err == nil { if tablet == nil { shardSwap.propagationUINode.Message = "" shardSwap.propagationUINode.BroadcastChanges(false /* updateChildren */) return nil } err = shardSwap.swapOnTablet(tablet) if err == nil { shardSwap.numTabletsSwapped++ shardSwap.addPropagationLog(fmt.Sprintf("Schema is successfully swapped on tablet %v.", tablet.Alias)) continue } if err == errNoBackupWithSwap { if err := shardSwap.takeSeedBackup(); err != nil { return err } continue } shardSwap.addPropagationLog(fmt.Sprintf("Error swapping schema on tablet %v: %v", tablet.Alias, err)) } else { shardSwap.addPropagationLog(fmt.Sprintf("Error searching for next tablet to swap schema on: %v.", err)) } shardSwap.addPropagationLog(fmt.Sprintf("Sleeping for %v.", *delayBetweenErrors)) select { case <-shardSwap.parent.ctx.Done(): return shardSwap.parent.ctx.Err() case <-time.After(*delayBetweenErrors): // Waiting is done going to the next loop. } shardSwap.propagationUINode.Message = "" shardSwap.propagationUINode.BroadcastChanges(false /* updateChildren */) } }
[ "func", "(", "shardSwap", "*", "shardSchemaSwap", ")", "propagateToAllTablets", "(", "withMasterReparent", "bool", ")", "(", "err", "error", ")", "{", "shardSwap", ".", "markPropagationInProgress", "(", ")", "\n", "defer", "shardSwap", ".", "markPropagationDone", "(", "&", "err", ")", "\n\n", "for", "{", "shardSwap", ".", "updatePropagationProgressUI", "(", ")", "\n", "tablet", ",", "err", ":=", "shardSwap", ".", "findNextTabletToSwap", "(", ")", "\n", "// Update UI immediately after finding next tablet because the total number of tablets or", "// the number of tablets with swapped schema can change in it.", "shardSwap", ".", "updatePropagationProgressUI", "(", ")", "\n", "if", "err", "==", "errOnlyMasterLeft", "{", "if", "withMasterReparent", "{", "err", "=", "shardSwap", ".", "reparentFromMaster", "(", "tablet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "else", "{", "return", "nil", "\n", "}", "\n", "}", "\n", "if", "err", "==", "nil", "{", "if", "tablet", "==", "nil", "{", "shardSwap", ".", "propagationUINode", ".", "Message", "=", "\"", "\"", "\n", "shardSwap", ".", "propagationUINode", ".", "BroadcastChanges", "(", "false", "/* updateChildren */", ")", "\n", "return", "nil", "\n", "}", "\n", "err", "=", "shardSwap", ".", "swapOnTablet", "(", "tablet", ")", "\n", "if", "err", "==", "nil", "{", "shardSwap", ".", "numTabletsSwapped", "++", "\n", "shardSwap", ".", "addPropagationLog", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "tablet", ".", "Alias", ")", ")", "\n", "continue", "\n", "}", "\n", "if", "err", "==", "errNoBackupWithSwap", "{", "if", "err", ":=", "shardSwap", ".", "takeSeedBackup", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "continue", "\n", "}", "\n", "shardSwap", ".", "addPropagationLog", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "tablet", ".", "Alias", ",", "err", ")", ")", "\n", "}", "else", "{", "shardSwap", ".", "addPropagationLog", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n\n", "shardSwap", ".", "addPropagationLog", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "*", "delayBetweenErrors", ")", ")", "\n", "select", "{", "case", "<-", "shardSwap", ".", "parent", ".", "ctx", ".", "Done", "(", ")", ":", "return", "shardSwap", ".", "parent", ".", "ctx", ".", "Err", "(", ")", "\n", "case", "<-", "time", ".", "After", "(", "*", "delayBetweenErrors", ")", ":", "// Waiting is done going to the next loop.", "}", "\n", "shardSwap", ".", "propagationUINode", ".", "Message", "=", "\"", "\"", "\n", "shardSwap", ".", "propagationUINode", ".", "BroadcastChanges", "(", "false", "/* updateChildren */", ")", "\n", "}", "\n", "}" ]
// propagateToNonMasterTablets propagates the schema change to all non-master tablets // in the shard. When it returns nil it means that only master can remain left with the // old schema, everything else is verified to have schema swap applied.
[ "propagateToNonMasterTablets", "propagates", "the", "schema", "change", "to", "all", "non", "-", "master", "tablets", "in", "the", "shard", ".", "When", "it", "returns", "nil", "it", "means", "that", "only", "master", "can", "remain", "left", "with", "the", "old", "schema", "everything", "else", "is", "verified", "to", "have", "schema", "swap", "applied", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L1222-L1275
train
vitessio/vitess
go/vt/schemamanager/schemaswap/schema_swap.go
reparentFromMaster
func (shardSwap *shardSchemaSwap) reparentFromMaster(masterTablet *topodatapb.Tablet) (err error) { shardSwap.markStepInProgress(shardSwap.reparentUINode) defer shardSwap.markStepDone(shardSwap.reparentUINode, &err) shardSwap.addShardLog(fmt.Sprintf("Reparenting away from master %v", masterTablet.Alias)) if *mysqlctl.DisableActiveReparents { hk := &hook.Hook{ Name: "reparent_away", } hookResult, err := shardSwap.parent.tabletClient.ExecuteHook(shardSwap.parent.ctx, masterTablet, hk) if err != nil { return err } if hookResult.ExitStatus != hook.HOOK_SUCCESS { return fmt.Errorf("error executing 'reparent_away' hook: %v", hookResult.String()) } } else { wr := wrangler.New(logutil.NewConsoleLogger(), shardSwap.parent.topoServer, shardSwap.parent.tabletClient) err = wr.PlannedReparentShard( shardSwap.parent.ctx, shardSwap.parent.keyspace, shardSwap.shardName, nil, /* masterElectTabletAlias */ masterTablet.Alias, /* avoidMasterAlias */ *reparentTimeout) if err != nil { return err } } return nil }
go
func (shardSwap *shardSchemaSwap) reparentFromMaster(masterTablet *topodatapb.Tablet) (err error) { shardSwap.markStepInProgress(shardSwap.reparentUINode) defer shardSwap.markStepDone(shardSwap.reparentUINode, &err) shardSwap.addShardLog(fmt.Sprintf("Reparenting away from master %v", masterTablet.Alias)) if *mysqlctl.DisableActiveReparents { hk := &hook.Hook{ Name: "reparent_away", } hookResult, err := shardSwap.parent.tabletClient.ExecuteHook(shardSwap.parent.ctx, masterTablet, hk) if err != nil { return err } if hookResult.ExitStatus != hook.HOOK_SUCCESS { return fmt.Errorf("error executing 'reparent_away' hook: %v", hookResult.String()) } } else { wr := wrangler.New(logutil.NewConsoleLogger(), shardSwap.parent.topoServer, shardSwap.parent.tabletClient) err = wr.PlannedReparentShard( shardSwap.parent.ctx, shardSwap.parent.keyspace, shardSwap.shardName, nil, /* masterElectTabletAlias */ masterTablet.Alias, /* avoidMasterAlias */ *reparentTimeout) if err != nil { return err } } return nil }
[ "func", "(", "shardSwap", "*", "shardSchemaSwap", ")", "reparentFromMaster", "(", "masterTablet", "*", "topodatapb", ".", "Tablet", ")", "(", "err", "error", ")", "{", "shardSwap", ".", "markStepInProgress", "(", "shardSwap", ".", "reparentUINode", ")", "\n", "defer", "shardSwap", ".", "markStepDone", "(", "shardSwap", ".", "reparentUINode", ",", "&", "err", ")", "\n\n", "shardSwap", ".", "addShardLog", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "masterTablet", ".", "Alias", ")", ")", "\n", "if", "*", "mysqlctl", ".", "DisableActiveReparents", "{", "hk", ":=", "&", "hook", ".", "Hook", "{", "Name", ":", "\"", "\"", ",", "}", "\n", "hookResult", ",", "err", ":=", "shardSwap", ".", "parent", ".", "tabletClient", ".", "ExecuteHook", "(", "shardSwap", ".", "parent", ".", "ctx", ",", "masterTablet", ",", "hk", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "hookResult", ".", "ExitStatus", "!=", "hook", ".", "HOOK_SUCCESS", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hookResult", ".", "String", "(", ")", ")", "\n", "}", "\n", "}", "else", "{", "wr", ":=", "wrangler", ".", "New", "(", "logutil", ".", "NewConsoleLogger", "(", ")", ",", "shardSwap", ".", "parent", ".", "topoServer", ",", "shardSwap", ".", "parent", ".", "tabletClient", ")", "\n", "err", "=", "wr", ".", "PlannedReparentShard", "(", "shardSwap", ".", "parent", ".", "ctx", ",", "shardSwap", ".", "parent", ".", "keyspace", ",", "shardSwap", ".", "shardName", ",", "nil", ",", "/* masterElectTabletAlias */", "masterTablet", ".", "Alias", ",", "/* avoidMasterAlias */", "*", "reparentTimeout", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// propagateToMaster propagates the schema change to the master. If the master already has // the schema change applied then the method does nothing.
[ "propagateToMaster", "propagates", "the", "schema", "change", "to", "the", "master", ".", "If", "the", "master", "already", "has", "the", "schema", "change", "applied", "then", "the", "method", "does", "nothing", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/schemamanager/schemaswap/schema_swap.go#L1279-L1309
train
vitessio/vitess
go/vt/binlog/slave_connection.go
connectForReplication
func connectForReplication(cp *mysql.ConnParams) (*mysql.Conn, error) { params, err := dbconfigs.WithCredentials(cp) if err != nil { return nil, err } ctx := context.Background() conn, err := mysql.Connect(ctx, params) if err != nil { return nil, err } // Tell the server that we understand the format of events // that will be used if binlog_checksum is enabled on the server. if _, err := conn.ExecuteFetch("SET @master_binlog_checksum=@@global.binlog_checksum", 0, false); err != nil { return nil, fmt.Errorf("failed to set @master_binlog_checksum=@@global.binlog_checksum: %v", err) } return conn, nil }
go
func connectForReplication(cp *mysql.ConnParams) (*mysql.Conn, error) { params, err := dbconfigs.WithCredentials(cp) if err != nil { return nil, err } ctx := context.Background() conn, err := mysql.Connect(ctx, params) if err != nil { return nil, err } // Tell the server that we understand the format of events // that will be used if binlog_checksum is enabled on the server. if _, err := conn.ExecuteFetch("SET @master_binlog_checksum=@@global.binlog_checksum", 0, false); err != nil { return nil, fmt.Errorf("failed to set @master_binlog_checksum=@@global.binlog_checksum: %v", err) } return conn, nil }
[ "func", "connectForReplication", "(", "cp", "*", "mysql", ".", "ConnParams", ")", "(", "*", "mysql", ".", "Conn", ",", "error", ")", "{", "params", ",", "err", ":=", "dbconfigs", ".", "WithCredentials", "(", "cp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "conn", ",", "err", ":=", "mysql", ".", "Connect", "(", "ctx", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Tell the server that we understand the format of events", "// that will be used if binlog_checksum is enabled on the server.", "if", "_", ",", "err", ":=", "conn", ".", "ExecuteFetch", "(", "\"", "\"", ",", "0", ",", "false", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "conn", ",", "nil", "\n", "}" ]
// connectForReplication create a MySQL connection ready to use for replication.
[ "connectForReplication", "create", "a", "MySQL", "connection", "ready", "to", "use", "for", "replication", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/binlog/slave_connection.go#L72-L91
train
vitessio/vitess
go/vt/binlog/slave_connection.go
StartBinlogDumpFromCurrent
func (sc *SlaveConnection) StartBinlogDumpFromCurrent(ctx context.Context) (mysql.Position, <-chan mysql.BinlogEvent, error) { ctx, sc.cancel = context.WithCancel(ctx) masterPosition, err := sc.Conn.MasterPosition() if err != nil { return mysql.Position{}, nil, fmt.Errorf("failed to get master position: %v", err) } c, err := sc.StartBinlogDumpFromPosition(ctx, masterPosition) return masterPosition, c, err }
go
func (sc *SlaveConnection) StartBinlogDumpFromCurrent(ctx context.Context) (mysql.Position, <-chan mysql.BinlogEvent, error) { ctx, sc.cancel = context.WithCancel(ctx) masterPosition, err := sc.Conn.MasterPosition() if err != nil { return mysql.Position{}, nil, fmt.Errorf("failed to get master position: %v", err) } c, err := sc.StartBinlogDumpFromPosition(ctx, masterPosition) return masterPosition, c, err }
[ "func", "(", "sc", "*", "SlaveConnection", ")", "StartBinlogDumpFromCurrent", "(", "ctx", "context", ".", "Context", ")", "(", "mysql", ".", "Position", ",", "<-", "chan", "mysql", ".", "BinlogEvent", ",", "error", ")", "{", "ctx", ",", "sc", ".", "cancel", "=", "context", ".", "WithCancel", "(", "ctx", ")", "\n\n", "masterPosition", ",", "err", ":=", "sc", ".", "Conn", ".", "MasterPosition", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "mysql", ".", "Position", "{", "}", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "c", ",", "err", ":=", "sc", ".", "StartBinlogDumpFromPosition", "(", "ctx", ",", "masterPosition", ")", "\n", "return", "masterPosition", ",", "c", ",", "err", "\n", "}" ]
// StartBinlogDumpFromCurrent requests a replication binlog dump from // the current position.
[ "StartBinlogDumpFromCurrent", "requests", "a", "replication", "binlog", "dump", "from", "the", "current", "position", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/binlog/slave_connection.go#L98-L108
train
vitessio/vitess
go/vt/binlog/slave_connection.go
StartBinlogDumpFromPosition
func (sc *SlaveConnection) StartBinlogDumpFromPosition(ctx context.Context, startPos mysql.Position) (<-chan mysql.BinlogEvent, error) { ctx, sc.cancel = context.WithCancel(ctx) log.Infof("sending binlog dump command: startPos=%v, slaveID=%v", startPos, sc.slaveID) if err := sc.SendBinlogDumpCommand(sc.slaveID, startPos); err != nil { log.Errorf("couldn't send binlog dump command: %v", err) return nil, err } return sc.streamEvents(ctx), nil }
go
func (sc *SlaveConnection) StartBinlogDumpFromPosition(ctx context.Context, startPos mysql.Position) (<-chan mysql.BinlogEvent, error) { ctx, sc.cancel = context.WithCancel(ctx) log.Infof("sending binlog dump command: startPos=%v, slaveID=%v", startPos, sc.slaveID) if err := sc.SendBinlogDumpCommand(sc.slaveID, startPos); err != nil { log.Errorf("couldn't send binlog dump command: %v", err) return nil, err } return sc.streamEvents(ctx), nil }
[ "func", "(", "sc", "*", "SlaveConnection", ")", "StartBinlogDumpFromPosition", "(", "ctx", "context", ".", "Context", ",", "startPos", "mysql", ".", "Position", ")", "(", "<-", "chan", "mysql", ".", "BinlogEvent", ",", "error", ")", "{", "ctx", ",", "sc", ".", "cancel", "=", "context", ".", "WithCancel", "(", "ctx", ")", "\n\n", "log", ".", "Infof", "(", "\"", "\"", ",", "startPos", ",", "sc", ".", "slaveID", ")", "\n", "if", "err", ":=", "sc", ".", "SendBinlogDumpCommand", "(", "sc", ".", "slaveID", ",", "startPos", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "sc", ".", "streamEvents", "(", "ctx", ")", ",", "nil", "\n", "}" ]
// StartBinlogDumpFromPosition requests a replication binlog dump from // the master mysqld at the given Position and then sends binlog // events to the provided channel. // The stream will continue in the background, waiting for new events if // necessary, until the connection is closed, either by the master or // by canceling the context. // // Note the context is valid and used until eventChan is closed.
[ "StartBinlogDumpFromPosition", "requests", "a", "replication", "binlog", "dump", "from", "the", "master", "mysqld", "at", "the", "given", "Position", "and", "then", "sends", "binlog", "events", "to", "the", "provided", "channel", ".", "The", "stream", "will", "continue", "in", "the", "background", "waiting", "for", "new", "events", "if", "necessary", "until", "the", "connection", "is", "closed", "either", "by", "the", "master", "or", "by", "canceling", "the", "context", ".", "Note", "the", "context", "is", "valid", "and", "used", "until", "eventChan", "is", "closed", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/binlog/slave_connection.go#L118-L128
train
vitessio/vitess
go/vt/binlog/slave_connection.go
streamEvents
func (sc *SlaveConnection) streamEvents(ctx context.Context) chan mysql.BinlogEvent { // FIXME(alainjobart) I think we can use a buffered channel for better performance. eventChan := make(chan mysql.BinlogEvent) // Start reading events. sc.wg.Add(1) go func() { defer func() { close(eventChan) sc.wg.Done() }() for { event, err := sc.Conn.ReadBinlogEvent() if err != nil { if sqlErr, ok := err.(*mysql.SQLError); ok && sqlErr.Number() == mysql.CRServerLost { // CRServerLost = Lost connection to MySQL server during query // This is not necessarily an error. It could just be that we closed // the connection from outside. log.Infof("connection closed during binlog stream (possibly intentional): %v", err) return } log.Errorf("read error while streaming binlog events: %v", err) return } select { case eventChan <- event: case <-ctx.Done(): return } } }() return eventChan }
go
func (sc *SlaveConnection) streamEvents(ctx context.Context) chan mysql.BinlogEvent { // FIXME(alainjobart) I think we can use a buffered channel for better performance. eventChan := make(chan mysql.BinlogEvent) // Start reading events. sc.wg.Add(1) go func() { defer func() { close(eventChan) sc.wg.Done() }() for { event, err := sc.Conn.ReadBinlogEvent() if err != nil { if sqlErr, ok := err.(*mysql.SQLError); ok && sqlErr.Number() == mysql.CRServerLost { // CRServerLost = Lost connection to MySQL server during query // This is not necessarily an error. It could just be that we closed // the connection from outside. log.Infof("connection closed during binlog stream (possibly intentional): %v", err) return } log.Errorf("read error while streaming binlog events: %v", err) return } select { case eventChan <- event: case <-ctx.Done(): return } } }() return eventChan }
[ "func", "(", "sc", "*", "SlaveConnection", ")", "streamEvents", "(", "ctx", "context", ".", "Context", ")", "chan", "mysql", ".", "BinlogEvent", "{", "// FIXME(alainjobart) I think we can use a buffered channel for better performance.", "eventChan", ":=", "make", "(", "chan", "mysql", ".", "BinlogEvent", ")", "\n\n", "// Start reading events.", "sc", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "defer", "func", "(", ")", "{", "close", "(", "eventChan", ")", "\n", "sc", ".", "wg", ".", "Done", "(", ")", "\n", "}", "(", ")", "\n", "for", "{", "event", ",", "err", ":=", "sc", ".", "Conn", ".", "ReadBinlogEvent", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "sqlErr", ",", "ok", ":=", "err", ".", "(", "*", "mysql", ".", "SQLError", ")", ";", "ok", "&&", "sqlErr", ".", "Number", "(", ")", "==", "mysql", ".", "CRServerLost", "{", "// CRServerLost = Lost connection to MySQL server during query", "// This is not necessarily an error. It could just be that we closed", "// the connection from outside.", "log", ".", "Infof", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "select", "{", "case", "eventChan", "<-", "event", ":", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "return", "eventChan", "\n", "}" ]
// streamEvents returns a channel on which events are streamed.
[ "streamEvents", "returns", "a", "channel", "on", "which", "events", "are", "streamed", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/binlog/slave_connection.go#L131-L164
train
vitessio/vitess
go/vt/throttler/interval_history.go
average
func (h *intervalHistory) average(from, to time.Time) float64 { // Search only entries whose time of observation is in [start, end). // Example: [from, to) = [1.5s, 2.5s) => [start, end) = [1s, 2s) start := from.Truncate(h.interval) end := to.Truncate(h.interval) sum := 0.0 count := 0.0 var nextIntervalStart time.Time for i := len(h.records) - 1; i >= 0; i-- { t := h.records[i].time if t.After(end) { continue } if t.Before(start) { break } // Account for intervals which were not recorded. if !nextIntervalStart.IsZero() { uncoveredRange := nextIntervalStart.Sub(t) count += float64(uncoveredRange / h.interval) } // If an interval is only partially included, count only that fraction. durationAfterTo := t.Add(h.interval).Sub(to) if durationAfterTo < 0 { durationAfterTo = 0 } durationBeforeFrom := from.Sub(t) if durationBeforeFrom < 0 { durationBeforeFrom = 0 } weight := float64((h.interval - durationBeforeFrom - durationAfterTo).Nanoseconds()) / float64(h.interval.Nanoseconds()) sum += weight * float64(h.records[i].value) count += weight nextIntervalStart = t.Add(-1 * h.interval) } return float64(sum) / count }
go
func (h *intervalHistory) average(from, to time.Time) float64 { // Search only entries whose time of observation is in [start, end). // Example: [from, to) = [1.5s, 2.5s) => [start, end) = [1s, 2s) start := from.Truncate(h.interval) end := to.Truncate(h.interval) sum := 0.0 count := 0.0 var nextIntervalStart time.Time for i := len(h.records) - 1; i >= 0; i-- { t := h.records[i].time if t.After(end) { continue } if t.Before(start) { break } // Account for intervals which were not recorded. if !nextIntervalStart.IsZero() { uncoveredRange := nextIntervalStart.Sub(t) count += float64(uncoveredRange / h.interval) } // If an interval is only partially included, count only that fraction. durationAfterTo := t.Add(h.interval).Sub(to) if durationAfterTo < 0 { durationAfterTo = 0 } durationBeforeFrom := from.Sub(t) if durationBeforeFrom < 0 { durationBeforeFrom = 0 } weight := float64((h.interval - durationBeforeFrom - durationAfterTo).Nanoseconds()) / float64(h.interval.Nanoseconds()) sum += weight * float64(h.records[i].value) count += weight nextIntervalStart = t.Add(-1 * h.interval) } return float64(sum) / count }
[ "func", "(", "h", "*", "intervalHistory", ")", "average", "(", "from", ",", "to", "time", ".", "Time", ")", "float64", "{", "// Search only entries whose time of observation is in [start, end).", "// Example: [from, to) = [1.5s, 2.5s) => [start, end) = [1s, 2s)", "start", ":=", "from", ".", "Truncate", "(", "h", ".", "interval", ")", "\n", "end", ":=", "to", ".", "Truncate", "(", "h", ".", "interval", ")", "\n\n", "sum", ":=", "0.0", "\n", "count", ":=", "0.0", "\n", "var", "nextIntervalStart", "time", ".", "Time", "\n", "for", "i", ":=", "len", "(", "h", ".", "records", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "t", ":=", "h", ".", "records", "[", "i", "]", ".", "time", "\n\n", "if", "t", ".", "After", "(", "end", ")", "{", "continue", "\n", "}", "\n", "if", "t", ".", "Before", "(", "start", ")", "{", "break", "\n", "}", "\n\n", "// Account for intervals which were not recorded.", "if", "!", "nextIntervalStart", ".", "IsZero", "(", ")", "{", "uncoveredRange", ":=", "nextIntervalStart", ".", "Sub", "(", "t", ")", "\n", "count", "+=", "float64", "(", "uncoveredRange", "/", "h", ".", "interval", ")", "\n", "}", "\n\n", "// If an interval is only partially included, count only that fraction.", "durationAfterTo", ":=", "t", ".", "Add", "(", "h", ".", "interval", ")", ".", "Sub", "(", "to", ")", "\n", "if", "durationAfterTo", "<", "0", "{", "durationAfterTo", "=", "0", "\n", "}", "\n", "durationBeforeFrom", ":=", "from", ".", "Sub", "(", "t", ")", "\n", "if", "durationBeforeFrom", "<", "0", "{", "durationBeforeFrom", "=", "0", "\n", "}", "\n", "weight", ":=", "float64", "(", "(", "h", ".", "interval", "-", "durationBeforeFrom", "-", "durationAfterTo", ")", ".", "Nanoseconds", "(", ")", ")", "/", "float64", "(", "h", ".", "interval", ".", "Nanoseconds", "(", ")", ")", "\n\n", "sum", "+=", "weight", "*", "float64", "(", "h", ".", "records", "[", "i", "]", ".", "value", ")", "\n", "count", "+=", "weight", "\n", "nextIntervalStart", "=", "t", ".", "Add", "(", "-", "1", "*", "h", ".", "interval", ")", "\n", "}", "\n\n", "return", "float64", "(", "sum", ")", "/", "count", "\n", "}" ]
// average returns the average value across all observations which span // the range [from, to). // Partially included observations are accounted by their included fraction. // Missing observations are assumed with the value zero.
[ "average", "returns", "the", "average", "value", "across", "all", "observations", "which", "span", "the", "range", "[", "from", "to", ")", ".", "Partially", "included", "observations", "are", "accounted", "by", "their", "included", "fraction", ".", "Missing", "observations", "are", "assumed", "with", "the", "value", "zero", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/interval_history.go#L64-L106
train
vitessio/vitess
go/vt/vttime/time_clock.go
Now
func (t TimeClock) Now() (Interval, error) { now := time.Now() return NewInterval(now.Add(-(*uncertainty)), now.Add(*uncertainty)) }
go
func (t TimeClock) Now() (Interval, error) { now := time.Now() return NewInterval(now.Add(-(*uncertainty)), now.Add(*uncertainty)) }
[ "func", "(", "t", "TimeClock", ")", "Now", "(", ")", "(", "Interval", ",", "error", ")", "{", "now", ":=", "time", ".", "Now", "(", ")", "\n", "return", "NewInterval", "(", "now", ".", "Add", "(", "-", "(", "*", "uncertainty", ")", ")", ",", "now", ".", "Add", "(", "*", "uncertainty", ")", ")", "\n", "}" ]
// Now is part of the Clock interface.
[ "Now", "is", "part", "of", "the", "Clock", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttime/time_clock.go#L33-L36
train
vitessio/vitess
go/vt/vttablet/tabletmanager/rpc_replication.go
SlaveStatus
func (agent *ActionAgent) SlaveStatus(ctx context.Context) (*replicationdatapb.Status, error) { status, err := agent.MysqlDaemon.SlaveStatus() if err != nil { return nil, err } return mysql.SlaveStatusToProto(status), nil }
go
func (agent *ActionAgent) SlaveStatus(ctx context.Context) (*replicationdatapb.Status, error) { status, err := agent.MysqlDaemon.SlaveStatus() if err != nil { return nil, err } return mysql.SlaveStatusToProto(status), nil }
[ "func", "(", "agent", "*", "ActionAgent", ")", "SlaveStatus", "(", "ctx", "context", ".", "Context", ")", "(", "*", "replicationdatapb", ".", "Status", ",", "error", ")", "{", "status", ",", "err", ":=", "agent", ".", "MysqlDaemon", ".", "SlaveStatus", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "mysql", ".", "SlaveStatusToProto", "(", "status", ")", ",", "nil", "\n", "}" ]
// SlaveStatus returns the replication status
[ "SlaveStatus", "returns", "the", "replication", "status" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/rpc_replication.go#L45-L51
train
vitessio/vitess
go/vt/vttablet/tabletmanager/rpc_replication.go
MasterPosition
func (agent *ActionAgent) MasterPosition(ctx context.Context) (string, error) { pos, err := agent.MysqlDaemon.MasterPosition() if err != nil { return "", err } return mysql.EncodePosition(pos), nil }
go
func (agent *ActionAgent) MasterPosition(ctx context.Context) (string, error) { pos, err := agent.MysqlDaemon.MasterPosition() if err != nil { return "", err } return mysql.EncodePosition(pos), nil }
[ "func", "(", "agent", "*", "ActionAgent", ")", "MasterPosition", "(", "ctx", "context", ".", "Context", ")", "(", "string", ",", "error", ")", "{", "pos", ",", "err", ":=", "agent", ".", "MysqlDaemon", ".", "MasterPosition", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "mysql", ".", "EncodePosition", "(", "pos", ")", ",", "nil", "\n", "}" ]
// MasterPosition returns the master position
[ "MasterPosition", "returns", "the", "master", "position" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/rpc_replication.go#L54-L60
train
vitessio/vitess
go/vt/vttablet/tabletmanager/rpc_replication.go
StartSlaveUntilAfter
func (agent *ActionAgent) StartSlaveUntilAfter(ctx context.Context, position string, waitTime time.Duration) error { if err := agent.lock(ctx); err != nil { return err } defer agent.unlock() waitCtx, cancel := context.WithTimeout(ctx, waitTime) defer cancel() pos, err := mysql.DecodePosition(position) if err != nil { return err } return agent.MysqlDaemon.StartSlaveUntilAfter(waitCtx, pos) }
go
func (agent *ActionAgent) StartSlaveUntilAfter(ctx context.Context, position string, waitTime time.Duration) error { if err := agent.lock(ctx); err != nil { return err } defer agent.unlock() waitCtx, cancel := context.WithTimeout(ctx, waitTime) defer cancel() pos, err := mysql.DecodePosition(position) if err != nil { return err } return agent.MysqlDaemon.StartSlaveUntilAfter(waitCtx, pos) }
[ "func", "(", "agent", "*", "ActionAgent", ")", "StartSlaveUntilAfter", "(", "ctx", "context", ".", "Context", ",", "position", "string", ",", "waitTime", "time", ".", "Duration", ")", "error", "{", "if", "err", ":=", "agent", ".", "lock", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "agent", ".", "unlock", "(", ")", "\n\n", "waitCtx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "ctx", ",", "waitTime", ")", "\n", "defer", "cancel", "(", ")", "\n\n", "pos", ",", "err", ":=", "mysql", ".", "DecodePosition", "(", "position", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "agent", ".", "MysqlDaemon", ".", "StartSlaveUntilAfter", "(", "waitCtx", ",", "pos", ")", "\n", "}" ]
// StartSlaveUntilAfter will start the replication and let it catch up // until and including the transactions in `position`
[ "StartSlaveUntilAfter", "will", "start", "the", "replication", "and", "let", "it", "catch", "up", "until", "and", "including", "the", "transactions", "in", "position" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/rpc_replication.go#L150-L165
train
vitessio/vitess
go/vt/vttablet/tabletmanager/rpc_replication.go
GetSlaves
func (agent *ActionAgent) GetSlaves(ctx context.Context) ([]string, error) { return mysqlctl.FindSlaves(agent.MysqlDaemon) }
go
func (agent *ActionAgent) GetSlaves(ctx context.Context) ([]string, error) { return mysqlctl.FindSlaves(agent.MysqlDaemon) }
[ "func", "(", "agent", "*", "ActionAgent", ")", "GetSlaves", "(", "ctx", "context", ".", "Context", ")", "(", "[", "]", "string", ",", "error", ")", "{", "return", "mysqlctl", ".", "FindSlaves", "(", "agent", ".", "MysqlDaemon", ")", "\n", "}" ]
// GetSlaves returns the address of all the slaves
[ "GetSlaves", "returns", "the", "address", "of", "all", "the", "slaves" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/rpc_replication.go#L168-L170
train
vitessio/vitess
go/vt/vttablet/tabletmanager/rpc_replication.go
ResetReplication
func (agent *ActionAgent) ResetReplication(ctx context.Context) error { if err := agent.lock(ctx); err != nil { return err } defer agent.unlock() agent.setSlaveStopped(true) return agent.MysqlDaemon.ResetReplication(ctx) }
go
func (agent *ActionAgent) ResetReplication(ctx context.Context) error { if err := agent.lock(ctx); err != nil { return err } defer agent.unlock() agent.setSlaveStopped(true) return agent.MysqlDaemon.ResetReplication(ctx) }
[ "func", "(", "agent", "*", "ActionAgent", ")", "ResetReplication", "(", "ctx", "context", ".", "Context", ")", "error", "{", "if", "err", ":=", "agent", ".", "lock", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "agent", ".", "unlock", "(", ")", "\n\n", "agent", ".", "setSlaveStopped", "(", "true", ")", "\n", "return", "agent", ".", "MysqlDaemon", ".", "ResetReplication", "(", "ctx", ")", "\n", "}" ]
// ResetReplication completely resets the replication on the host. // All binary and relay logs are flushed. All replication positions are reset.
[ "ResetReplication", "completely", "resets", "the", "replication", "on", "the", "host", ".", "All", "binary", "and", "relay", "logs", "are", "flushed", ".", "All", "replication", "positions", "are", "reset", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/rpc_replication.go#L174-L182
train
vitessio/vitess
go/vt/vttablet/tabletmanager/rpc_replication.go
InitMaster
func (agent *ActionAgent) InitMaster(ctx context.Context) (string, error) { if err := agent.lock(ctx); err != nil { return "", err } defer agent.unlock() // Initializing as master implies undoing any previous "do not replicate". agent.setSlaveStopped(false) // we need to insert something in the binlogs, so we can get the // current position. Let's just use the mysqlctl.CreateReparentJournal commands. cmds := mysqlctl.CreateReparentJournal() if err := agent.MysqlDaemon.ExecuteSuperQueryList(ctx, cmds); err != nil { return "", err } // get the current replication position pos, err := agent.MysqlDaemon.MasterPosition() if err != nil { return "", err } // If using semi-sync, we need to enable it before going read-write. if err := agent.fixSemiSync(topodatapb.TabletType_MASTER); err != nil { return "", err } // Set the server read-write, from now on we can accept real // client writes. Note that if semi-sync replication is enabled, // we'll still need some slaves to be able to commit transactions. startTime := time.Now() if err := agent.MysqlDaemon.SetReadOnly(false); err != nil { return "", err } agent.setExternallyReparentedTime(startTime) // Change our type to master if not already if _, err := agent.TopoServer.UpdateTabletFields(ctx, agent.TabletAlias, func(tablet *topodatapb.Tablet) error { tablet.Type = topodatapb.TabletType_MASTER return nil }); err != nil { return "", err } // and refresh our state agent.initReplication = true if err := agent.refreshTablet(ctx, "InitMaster"); err != nil { return "", err } return mysql.EncodePosition(pos), nil }
go
func (agent *ActionAgent) InitMaster(ctx context.Context) (string, error) { if err := agent.lock(ctx); err != nil { return "", err } defer agent.unlock() // Initializing as master implies undoing any previous "do not replicate". agent.setSlaveStopped(false) // we need to insert something in the binlogs, so we can get the // current position. Let's just use the mysqlctl.CreateReparentJournal commands. cmds := mysqlctl.CreateReparentJournal() if err := agent.MysqlDaemon.ExecuteSuperQueryList(ctx, cmds); err != nil { return "", err } // get the current replication position pos, err := agent.MysqlDaemon.MasterPosition() if err != nil { return "", err } // If using semi-sync, we need to enable it before going read-write. if err := agent.fixSemiSync(topodatapb.TabletType_MASTER); err != nil { return "", err } // Set the server read-write, from now on we can accept real // client writes. Note that if semi-sync replication is enabled, // we'll still need some slaves to be able to commit transactions. startTime := time.Now() if err := agent.MysqlDaemon.SetReadOnly(false); err != nil { return "", err } agent.setExternallyReparentedTime(startTime) // Change our type to master if not already if _, err := agent.TopoServer.UpdateTabletFields(ctx, agent.TabletAlias, func(tablet *topodatapb.Tablet) error { tablet.Type = topodatapb.TabletType_MASTER return nil }); err != nil { return "", err } // and refresh our state agent.initReplication = true if err := agent.refreshTablet(ctx, "InitMaster"); err != nil { return "", err } return mysql.EncodePosition(pos), nil }
[ "func", "(", "agent", "*", "ActionAgent", ")", "InitMaster", "(", "ctx", "context", ".", "Context", ")", "(", "string", ",", "error", ")", "{", "if", "err", ":=", "agent", ".", "lock", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "defer", "agent", ".", "unlock", "(", ")", "\n\n", "// Initializing as master implies undoing any previous \"do not replicate\".", "agent", ".", "setSlaveStopped", "(", "false", ")", "\n\n", "// we need to insert something in the binlogs, so we can get the", "// current position. Let's just use the mysqlctl.CreateReparentJournal commands.", "cmds", ":=", "mysqlctl", ".", "CreateReparentJournal", "(", ")", "\n", "if", "err", ":=", "agent", ".", "MysqlDaemon", ".", "ExecuteSuperQueryList", "(", "ctx", ",", "cmds", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// get the current replication position", "pos", ",", "err", ":=", "agent", ".", "MysqlDaemon", ".", "MasterPosition", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// If using semi-sync, we need to enable it before going read-write.", "if", "err", ":=", "agent", ".", "fixSemiSync", "(", "topodatapb", ".", "TabletType_MASTER", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// Set the server read-write, from now on we can accept real", "// client writes. Note that if semi-sync replication is enabled,", "// we'll still need some slaves to be able to commit transactions.", "startTime", ":=", "time", ".", "Now", "(", ")", "\n", "if", "err", ":=", "agent", ".", "MysqlDaemon", ".", "SetReadOnly", "(", "false", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "agent", ".", "setExternallyReparentedTime", "(", "startTime", ")", "\n\n", "// Change our type to master if not already", "if", "_", ",", "err", ":=", "agent", ".", "TopoServer", ".", "UpdateTabletFields", "(", "ctx", ",", "agent", ".", "TabletAlias", ",", "func", "(", "tablet", "*", "topodatapb", ".", "Tablet", ")", "error", "{", "tablet", ".", "Type", "=", "topodatapb", ".", "TabletType_MASTER", "\n", "return", "nil", "\n", "}", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// and refresh our state", "agent", ".", "initReplication", "=", "true", "\n", "if", "err", ":=", "agent", ".", "refreshTablet", "(", "ctx", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "mysql", ".", "EncodePosition", "(", "pos", ")", ",", "nil", "\n", "}" ]
// InitMaster enables writes and returns the replication position.
[ "InitMaster", "enables", "writes", "and", "returns", "the", "replication", "position", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/rpc_replication.go#L185-L235
train
vitessio/vitess
go/vt/vttablet/tabletmanager/rpc_replication.go
PopulateReparentJournal
func (agent *ActionAgent) PopulateReparentJournal(ctx context.Context, timeCreatedNS int64, actionName string, masterAlias *topodatapb.TabletAlias, position string) error { pos, err := mysql.DecodePosition(position) if err != nil { return err } cmds := mysqlctl.CreateReparentJournal() cmds = append(cmds, mysqlctl.PopulateReparentJournal(timeCreatedNS, actionName, topoproto.TabletAliasString(masterAlias), pos)) return agent.MysqlDaemon.ExecuteSuperQueryList(ctx, cmds) }
go
func (agent *ActionAgent) PopulateReparentJournal(ctx context.Context, timeCreatedNS int64, actionName string, masterAlias *topodatapb.TabletAlias, position string) error { pos, err := mysql.DecodePosition(position) if err != nil { return err } cmds := mysqlctl.CreateReparentJournal() cmds = append(cmds, mysqlctl.PopulateReparentJournal(timeCreatedNS, actionName, topoproto.TabletAliasString(masterAlias), pos)) return agent.MysqlDaemon.ExecuteSuperQueryList(ctx, cmds) }
[ "func", "(", "agent", "*", "ActionAgent", ")", "PopulateReparentJournal", "(", "ctx", "context", ".", "Context", ",", "timeCreatedNS", "int64", ",", "actionName", "string", ",", "masterAlias", "*", "topodatapb", ".", "TabletAlias", ",", "position", "string", ")", "error", "{", "pos", ",", "err", ":=", "mysql", ".", "DecodePosition", "(", "position", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cmds", ":=", "mysqlctl", ".", "CreateReparentJournal", "(", ")", "\n", "cmds", "=", "append", "(", "cmds", ",", "mysqlctl", ".", "PopulateReparentJournal", "(", "timeCreatedNS", ",", "actionName", ",", "topoproto", ".", "TabletAliasString", "(", "masterAlias", ")", ",", "pos", ")", ")", "\n\n", "return", "agent", ".", "MysqlDaemon", ".", "ExecuteSuperQueryList", "(", "ctx", ",", "cmds", ")", "\n", "}" ]
// PopulateReparentJournal adds an entry into the reparent_journal table.
[ "PopulateReparentJournal", "adds", "an", "entry", "into", "the", "reparent_journal", "table", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/rpc_replication.go#L238-L247
train
vitessio/vitess
go/vt/vttablet/tabletmanager/rpc_replication.go
InitSlave
func (agent *ActionAgent) InitSlave(ctx context.Context, parent *topodatapb.TabletAlias, position string, timeCreatedNS int64) error { if err := agent.lock(ctx); err != nil { return err } defer agent.unlock() pos, err := mysql.DecodePosition(position) if err != nil { return err } ti, err := agent.TopoServer.GetTablet(ctx, parent) if err != nil { return err } agent.setSlaveStopped(false) // If using semi-sync, we need to enable it before connecting to master. // If we were a master type, we need to switch back to replica settings. // Otherwise we won't be able to commit anything. tt := agent.Tablet().Type if tt == topodatapb.TabletType_MASTER { tt = topodatapb.TabletType_REPLICA } if err := agent.fixSemiSync(tt); err != nil { return err } if err := agent.MysqlDaemon.SetSlavePosition(ctx, pos); err != nil { return err } if err := agent.MysqlDaemon.SetMaster(ctx, topoproto.MysqlHostname(ti.Tablet), int(topoproto.MysqlPort(ti.Tablet)), false /* slaveStopBefore */, true /* slaveStartAfter */); err != nil { return err } agent.initReplication = true // If we were a master type, switch our type to replica. This // is used on the old master when using InitShardMaster with // -force, and the new master is different from the old master. if agent.Tablet().Type == topodatapb.TabletType_MASTER { if _, err := topotools.ChangeType(ctx, agent.TopoServer, agent.TabletAlias, topodatapb.TabletType_REPLICA); err != nil { return err } if err := agent.refreshTablet(ctx, "InitSlave"); err != nil { return err } } // wait until we get the replicated row, or our context times out return agent.MysqlDaemon.WaitForReparentJournal(ctx, timeCreatedNS) }
go
func (agent *ActionAgent) InitSlave(ctx context.Context, parent *topodatapb.TabletAlias, position string, timeCreatedNS int64) error { if err := agent.lock(ctx); err != nil { return err } defer agent.unlock() pos, err := mysql.DecodePosition(position) if err != nil { return err } ti, err := agent.TopoServer.GetTablet(ctx, parent) if err != nil { return err } agent.setSlaveStopped(false) // If using semi-sync, we need to enable it before connecting to master. // If we were a master type, we need to switch back to replica settings. // Otherwise we won't be able to commit anything. tt := agent.Tablet().Type if tt == topodatapb.TabletType_MASTER { tt = topodatapb.TabletType_REPLICA } if err := agent.fixSemiSync(tt); err != nil { return err } if err := agent.MysqlDaemon.SetSlavePosition(ctx, pos); err != nil { return err } if err := agent.MysqlDaemon.SetMaster(ctx, topoproto.MysqlHostname(ti.Tablet), int(topoproto.MysqlPort(ti.Tablet)), false /* slaveStopBefore */, true /* slaveStartAfter */); err != nil { return err } agent.initReplication = true // If we were a master type, switch our type to replica. This // is used on the old master when using InitShardMaster with // -force, and the new master is different from the old master. if agent.Tablet().Type == topodatapb.TabletType_MASTER { if _, err := topotools.ChangeType(ctx, agent.TopoServer, agent.TabletAlias, topodatapb.TabletType_REPLICA); err != nil { return err } if err := agent.refreshTablet(ctx, "InitSlave"); err != nil { return err } } // wait until we get the replicated row, or our context times out return agent.MysqlDaemon.WaitForReparentJournal(ctx, timeCreatedNS) }
[ "func", "(", "agent", "*", "ActionAgent", ")", "InitSlave", "(", "ctx", "context", ".", "Context", ",", "parent", "*", "topodatapb", ".", "TabletAlias", ",", "position", "string", ",", "timeCreatedNS", "int64", ")", "error", "{", "if", "err", ":=", "agent", ".", "lock", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "agent", ".", "unlock", "(", ")", "\n\n", "pos", ",", "err", ":=", "mysql", ".", "DecodePosition", "(", "position", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "ti", ",", "err", ":=", "agent", ".", "TopoServer", ".", "GetTablet", "(", "ctx", ",", "parent", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "agent", ".", "setSlaveStopped", "(", "false", ")", "\n\n", "// If using semi-sync, we need to enable it before connecting to master.", "// If we were a master type, we need to switch back to replica settings.", "// Otherwise we won't be able to commit anything.", "tt", ":=", "agent", ".", "Tablet", "(", ")", ".", "Type", "\n", "if", "tt", "==", "topodatapb", ".", "TabletType_MASTER", "{", "tt", "=", "topodatapb", ".", "TabletType_REPLICA", "\n", "}", "\n", "if", "err", ":=", "agent", ".", "fixSemiSync", "(", "tt", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "agent", ".", "MysqlDaemon", ".", "SetSlavePosition", "(", "ctx", ",", "pos", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "agent", ".", "MysqlDaemon", ".", "SetMaster", "(", "ctx", ",", "topoproto", ".", "MysqlHostname", "(", "ti", ".", "Tablet", ")", ",", "int", "(", "topoproto", ".", "MysqlPort", "(", "ti", ".", "Tablet", ")", ")", ",", "false", "/* slaveStopBefore */", ",", "true", "/* slaveStartAfter */", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "agent", ".", "initReplication", "=", "true", "\n\n", "// If we were a master type, switch our type to replica. This", "// is used on the old master when using InitShardMaster with", "// -force, and the new master is different from the old master.", "if", "agent", ".", "Tablet", "(", ")", ".", "Type", "==", "topodatapb", ".", "TabletType_MASTER", "{", "if", "_", ",", "err", ":=", "topotools", ".", "ChangeType", "(", "ctx", ",", "agent", ".", "TopoServer", ",", "agent", ".", "TabletAlias", ",", "topodatapb", ".", "TabletType_REPLICA", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "agent", ".", "refreshTablet", "(", "ctx", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "// wait until we get the replicated row, or our context times out", "return", "agent", ".", "MysqlDaemon", ".", "WaitForReparentJournal", "(", "ctx", ",", "timeCreatedNS", ")", "\n", "}" ]
// InitSlave sets replication master and position, and waits for the // reparent_journal table entry up to context timeout
[ "InitSlave", "sets", "replication", "master", "and", "position", "and", "waits", "for", "the", "reparent_journal", "table", "entry", "up", "to", "context", "timeout" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/rpc_replication.go#L251-L302
train
vitessio/vitess
go/vt/vttablet/tabletmanager/rpc_replication.go
DemoteMaster
func (agent *ActionAgent) DemoteMaster(ctx context.Context) (string, error) { if err := agent.lock(ctx); err != nil { return "", err } defer agent.unlock() // Tell Orchestrator we're stopped on purpose the demotion. // This is a best effort task, so run it in a goroutine. go func() { if agent.orc == nil { return } if err := agent.orc.BeginMaintenance(agent.Tablet(), "vttablet has been told to DemoteMaster"); err != nil { log.Warningf("Orchestrator BeginMaintenance failed: %v", err) } }() // First, disallow queries, to make sure nobody is writing to the // database. tablet := agent.Tablet() // We don't care if the QueryService state actually changed because we'll // let vtgate keep serving read traffic from this master (see comment below). log.Infof("DemoteMaster disabling query service") if _ /* state changed */, err := agent.QueryServiceControl.SetServingType(tablet.Type, false, nil); err != nil { return "", vterrors.Wrap(err, "SetServingType(serving=false) failed") } // Now, set the server read-only. Note all active connections are not // affected. if *setSuperReadOnly { // Setting super_read_only also sets read_only if err := agent.MysqlDaemon.SetSuperReadOnly(true); err != nil { // if this failed, revert the change to serving if _ /* state changed */, err1 := agent.QueryServiceControl.SetServingType(tablet.Type, true, nil); err1 != nil { log.Warningf("SetServingType(serving=true) failed after failed SetSuperReadOnly %v", err1) } return "", err } } else { if err := agent.MysqlDaemon.SetReadOnly(true); err != nil { // if this failed, revert the change to serving if _ /* state changed */, err1 := agent.QueryServiceControl.SetServingType(tablet.Type, true, nil); err1 != nil { log.Warningf("SetServingType(serving=true) failed after failed SetReadOnly %v", err1) } return "", err } } // If using semi-sync, we need to disable master-side. if err := agent.fixSemiSync(topodatapb.TabletType_REPLICA); err != nil { // if this failed, set server read-only back to false, set tablet back to serving // setting read_only OFF will also set super_read_only OFF if it was set if err1 := agent.MysqlDaemon.SetReadOnly(false); err1 != nil { log.Warningf("SetReadOnly(false) failed after failed fixSemiSync %v", err1) } if _ /* state changed */, err1 := agent.QueryServiceControl.SetServingType(tablet.Type, true, nil); err1 != nil { log.Warningf("SetServingType(serving=true) failed after failed fixSemiSync %v", err1) } return "", err } pos, err := agent.MysqlDaemon.DemoteMaster() if err != nil { // if DemoteMaster failed, undo all the steps before // 1. set server back to read-only false // setting read_only OFF will also set super_read_only OFF if it was set if err1 := agent.MysqlDaemon.SetReadOnly(false); err1 != nil { log.Warningf("SetReadOnly(false) failed after failed DemoteMaster %v", err1) } // 2. set tablet back to serving if _ /* state changed */, err1 := agent.QueryServiceControl.SetServingType(tablet.Type, true, nil); err1 != nil { log.Warningf("SetServingType(serving=true) failed after failed DemoteMaster %v", err1) } // 3. enable master side again if err1 := agent.fixSemiSync(topodatapb.TabletType_MASTER); err1 != nil { log.Warningf("fixSemiSync(MASTER) failed after failed DemoteMaster %v", err1) } return "", err } return mysql.EncodePosition(pos), nil // There is no serving graph update - the master tablet will // be replaced. Even though writes may fail, reads will // succeed. It will be less noisy to simply leave the entry // until we'll promote the master. }
go
func (agent *ActionAgent) DemoteMaster(ctx context.Context) (string, error) { if err := agent.lock(ctx); err != nil { return "", err } defer agent.unlock() // Tell Orchestrator we're stopped on purpose the demotion. // This is a best effort task, so run it in a goroutine. go func() { if agent.orc == nil { return } if err := agent.orc.BeginMaintenance(agent.Tablet(), "vttablet has been told to DemoteMaster"); err != nil { log.Warningf("Orchestrator BeginMaintenance failed: %v", err) } }() // First, disallow queries, to make sure nobody is writing to the // database. tablet := agent.Tablet() // We don't care if the QueryService state actually changed because we'll // let vtgate keep serving read traffic from this master (see comment below). log.Infof("DemoteMaster disabling query service") if _ /* state changed */, err := agent.QueryServiceControl.SetServingType(tablet.Type, false, nil); err != nil { return "", vterrors.Wrap(err, "SetServingType(serving=false) failed") } // Now, set the server read-only. Note all active connections are not // affected. if *setSuperReadOnly { // Setting super_read_only also sets read_only if err := agent.MysqlDaemon.SetSuperReadOnly(true); err != nil { // if this failed, revert the change to serving if _ /* state changed */, err1 := agent.QueryServiceControl.SetServingType(tablet.Type, true, nil); err1 != nil { log.Warningf("SetServingType(serving=true) failed after failed SetSuperReadOnly %v", err1) } return "", err } } else { if err := agent.MysqlDaemon.SetReadOnly(true); err != nil { // if this failed, revert the change to serving if _ /* state changed */, err1 := agent.QueryServiceControl.SetServingType(tablet.Type, true, nil); err1 != nil { log.Warningf("SetServingType(serving=true) failed after failed SetReadOnly %v", err1) } return "", err } } // If using semi-sync, we need to disable master-side. if err := agent.fixSemiSync(topodatapb.TabletType_REPLICA); err != nil { // if this failed, set server read-only back to false, set tablet back to serving // setting read_only OFF will also set super_read_only OFF if it was set if err1 := agent.MysqlDaemon.SetReadOnly(false); err1 != nil { log.Warningf("SetReadOnly(false) failed after failed fixSemiSync %v", err1) } if _ /* state changed */, err1 := agent.QueryServiceControl.SetServingType(tablet.Type, true, nil); err1 != nil { log.Warningf("SetServingType(serving=true) failed after failed fixSemiSync %v", err1) } return "", err } pos, err := agent.MysqlDaemon.DemoteMaster() if err != nil { // if DemoteMaster failed, undo all the steps before // 1. set server back to read-only false // setting read_only OFF will also set super_read_only OFF if it was set if err1 := agent.MysqlDaemon.SetReadOnly(false); err1 != nil { log.Warningf("SetReadOnly(false) failed after failed DemoteMaster %v", err1) } // 2. set tablet back to serving if _ /* state changed */, err1 := agent.QueryServiceControl.SetServingType(tablet.Type, true, nil); err1 != nil { log.Warningf("SetServingType(serving=true) failed after failed DemoteMaster %v", err1) } // 3. enable master side again if err1 := agent.fixSemiSync(topodatapb.TabletType_MASTER); err1 != nil { log.Warningf("fixSemiSync(MASTER) failed after failed DemoteMaster %v", err1) } return "", err } return mysql.EncodePosition(pos), nil // There is no serving graph update - the master tablet will // be replaced. Even though writes may fail, reads will // succeed. It will be less noisy to simply leave the entry // until we'll promote the master. }
[ "func", "(", "agent", "*", "ActionAgent", ")", "DemoteMaster", "(", "ctx", "context", ".", "Context", ")", "(", "string", ",", "error", ")", "{", "if", "err", ":=", "agent", ".", "lock", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "defer", "agent", ".", "unlock", "(", ")", "\n\n", "// Tell Orchestrator we're stopped on purpose the demotion.", "// This is a best effort task, so run it in a goroutine.", "go", "func", "(", ")", "{", "if", "agent", ".", "orc", "==", "nil", "{", "return", "\n", "}", "\n", "if", "err", ":=", "agent", ".", "orc", ".", "BeginMaintenance", "(", "agent", ".", "Tablet", "(", ")", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "// First, disallow queries, to make sure nobody is writing to the", "// database.", "tablet", ":=", "agent", ".", "Tablet", "(", ")", "\n", "// We don't care if the QueryService state actually changed because we'll", "// let vtgate keep serving read traffic from this master (see comment below).", "log", ".", "Infof", "(", "\"", "\"", ")", "\n", "if", "_", "/* state changed */", ",", "err", ":=", "agent", ".", "QueryServiceControl", ".", "SetServingType", "(", "tablet", ".", "Type", ",", "false", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "vterrors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Now, set the server read-only. Note all active connections are not", "// affected.", "if", "*", "setSuperReadOnly", "{", "// Setting super_read_only also sets read_only", "if", "err", ":=", "agent", ".", "MysqlDaemon", ".", "SetSuperReadOnly", "(", "true", ")", ";", "err", "!=", "nil", "{", "// if this failed, revert the change to serving", "if", "_", "/* state changed */", ",", "err1", ":=", "agent", ".", "QueryServiceControl", ".", "SetServingType", "(", "tablet", ".", "Type", ",", "true", ",", "nil", ")", ";", "err1", "!=", "nil", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "err1", ")", "\n", "}", "\n", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "}", "else", "{", "if", "err", ":=", "agent", ".", "MysqlDaemon", ".", "SetReadOnly", "(", "true", ")", ";", "err", "!=", "nil", "{", "// if this failed, revert the change to serving", "if", "_", "/* state changed */", ",", "err1", ":=", "agent", ".", "QueryServiceControl", ".", "SetServingType", "(", "tablet", ".", "Type", ",", "true", ",", "nil", ")", ";", "err1", "!=", "nil", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "err1", ")", "\n", "}", "\n", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "}", "\n\n", "// If using semi-sync, we need to disable master-side.", "if", "err", ":=", "agent", ".", "fixSemiSync", "(", "topodatapb", ".", "TabletType_REPLICA", ")", ";", "err", "!=", "nil", "{", "// if this failed, set server read-only back to false, set tablet back to serving", "// setting read_only OFF will also set super_read_only OFF if it was set", "if", "err1", ":=", "agent", ".", "MysqlDaemon", ".", "SetReadOnly", "(", "false", ")", ";", "err1", "!=", "nil", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "err1", ")", "\n", "}", "\n", "if", "_", "/* state changed */", ",", "err1", ":=", "agent", ".", "QueryServiceControl", ".", "SetServingType", "(", "tablet", ".", "Type", ",", "true", ",", "nil", ")", ";", "err1", "!=", "nil", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "err1", ")", "\n", "}", "\n", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "pos", ",", "err", ":=", "agent", ".", "MysqlDaemon", ".", "DemoteMaster", "(", ")", "\n", "if", "err", "!=", "nil", "{", "// if DemoteMaster failed, undo all the steps before", "// 1. set server back to read-only false", "// setting read_only OFF will also set super_read_only OFF if it was set", "if", "err1", ":=", "agent", ".", "MysqlDaemon", ".", "SetReadOnly", "(", "false", ")", ";", "err1", "!=", "nil", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "err1", ")", "\n", "}", "\n", "// 2. set tablet back to serving", "if", "_", "/* state changed */", ",", "err1", ":=", "agent", ".", "QueryServiceControl", ".", "SetServingType", "(", "tablet", ".", "Type", ",", "true", ",", "nil", ")", ";", "err1", "!=", "nil", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "err1", ")", "\n", "}", "\n", "// 3. enable master side again", "if", "err1", ":=", "agent", ".", "fixSemiSync", "(", "topodatapb", ".", "TabletType_MASTER", ")", ";", "err1", "!=", "nil", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "err1", ")", "\n", "}", "\n", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "mysql", ".", "EncodePosition", "(", "pos", ")", ",", "nil", "\n", "// There is no serving graph update - the master tablet will", "// be replaced. Even though writes may fail, reads will", "// succeed. It will be less noisy to simply leave the entry", "// until we'll promote the master.", "}" ]
// DemoteMaster marks the server read-only, wait until it is done with // its current transactions, and returns its master position.
[ "DemoteMaster", "marks", "the", "server", "read", "-", "only", "wait", "until", "it", "is", "done", "with", "its", "current", "transactions", "and", "returns", "its", "master", "position", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/rpc_replication.go#L306-L390
train
vitessio/vitess
go/vt/vttablet/tabletmanager/rpc_replication.go
UndoDemoteMaster
func (agent *ActionAgent) UndoDemoteMaster(ctx context.Context) error { if err := agent.lock(ctx); err != nil { return err } defer agent.unlock() // If using semi-sync, we need to enable master-side. if err := agent.fixSemiSync(topodatapb.TabletType_MASTER); err != nil { return err } // Now, set the server read-only false. if err := agent.MysqlDaemon.SetReadOnly(false); err != nil { return err } // Update serving graph tablet := agent.Tablet() log.Infof("UndoDemoteMaster re-enabling query service") if _ /* state changed */, err := agent.QueryServiceControl.SetServingType(tablet.Type, true, nil); err != nil { return vterrors.Wrap(err, "SetServingType(serving=true) failed") } return nil }
go
func (agent *ActionAgent) UndoDemoteMaster(ctx context.Context) error { if err := agent.lock(ctx); err != nil { return err } defer agent.unlock() // If using semi-sync, we need to enable master-side. if err := agent.fixSemiSync(topodatapb.TabletType_MASTER); err != nil { return err } // Now, set the server read-only false. if err := agent.MysqlDaemon.SetReadOnly(false); err != nil { return err } // Update serving graph tablet := agent.Tablet() log.Infof("UndoDemoteMaster re-enabling query service") if _ /* state changed */, err := agent.QueryServiceControl.SetServingType(tablet.Type, true, nil); err != nil { return vterrors.Wrap(err, "SetServingType(serving=true) failed") } return nil }
[ "func", "(", "agent", "*", "ActionAgent", ")", "UndoDemoteMaster", "(", "ctx", "context", ".", "Context", ")", "error", "{", "if", "err", ":=", "agent", ".", "lock", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "agent", ".", "unlock", "(", ")", "\n\n", "// If using semi-sync, we need to enable master-side.", "if", "err", ":=", "agent", ".", "fixSemiSync", "(", "topodatapb", ".", "TabletType_MASTER", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Now, set the server read-only false.", "if", "err", ":=", "agent", ".", "MysqlDaemon", ".", "SetReadOnly", "(", "false", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Update serving graph", "tablet", ":=", "agent", ".", "Tablet", "(", ")", "\n", "log", ".", "Infof", "(", "\"", "\"", ")", "\n", "if", "_", "/* state changed */", ",", "err", ":=", "agent", ".", "QueryServiceControl", ".", "SetServingType", "(", "tablet", ".", "Type", ",", "true", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "vterrors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// UndoDemoteMaster reverts a previous call to DemoteMaster // it sets read-only to false, fixes semi-sync // and returns its master position.
[ "UndoDemoteMaster", "reverts", "a", "previous", "call", "to", "DemoteMaster", "it", "sets", "read", "-", "only", "to", "false", "fixes", "semi", "-", "sync", "and", "returns", "its", "master", "position", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/rpc_replication.go#L395-L419
train
vitessio/vitess
go/vt/vttablet/tabletmanager/rpc_replication.go
SlaveWasPromoted
func (agent *ActionAgent) SlaveWasPromoted(ctx context.Context) error { if err := agent.lock(ctx); err != nil { return err } defer agent.unlock() if _, err := topotools.ChangeType(ctx, agent.TopoServer, agent.TabletAlias, topodatapb.TabletType_MASTER); err != nil { return err } if err := agent.refreshTablet(ctx, "SlaveWasPromoted"); err != nil { return err } return nil }
go
func (agent *ActionAgent) SlaveWasPromoted(ctx context.Context) error { if err := agent.lock(ctx); err != nil { return err } defer agent.unlock() if _, err := topotools.ChangeType(ctx, agent.TopoServer, agent.TabletAlias, topodatapb.TabletType_MASTER); err != nil { return err } if err := agent.refreshTablet(ctx, "SlaveWasPromoted"); err != nil { return err } return nil }
[ "func", "(", "agent", "*", "ActionAgent", ")", "SlaveWasPromoted", "(", "ctx", "context", ".", "Context", ")", "error", "{", "if", "err", ":=", "agent", ".", "lock", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "agent", ".", "unlock", "(", ")", "\n\n", "if", "_", ",", "err", ":=", "topotools", ".", "ChangeType", "(", "ctx", ",", "agent", ".", "TopoServer", ",", "agent", ".", "TabletAlias", ",", "topodatapb", ".", "TabletType_MASTER", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "agent", ".", "refreshTablet", "(", "ctx", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// SlaveWasPromoted promotes a slave to master, no questions asked.
[ "SlaveWasPromoted", "promotes", "a", "slave", "to", "master", "no", "questions", "asked", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/rpc_replication.go#L467-L482
train
vitessio/vitess
go/vt/vttablet/tabletmanager/rpc_replication.go
SetMaster
func (agent *ActionAgent) SetMaster(ctx context.Context, parentAlias *topodatapb.TabletAlias, timeCreatedNS int64, forceStartSlave bool) error { if err := agent.lock(ctx); err != nil { return err } defer agent.unlock() return agent.setMasterLocked(ctx, parentAlias, timeCreatedNS, forceStartSlave) }
go
func (agent *ActionAgent) SetMaster(ctx context.Context, parentAlias *topodatapb.TabletAlias, timeCreatedNS int64, forceStartSlave bool) error { if err := agent.lock(ctx); err != nil { return err } defer agent.unlock() return agent.setMasterLocked(ctx, parentAlias, timeCreatedNS, forceStartSlave) }
[ "func", "(", "agent", "*", "ActionAgent", ")", "SetMaster", "(", "ctx", "context", ".", "Context", ",", "parentAlias", "*", "topodatapb", ".", "TabletAlias", ",", "timeCreatedNS", "int64", ",", "forceStartSlave", "bool", ")", "error", "{", "if", "err", ":=", "agent", ".", "lock", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "agent", ".", "unlock", "(", ")", "\n\n", "return", "agent", ".", "setMasterLocked", "(", "ctx", ",", "parentAlias", ",", "timeCreatedNS", ",", "forceStartSlave", ")", "\n", "}" ]
// SetMaster sets replication master, and waits for the // reparent_journal table entry up to context timeout
[ "SetMaster", "sets", "replication", "master", "and", "waits", "for", "the", "reparent_journal", "table", "entry", "up", "to", "context", "timeout" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/rpc_replication.go#L486-L493
train
vitessio/vitess
go/vt/vttablet/tabletmanager/rpc_replication.go
SlaveWasRestarted
func (agent *ActionAgent) SlaveWasRestarted(ctx context.Context, parent *topodatapb.TabletAlias) error { if err := agent.lock(ctx); err != nil { return err } defer agent.unlock() typeChanged := false // Once this action completes, update authoritative tablet node first. if _, err := agent.TopoServer.UpdateTabletFields(ctx, agent.TabletAlias, func(tablet *topodatapb.Tablet) error { if tablet.Type == topodatapb.TabletType_MASTER { tablet.Type = topodatapb.TabletType_REPLICA typeChanged = true return nil } return topo.NewError(topo.NoUpdateNeeded, agent.TabletAlias.String()) }); err != nil { return err } if typeChanged { if err := agent.refreshTablet(ctx, "SlaveWasRestarted"); err != nil { return err } agent.runHealthCheckLocked() } return nil }
go
func (agent *ActionAgent) SlaveWasRestarted(ctx context.Context, parent *topodatapb.TabletAlias) error { if err := agent.lock(ctx); err != nil { return err } defer agent.unlock() typeChanged := false // Once this action completes, update authoritative tablet node first. if _, err := agent.TopoServer.UpdateTabletFields(ctx, agent.TabletAlias, func(tablet *topodatapb.Tablet) error { if tablet.Type == topodatapb.TabletType_MASTER { tablet.Type = topodatapb.TabletType_REPLICA typeChanged = true return nil } return topo.NewError(topo.NoUpdateNeeded, agent.TabletAlias.String()) }); err != nil { return err } if typeChanged { if err := agent.refreshTablet(ctx, "SlaveWasRestarted"); err != nil { return err } agent.runHealthCheckLocked() } return nil }
[ "func", "(", "agent", "*", "ActionAgent", ")", "SlaveWasRestarted", "(", "ctx", "context", ".", "Context", ",", "parent", "*", "topodatapb", ".", "TabletAlias", ")", "error", "{", "if", "err", ":=", "agent", ".", "lock", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "agent", ".", "unlock", "(", ")", "\n\n", "typeChanged", ":=", "false", "\n\n", "// Once this action completes, update authoritative tablet node first.", "if", "_", ",", "err", ":=", "agent", ".", "TopoServer", ".", "UpdateTabletFields", "(", "ctx", ",", "agent", ".", "TabletAlias", ",", "func", "(", "tablet", "*", "topodatapb", ".", "Tablet", ")", "error", "{", "if", "tablet", ".", "Type", "==", "topodatapb", ".", "TabletType_MASTER", "{", "tablet", ".", "Type", "=", "topodatapb", ".", "TabletType_REPLICA", "\n", "typeChanged", "=", "true", "\n", "return", "nil", "\n", "}", "\n", "return", "topo", ".", "NewError", "(", "topo", ".", "NoUpdateNeeded", ",", "agent", ".", "TabletAlias", ".", "String", "(", ")", ")", "\n", "}", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "typeChanged", "{", "if", "err", ":=", "agent", ".", "refreshTablet", "(", "ctx", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "agent", ".", "runHealthCheckLocked", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SlaveWasRestarted updates the parent record for a tablet.
[ "SlaveWasRestarted", "updates", "the", "parent", "record", "for", "a", "tablet", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/rpc_replication.go#L590-L617
train
vitessio/vitess
go/vt/vttablet/tabletmanager/rpc_replication.go
StopReplicationAndGetStatus
func (agent *ActionAgent) StopReplicationAndGetStatus(ctx context.Context) (*replicationdatapb.Status, error) { if err := agent.lock(ctx); err != nil { return nil, err } defer agent.unlock() // get the status before we stop replication rs, err := agent.MysqlDaemon.SlaveStatus() if err != nil { return nil, vterrors.Wrap(err, "before status failed") } if !rs.SlaveIORunning && !rs.SlaveSQLRunning { // no replication is running, just return what we got return mysql.SlaveStatusToProto(rs), nil } if err := agent.stopSlaveLocked(ctx); err != nil { return nil, vterrors.Wrap(err, "stop slave failed") } // now patch in the current position rs.Position, err = agent.MysqlDaemon.MasterPosition() if err != nil { return nil, vterrors.Wrap(err, "after position failed") } return mysql.SlaveStatusToProto(rs), nil }
go
func (agent *ActionAgent) StopReplicationAndGetStatus(ctx context.Context) (*replicationdatapb.Status, error) { if err := agent.lock(ctx); err != nil { return nil, err } defer agent.unlock() // get the status before we stop replication rs, err := agent.MysqlDaemon.SlaveStatus() if err != nil { return nil, vterrors.Wrap(err, "before status failed") } if !rs.SlaveIORunning && !rs.SlaveSQLRunning { // no replication is running, just return what we got return mysql.SlaveStatusToProto(rs), nil } if err := agent.stopSlaveLocked(ctx); err != nil { return nil, vterrors.Wrap(err, "stop slave failed") } // now patch in the current position rs.Position, err = agent.MysqlDaemon.MasterPosition() if err != nil { return nil, vterrors.Wrap(err, "after position failed") } return mysql.SlaveStatusToProto(rs), nil }
[ "func", "(", "agent", "*", "ActionAgent", ")", "StopReplicationAndGetStatus", "(", "ctx", "context", ".", "Context", ")", "(", "*", "replicationdatapb", ".", "Status", ",", "error", ")", "{", "if", "err", ":=", "agent", ".", "lock", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "agent", ".", "unlock", "(", ")", "\n\n", "// get the status before we stop replication", "rs", ",", "err", ":=", "agent", ".", "MysqlDaemon", ".", "SlaveStatus", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "vterrors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "!", "rs", ".", "SlaveIORunning", "&&", "!", "rs", ".", "SlaveSQLRunning", "{", "// no replication is running, just return what we got", "return", "mysql", ".", "SlaveStatusToProto", "(", "rs", ")", ",", "nil", "\n", "}", "\n", "if", "err", ":=", "agent", ".", "stopSlaveLocked", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "vterrors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "// now patch in the current position", "rs", ".", "Position", ",", "err", "=", "agent", ".", "MysqlDaemon", ".", "MasterPosition", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "vterrors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "mysql", ".", "SlaveStatusToProto", "(", "rs", ")", ",", "nil", "\n", "}" ]
// StopReplicationAndGetStatus stops MySQL replication, and returns the // current status.
[ "StopReplicationAndGetStatus", "stops", "MySQL", "replication", "and", "returns", "the", "current", "status", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/rpc_replication.go#L621-L645
train
vitessio/vitess
go/vt/vttablet/tabletmanager/rpc_replication.go
PromoteSlave
func (agent *ActionAgent) PromoteSlave(ctx context.Context) (string, error) { if err := agent.lock(ctx); err != nil { return "", err } defer agent.unlock() pos, err := agent.MysqlDaemon.PromoteSlave(agent.hookExtraEnv()) if err != nil { return "", err } // If using semi-sync, we need to enable it before going read-write. if err := agent.fixSemiSync(topodatapb.TabletType_MASTER); err != nil { return "", err } // Set the server read-write startTime := time.Now() if err := agent.MysqlDaemon.SetReadOnly(false); err != nil { return "", err } agent.setExternallyReparentedTime(startTime) if _, err := topotools.ChangeType(ctx, agent.TopoServer, agent.TabletAlias, topodatapb.TabletType_MASTER); err != nil { return "", err } if err := agent.refreshTablet(ctx, "PromoteSlave"); err != nil { return "", err } return mysql.EncodePosition(pos), nil }
go
func (agent *ActionAgent) PromoteSlave(ctx context.Context) (string, error) { if err := agent.lock(ctx); err != nil { return "", err } defer agent.unlock() pos, err := agent.MysqlDaemon.PromoteSlave(agent.hookExtraEnv()) if err != nil { return "", err } // If using semi-sync, we need to enable it before going read-write. if err := agent.fixSemiSync(topodatapb.TabletType_MASTER); err != nil { return "", err } // Set the server read-write startTime := time.Now() if err := agent.MysqlDaemon.SetReadOnly(false); err != nil { return "", err } agent.setExternallyReparentedTime(startTime) if _, err := topotools.ChangeType(ctx, agent.TopoServer, agent.TabletAlias, topodatapb.TabletType_MASTER); err != nil { return "", err } if err := agent.refreshTablet(ctx, "PromoteSlave"); err != nil { return "", err } return mysql.EncodePosition(pos), nil }
[ "func", "(", "agent", "*", "ActionAgent", ")", "PromoteSlave", "(", "ctx", "context", ".", "Context", ")", "(", "string", ",", "error", ")", "{", "if", "err", ":=", "agent", ".", "lock", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "defer", "agent", ".", "unlock", "(", ")", "\n\n", "pos", ",", "err", ":=", "agent", ".", "MysqlDaemon", ".", "PromoteSlave", "(", "agent", ".", "hookExtraEnv", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// If using semi-sync, we need to enable it before going read-write.", "if", "err", ":=", "agent", ".", "fixSemiSync", "(", "topodatapb", ".", "TabletType_MASTER", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// Set the server read-write", "startTime", ":=", "time", ".", "Now", "(", ")", "\n", "if", "err", ":=", "agent", ".", "MysqlDaemon", ".", "SetReadOnly", "(", "false", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "agent", ".", "setExternallyReparentedTime", "(", "startTime", ")", "\n\n", "if", "_", ",", "err", ":=", "topotools", ".", "ChangeType", "(", "ctx", ",", "agent", ".", "TopoServer", ",", "agent", ".", "TabletAlias", ",", "topodatapb", ".", "TabletType_MASTER", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "agent", ".", "refreshTablet", "(", "ctx", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "mysql", ".", "EncodePosition", "(", "pos", ")", ",", "nil", "\n", "}" ]
// PromoteSlave makes the current tablet the master
[ "PromoteSlave", "makes", "the", "current", "tablet", "the", "master" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/rpc_replication.go#L648-L680
train
vitessio/vitess
go/vt/wrangler/reparent.go
ShardReplicationStatuses
func (wr *Wrangler) ShardReplicationStatuses(ctx context.Context, keyspace, shard string) ([]*topo.TabletInfo, []*replicationdatapb.Status, error) { tabletMap, err := wr.ts.GetTabletMapForShard(ctx, keyspace, shard) if err != nil { return nil, nil, err } tablets := topotools.CopyMapValues(tabletMap, []*topo.TabletInfo{}).([]*topo.TabletInfo) wr.logger.Infof("Gathering tablet replication status for: %v", tablets) wg := sync.WaitGroup{} rec := concurrency.AllErrorRecorder{} result := make([]*replicationdatapb.Status, len(tablets)) for i, ti := range tablets { // Don't scan tablets that won't return something // useful. Otherwise, you'll end up waiting for a timeout. if ti.Type == topodatapb.TabletType_MASTER { wg.Add(1) go func(i int, ti *topo.TabletInfo) { defer wg.Done() pos, err := wr.tmc.MasterPosition(ctx, ti.Tablet) if err != nil { rec.RecordError(fmt.Errorf("MasterPosition(%v) failed: %v", ti.AliasString(), err)) return } result[i] = &replicationdatapb.Status{ Position: pos, } }(i, ti) } else if ti.IsSlaveType() { wg.Add(1) go func(i int, ti *topo.TabletInfo) { defer wg.Done() status, err := wr.tmc.SlaveStatus(ctx, ti.Tablet) if err != nil { rec.RecordError(fmt.Errorf("SlaveStatus(%v) failed: %v", ti.AliasString(), err)) return } result[i] = status }(i, ti) } } wg.Wait() return tablets, result, rec.Error() }
go
func (wr *Wrangler) ShardReplicationStatuses(ctx context.Context, keyspace, shard string) ([]*topo.TabletInfo, []*replicationdatapb.Status, error) { tabletMap, err := wr.ts.GetTabletMapForShard(ctx, keyspace, shard) if err != nil { return nil, nil, err } tablets := topotools.CopyMapValues(tabletMap, []*topo.TabletInfo{}).([]*topo.TabletInfo) wr.logger.Infof("Gathering tablet replication status for: %v", tablets) wg := sync.WaitGroup{} rec := concurrency.AllErrorRecorder{} result := make([]*replicationdatapb.Status, len(tablets)) for i, ti := range tablets { // Don't scan tablets that won't return something // useful. Otherwise, you'll end up waiting for a timeout. if ti.Type == topodatapb.TabletType_MASTER { wg.Add(1) go func(i int, ti *topo.TabletInfo) { defer wg.Done() pos, err := wr.tmc.MasterPosition(ctx, ti.Tablet) if err != nil { rec.RecordError(fmt.Errorf("MasterPosition(%v) failed: %v", ti.AliasString(), err)) return } result[i] = &replicationdatapb.Status{ Position: pos, } }(i, ti) } else if ti.IsSlaveType() { wg.Add(1) go func(i int, ti *topo.TabletInfo) { defer wg.Done() status, err := wr.tmc.SlaveStatus(ctx, ti.Tablet) if err != nil { rec.RecordError(fmt.Errorf("SlaveStatus(%v) failed: %v", ti.AliasString(), err)) return } result[i] = status }(i, ti) } } wg.Wait() return tablets, result, rec.Error() }
[ "func", "(", "wr", "*", "Wrangler", ")", "ShardReplicationStatuses", "(", "ctx", "context", ".", "Context", ",", "keyspace", ",", "shard", "string", ")", "(", "[", "]", "*", "topo", ".", "TabletInfo", ",", "[", "]", "*", "replicationdatapb", ".", "Status", ",", "error", ")", "{", "tabletMap", ",", "err", ":=", "wr", ".", "ts", ".", "GetTabletMapForShard", "(", "ctx", ",", "keyspace", ",", "shard", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "tablets", ":=", "topotools", ".", "CopyMapValues", "(", "tabletMap", ",", "[", "]", "*", "topo", ".", "TabletInfo", "{", "}", ")", ".", "(", "[", "]", "*", "topo", ".", "TabletInfo", ")", "\n\n", "wr", ".", "logger", ".", "Infof", "(", "\"", "\"", ",", "tablets", ")", "\n", "wg", ":=", "sync", ".", "WaitGroup", "{", "}", "\n", "rec", ":=", "concurrency", ".", "AllErrorRecorder", "{", "}", "\n", "result", ":=", "make", "(", "[", "]", "*", "replicationdatapb", ".", "Status", ",", "len", "(", "tablets", ")", ")", "\n\n", "for", "i", ",", "ti", ":=", "range", "tablets", "{", "// Don't scan tablets that won't return something", "// useful. Otherwise, you'll end up waiting for a timeout.", "if", "ti", ".", "Type", "==", "topodatapb", ".", "TabletType_MASTER", "{", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "i", "int", ",", "ti", "*", "topo", ".", "TabletInfo", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "pos", ",", "err", ":=", "wr", ".", "tmc", ".", "MasterPosition", "(", "ctx", ",", "ti", ".", "Tablet", ")", "\n", "if", "err", "!=", "nil", "{", "rec", ".", "RecordError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ti", ".", "AliasString", "(", ")", ",", "err", ")", ")", "\n", "return", "\n", "}", "\n", "result", "[", "i", "]", "=", "&", "replicationdatapb", ".", "Status", "{", "Position", ":", "pos", ",", "}", "\n", "}", "(", "i", ",", "ti", ")", "\n", "}", "else", "if", "ti", ".", "IsSlaveType", "(", ")", "{", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "i", "int", ",", "ti", "*", "topo", ".", "TabletInfo", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "status", ",", "err", ":=", "wr", ".", "tmc", ".", "SlaveStatus", "(", "ctx", ",", "ti", ".", "Tablet", ")", "\n", "if", "err", "!=", "nil", "{", "rec", ".", "RecordError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ti", ".", "AliasString", "(", ")", ",", "err", ")", ")", "\n", "return", "\n", "}", "\n", "result", "[", "i", "]", "=", "status", "\n", "}", "(", "i", ",", "ti", ")", "\n", "}", "\n", "}", "\n", "wg", ".", "Wait", "(", ")", "\n", "return", "tablets", ",", "result", ",", "rec", ".", "Error", "(", ")", "\n", "}" ]
// ShardReplicationStatuses returns the ReplicationStatus for each tablet in a shard.
[ "ShardReplicationStatuses", "returns", "the", "ReplicationStatus", "for", "each", "tablet", "in", "a", "shard", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/reparent.go#L50-L93
train
vitessio/vitess
go/vt/wrangler/reparent.go
ReparentTablet
func (wr *Wrangler) ReparentTablet(ctx context.Context, tabletAlias *topodatapb.TabletAlias) error { // Get specified tablet. // Get current shard master tablet. // Sanity check they are in the same keyspace/shard. // Issue a SetMaster to the tablet. ti, err := wr.ts.GetTablet(ctx, tabletAlias) if err != nil { return err } shardInfo, err := wr.ts.GetShard(ctx, ti.Keyspace, ti.Shard) if err != nil { return err } if !shardInfo.HasMaster() { return fmt.Errorf("no master tablet for shard %v/%v", ti.Keyspace, ti.Shard) } masterTi, err := wr.ts.GetTablet(ctx, shardInfo.MasterAlias) if err != nil { return err } // Basic sanity checking. if masterTi.Type != topodatapb.TabletType_MASTER { return fmt.Errorf("TopologyServer has inconsistent state for shard master %v", topoproto.TabletAliasString(shardInfo.MasterAlias)) } if masterTi.Keyspace != ti.Keyspace || masterTi.Shard != ti.Shard { return fmt.Errorf("master %v and potential slave not in same keyspace/shard", topoproto.TabletAliasString(shardInfo.MasterAlias)) } // and do the remote command return wr.tmc.SetMaster(ctx, ti.Tablet, shardInfo.MasterAlias, 0, false) }
go
func (wr *Wrangler) ReparentTablet(ctx context.Context, tabletAlias *topodatapb.TabletAlias) error { // Get specified tablet. // Get current shard master tablet. // Sanity check they are in the same keyspace/shard. // Issue a SetMaster to the tablet. ti, err := wr.ts.GetTablet(ctx, tabletAlias) if err != nil { return err } shardInfo, err := wr.ts.GetShard(ctx, ti.Keyspace, ti.Shard) if err != nil { return err } if !shardInfo.HasMaster() { return fmt.Errorf("no master tablet for shard %v/%v", ti.Keyspace, ti.Shard) } masterTi, err := wr.ts.GetTablet(ctx, shardInfo.MasterAlias) if err != nil { return err } // Basic sanity checking. if masterTi.Type != topodatapb.TabletType_MASTER { return fmt.Errorf("TopologyServer has inconsistent state for shard master %v", topoproto.TabletAliasString(shardInfo.MasterAlias)) } if masterTi.Keyspace != ti.Keyspace || masterTi.Shard != ti.Shard { return fmt.Errorf("master %v and potential slave not in same keyspace/shard", topoproto.TabletAliasString(shardInfo.MasterAlias)) } // and do the remote command return wr.tmc.SetMaster(ctx, ti.Tablet, shardInfo.MasterAlias, 0, false) }
[ "func", "(", "wr", "*", "Wrangler", ")", "ReparentTablet", "(", "ctx", "context", ".", "Context", ",", "tabletAlias", "*", "topodatapb", ".", "TabletAlias", ")", "error", "{", "// Get specified tablet.", "// Get current shard master tablet.", "// Sanity check they are in the same keyspace/shard.", "// Issue a SetMaster to the tablet.", "ti", ",", "err", ":=", "wr", ".", "ts", ".", "GetTablet", "(", "ctx", ",", "tabletAlias", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "shardInfo", ",", "err", ":=", "wr", ".", "ts", ".", "GetShard", "(", "ctx", ",", "ti", ".", "Keyspace", ",", "ti", ".", "Shard", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "shardInfo", ".", "HasMaster", "(", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ti", ".", "Keyspace", ",", "ti", ".", "Shard", ")", "\n", "}", "\n\n", "masterTi", ",", "err", ":=", "wr", ".", "ts", ".", "GetTablet", "(", "ctx", ",", "shardInfo", ".", "MasterAlias", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Basic sanity checking.", "if", "masterTi", ".", "Type", "!=", "topodatapb", ".", "TabletType_MASTER", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "topoproto", ".", "TabletAliasString", "(", "shardInfo", ".", "MasterAlias", ")", ")", "\n", "}", "\n", "if", "masterTi", ".", "Keyspace", "!=", "ti", ".", "Keyspace", "||", "masterTi", ".", "Shard", "!=", "ti", ".", "Shard", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "topoproto", ".", "TabletAliasString", "(", "shardInfo", ".", "MasterAlias", ")", ")", "\n", "}", "\n\n", "// and do the remote command", "return", "wr", ".", "tmc", ".", "SetMaster", "(", "ctx", ",", "ti", ".", "Tablet", ",", "shardInfo", ".", "MasterAlias", ",", "0", ",", "false", ")", "\n", "}" ]
// ReparentTablet tells a tablet to reparent this tablet to the current // master, based on the current replication position. If there is no // match, it will fail.
[ "ReparentTablet", "tells", "a", "tablet", "to", "reparent", "this", "tablet", "to", "the", "current", "master", "based", "on", "the", "current", "replication", "position", ".", "If", "there", "is", "no", "match", "it", "will", "fail", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/reparent.go#L98-L131
train
vitessio/vitess
go/vt/wrangler/reparent.go
PlannedReparentShard
func (wr *Wrangler) PlannedReparentShard(ctx context.Context, keyspace, shard string, masterElectTabletAlias, avoidMasterAlias *topodatapb.TabletAlias, waitSlaveTimeout time.Duration) (err error) { // lock the shard lockAction := fmt.Sprintf( "PlannedReparentShard(%v, avoid_master=%v)", topoproto.TabletAliasString(masterElectTabletAlias), topoproto.TabletAliasString(avoidMasterAlias)) ctx, unlock, lockErr := wr.ts.LockShard(ctx, keyspace, shard, lockAction) if lockErr != nil { return lockErr } defer unlock(&err) // Create reusable Reparent event with available info ev := &events.Reparent{} // Attempt to set avoidMasterAlias if not provided by parameters if masterElectTabletAlias == nil && avoidMasterAlias == nil { shardInfo, err := wr.ts.GetShard(ctx, keyspace, shard) if err != nil { return err } avoidMasterAlias = shardInfo.MasterAlias } // do the work err = wr.plannedReparentShardLocked(ctx, ev, keyspace, shard, masterElectTabletAlias, avoidMasterAlias, waitSlaveTimeout) if err != nil { event.DispatchUpdate(ev, "failed PlannedReparentShard: "+err.Error()) } else { event.DispatchUpdate(ev, "finished PlannedReparentShard") } return err }
go
func (wr *Wrangler) PlannedReparentShard(ctx context.Context, keyspace, shard string, masterElectTabletAlias, avoidMasterAlias *topodatapb.TabletAlias, waitSlaveTimeout time.Duration) (err error) { // lock the shard lockAction := fmt.Sprintf( "PlannedReparentShard(%v, avoid_master=%v)", topoproto.TabletAliasString(masterElectTabletAlias), topoproto.TabletAliasString(avoidMasterAlias)) ctx, unlock, lockErr := wr.ts.LockShard(ctx, keyspace, shard, lockAction) if lockErr != nil { return lockErr } defer unlock(&err) // Create reusable Reparent event with available info ev := &events.Reparent{} // Attempt to set avoidMasterAlias if not provided by parameters if masterElectTabletAlias == nil && avoidMasterAlias == nil { shardInfo, err := wr.ts.GetShard(ctx, keyspace, shard) if err != nil { return err } avoidMasterAlias = shardInfo.MasterAlias } // do the work err = wr.plannedReparentShardLocked(ctx, ev, keyspace, shard, masterElectTabletAlias, avoidMasterAlias, waitSlaveTimeout) if err != nil { event.DispatchUpdate(ev, "failed PlannedReparentShard: "+err.Error()) } else { event.DispatchUpdate(ev, "finished PlannedReparentShard") } return err }
[ "func", "(", "wr", "*", "Wrangler", ")", "PlannedReparentShard", "(", "ctx", "context", ".", "Context", ",", "keyspace", ",", "shard", "string", ",", "masterElectTabletAlias", ",", "avoidMasterAlias", "*", "topodatapb", ".", "TabletAlias", ",", "waitSlaveTimeout", "time", ".", "Duration", ")", "(", "err", "error", ")", "{", "// lock the shard", "lockAction", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "topoproto", ".", "TabletAliasString", "(", "masterElectTabletAlias", ")", ",", "topoproto", ".", "TabletAliasString", "(", "avoidMasterAlias", ")", ")", "\n", "ctx", ",", "unlock", ",", "lockErr", ":=", "wr", ".", "ts", ".", "LockShard", "(", "ctx", ",", "keyspace", ",", "shard", ",", "lockAction", ")", "\n", "if", "lockErr", "!=", "nil", "{", "return", "lockErr", "\n", "}", "\n", "defer", "unlock", "(", "&", "err", ")", "\n\n", "// Create reusable Reparent event with available info", "ev", ":=", "&", "events", ".", "Reparent", "{", "}", "\n\n", "// Attempt to set avoidMasterAlias if not provided by parameters", "if", "masterElectTabletAlias", "==", "nil", "&&", "avoidMasterAlias", "==", "nil", "{", "shardInfo", ",", "err", ":=", "wr", ".", "ts", ".", "GetShard", "(", "ctx", ",", "keyspace", ",", "shard", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "avoidMasterAlias", "=", "shardInfo", ".", "MasterAlias", "\n", "}", "\n\n", "// do the work", "err", "=", "wr", ".", "plannedReparentShardLocked", "(", "ctx", ",", "ev", ",", "keyspace", ",", "shard", ",", "masterElectTabletAlias", ",", "avoidMasterAlias", ",", "waitSlaveTimeout", ")", "\n", "if", "err", "!=", "nil", "{", "event", ".", "DispatchUpdate", "(", "ev", ",", "\"", "\"", "+", "err", ".", "Error", "(", ")", ")", "\n", "}", "else", "{", "event", ".", "DispatchUpdate", "(", "ev", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// PlannedReparentShard will make the provided tablet the master for the shard, // when both the current and new master are reachable and in good shape.
[ "PlannedReparentShard", "will", "make", "the", "provided", "tablet", "the", "master", "for", "the", "shard", "when", "both", "the", "current", "and", "new", "master", "are", "reachable", "and", "in", "good", "shape", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/reparent.go#L331-L363
train
vitessio/vitess
go/vt/wrangler/reparent.go
EmergencyReparentShard
func (wr *Wrangler) EmergencyReparentShard(ctx context.Context, keyspace, shard string, masterElectTabletAlias *topodatapb.TabletAlias, waitSlaveTimeout time.Duration) (err error) { // lock the shard ctx, unlock, lockErr := wr.ts.LockShard(ctx, keyspace, shard, fmt.Sprintf("EmergencyReparentShard(%v)", topoproto.TabletAliasString(masterElectTabletAlias))) if lockErr != nil { return lockErr } defer unlock(&err) // Create reusable Reparent event with available info ev := &events.Reparent{} // do the work err = wr.emergencyReparentShardLocked(ctx, ev, keyspace, shard, masterElectTabletAlias, waitSlaveTimeout) if err != nil { event.DispatchUpdate(ev, "failed EmergencyReparentShard: "+err.Error()) } else { event.DispatchUpdate(ev, "finished EmergencyReparentShard") } return err }
go
func (wr *Wrangler) EmergencyReparentShard(ctx context.Context, keyspace, shard string, masterElectTabletAlias *topodatapb.TabletAlias, waitSlaveTimeout time.Duration) (err error) { // lock the shard ctx, unlock, lockErr := wr.ts.LockShard(ctx, keyspace, shard, fmt.Sprintf("EmergencyReparentShard(%v)", topoproto.TabletAliasString(masterElectTabletAlias))) if lockErr != nil { return lockErr } defer unlock(&err) // Create reusable Reparent event with available info ev := &events.Reparent{} // do the work err = wr.emergencyReparentShardLocked(ctx, ev, keyspace, shard, masterElectTabletAlias, waitSlaveTimeout) if err != nil { event.DispatchUpdate(ev, "failed EmergencyReparentShard: "+err.Error()) } else { event.DispatchUpdate(ev, "finished EmergencyReparentShard") } return err }
[ "func", "(", "wr", "*", "Wrangler", ")", "EmergencyReparentShard", "(", "ctx", "context", ".", "Context", ",", "keyspace", ",", "shard", "string", ",", "masterElectTabletAlias", "*", "topodatapb", ".", "TabletAlias", ",", "waitSlaveTimeout", "time", ".", "Duration", ")", "(", "err", "error", ")", "{", "// lock the shard", "ctx", ",", "unlock", ",", "lockErr", ":=", "wr", ".", "ts", ".", "LockShard", "(", "ctx", ",", "keyspace", ",", "shard", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "topoproto", ".", "TabletAliasString", "(", "masterElectTabletAlias", ")", ")", ")", "\n", "if", "lockErr", "!=", "nil", "{", "return", "lockErr", "\n", "}", "\n", "defer", "unlock", "(", "&", "err", ")", "\n\n", "// Create reusable Reparent event with available info", "ev", ":=", "&", "events", ".", "Reparent", "{", "}", "\n\n", "// do the work", "err", "=", "wr", ".", "emergencyReparentShardLocked", "(", "ctx", ",", "ev", ",", "keyspace", ",", "shard", ",", "masterElectTabletAlias", ",", "waitSlaveTimeout", ")", "\n", "if", "err", "!=", "nil", "{", "event", ".", "DispatchUpdate", "(", "ev", ",", "\"", "\"", "+", "err", ".", "Error", "(", ")", ")", "\n", "}", "else", "{", "event", ".", "DispatchUpdate", "(", "ev", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// EmergencyReparentShard will make the provided tablet the master for // the shard, when the old master is completely unreachable.
[ "EmergencyReparentShard", "will", "make", "the", "provided", "tablet", "the", "master", "for", "the", "shard", "when", "the", "old", "master", "is", "completely", "unreachable", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/reparent.go#L606-L625
train
vitessio/vitess
go/vt/vttablet/tabletserver/messager/engine.go
Subscribe
func (me *Engine) Subscribe(ctx context.Context, name string, send func(*sqltypes.Result) error) (done <-chan struct{}, err error) { me.mu.Lock() defer me.mu.Unlock() if !me.isOpen { return nil, vterrors.Errorf(vtrpcpb.Code_UNAVAILABLE, "messager engine is closed, probably because this is not a master any more") } mm := me.managers[name] if mm == nil { return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "message table %s not found", name) } return mm.Subscribe(ctx, send), nil }
go
func (me *Engine) Subscribe(ctx context.Context, name string, send func(*sqltypes.Result) error) (done <-chan struct{}, err error) { me.mu.Lock() defer me.mu.Unlock() if !me.isOpen { return nil, vterrors.Errorf(vtrpcpb.Code_UNAVAILABLE, "messager engine is closed, probably because this is not a master any more") } mm := me.managers[name] if mm == nil { return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "message table %s not found", name) } return mm.Subscribe(ctx, send), nil }
[ "func", "(", "me", "*", "Engine", ")", "Subscribe", "(", "ctx", "context", ".", "Context", ",", "name", "string", ",", "send", "func", "(", "*", "sqltypes", ".", "Result", ")", "error", ")", "(", "done", "<-", "chan", "struct", "{", "}", ",", "err", "error", ")", "{", "me", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "me", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "!", "me", ".", "isOpen", "{", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_UNAVAILABLE", ",", "\"", "\"", ")", "\n", "}", "\n", "mm", ":=", "me", ".", "managers", "[", "name", "]", "\n", "if", "mm", "==", "nil", "{", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "return", "mm", ".", "Subscribe", "(", "ctx", ",", "send", ")", ",", "nil", "\n", "}" ]
// Subscribe subscribes to messages from the requested table. // The function returns a done channel that will be closed when // the subscription ends, which can be initiated by the send function // returning io.EOF. The engine can also end a subscription which is // usually triggered by Close. It's the responsibility of the send // function to promptly return if the done channel is closed. Otherwise, // the engine's Close function will hang indefinitely.
[ "Subscribe", "subscribes", "to", "messages", "from", "the", "requested", "table", ".", "The", "function", "returns", "a", "done", "channel", "that", "will", "be", "closed", "when", "the", "subscription", "ends", "which", "can", "be", "initiated", "by", "the", "send", "function", "returning", "io", ".", "EOF", ".", "The", "engine", "can", "also", "end", "a", "subscription", "which", "is", "usually", "triggered", "by", "Close", ".", "It", "s", "the", "responsibility", "of", "the", "send", "function", "to", "promptly", "return", "if", "the", "done", "channel", "is", "closed", ".", "Otherwise", "the", "engine", "s", "Close", "function", "will", "hang", "indefinitely", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/messager/engine.go#L117-L128
train
vitessio/vitess
go/vt/vttablet/tabletserver/messager/engine.go
LockDB
func (me *Engine) LockDB(newMessages map[string][]*MessageRow, changedMessages map[string][]string) func() { // Short-circuit to avoid taking any locks if there's nothing to do. if len(newMessages) == 0 && len(changedMessages) == 0 { return func() {} } // Build the set of affected messages tables. combined := make(map[string]struct{}) for name := range newMessages { combined[name] = struct{}{} } for name := range changedMessages { combined[name] = struct{}{} } // Build the list of manager objects (one per table). var mms []*messageManager // Don't do DBLock while holding lock on mu. // It causes deadlocks. func() { me.mu.Lock() defer me.mu.Unlock() for name := range combined { if mm := me.managers[name]; mm != nil { mms = append(mms, mm) } } }() if len(mms) > 1 { // Always use the same order in which manager objects are locked to avoid deadlocks. // The previous order in "mms" is not guaranteed for multiple reasons: // - We use a Go map above which does not guarantee an iteration order. // - Transactions may not always use the same order when writing to multiple // messages tables. sort.Slice(mms, func(i, j int) bool { return mms[i].name.String() < mms[j].name.String() }) } // Lock each manager/messages table. for _, mm := range mms { mm.DBLock.Lock() } return func() { for _, mm := range mms { mm.DBLock.Unlock() } } }
go
func (me *Engine) LockDB(newMessages map[string][]*MessageRow, changedMessages map[string][]string) func() { // Short-circuit to avoid taking any locks if there's nothing to do. if len(newMessages) == 0 && len(changedMessages) == 0 { return func() {} } // Build the set of affected messages tables. combined := make(map[string]struct{}) for name := range newMessages { combined[name] = struct{}{} } for name := range changedMessages { combined[name] = struct{}{} } // Build the list of manager objects (one per table). var mms []*messageManager // Don't do DBLock while holding lock on mu. // It causes deadlocks. func() { me.mu.Lock() defer me.mu.Unlock() for name := range combined { if mm := me.managers[name]; mm != nil { mms = append(mms, mm) } } }() if len(mms) > 1 { // Always use the same order in which manager objects are locked to avoid deadlocks. // The previous order in "mms" is not guaranteed for multiple reasons: // - We use a Go map above which does not guarantee an iteration order. // - Transactions may not always use the same order when writing to multiple // messages tables. sort.Slice(mms, func(i, j int) bool { return mms[i].name.String() < mms[j].name.String() }) } // Lock each manager/messages table. for _, mm := range mms { mm.DBLock.Lock() } return func() { for _, mm := range mms { mm.DBLock.Unlock() } } }
[ "func", "(", "me", "*", "Engine", ")", "LockDB", "(", "newMessages", "map", "[", "string", "]", "[", "]", "*", "MessageRow", ",", "changedMessages", "map", "[", "string", "]", "[", "]", "string", ")", "func", "(", ")", "{", "// Short-circuit to avoid taking any locks if there's nothing to do.", "if", "len", "(", "newMessages", ")", "==", "0", "&&", "len", "(", "changedMessages", ")", "==", "0", "{", "return", "func", "(", ")", "{", "}", "\n", "}", "\n\n", "// Build the set of affected messages tables.", "combined", ":=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "for", "name", ":=", "range", "newMessages", "{", "combined", "[", "name", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "for", "name", ":=", "range", "changedMessages", "{", "combined", "[", "name", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n\n", "// Build the list of manager objects (one per table).", "var", "mms", "[", "]", "*", "messageManager", "\n", "// Don't do DBLock while holding lock on mu.", "// It causes deadlocks.", "func", "(", ")", "{", "me", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "me", ".", "mu", ".", "Unlock", "(", ")", "\n", "for", "name", ":=", "range", "combined", "{", "if", "mm", ":=", "me", ".", "managers", "[", "name", "]", ";", "mm", "!=", "nil", "{", "mms", "=", "append", "(", "mms", ",", "mm", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "if", "len", "(", "mms", ")", ">", "1", "{", "// Always use the same order in which manager objects are locked to avoid deadlocks.", "// The previous order in \"mms\" is not guaranteed for multiple reasons:", "// - We use a Go map above which does not guarantee an iteration order.", "// - Transactions may not always use the same order when writing to multiple", "// messages tables.", "sort", ".", "Slice", "(", "mms", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "mms", "[", "i", "]", ".", "name", ".", "String", "(", ")", "<", "mms", "[", "j", "]", ".", "name", ".", "String", "(", ")", "}", ")", "\n", "}", "\n\n", "// Lock each manager/messages table.", "for", "_", ",", "mm", ":=", "range", "mms", "{", "mm", ".", "DBLock", ".", "Lock", "(", ")", "\n", "}", "\n", "return", "func", "(", ")", "{", "for", "_", ",", "mm", ":=", "range", "mms", "{", "mm", ".", "DBLock", ".", "Unlock", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// LockDB obtains db locks for all messages that need to // be updated and returns the counterpart unlock function.
[ "LockDB", "obtains", "db", "locks", "for", "all", "messages", "that", "need", "to", "be", "updated", "and", "returns", "the", "counterpart", "unlock", "function", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/messager/engine.go#L132-L178
train
vitessio/vitess
go/vt/vttablet/tabletserver/messager/engine.go
UpdateCaches
func (me *Engine) UpdateCaches(newMessages map[string][]*MessageRow, changedMessages map[string][]string) { // Short-circuit to avoid taking any locks if there's nothing to do. if len(newMessages) == 0 && len(changedMessages) == 0 { return } me.mu.Lock() defer me.mu.Unlock() now := time.Now().UnixNano() for name, mrs := range newMessages { mm := me.managers[name] if mm == nil { continue } MessageStats.Add([]string{name, "Queued"}, int64(len(mrs))) for _, mr := range mrs { if mr.TimeNext > now { // We don't handle future messages yet. continue } mm.Add(mr) } } for name, ids := range changedMessages { mm := me.managers[name] if mm == nil { continue } mm.cache.Discard(ids) } }
go
func (me *Engine) UpdateCaches(newMessages map[string][]*MessageRow, changedMessages map[string][]string) { // Short-circuit to avoid taking any locks if there's nothing to do. if len(newMessages) == 0 && len(changedMessages) == 0 { return } me.mu.Lock() defer me.mu.Unlock() now := time.Now().UnixNano() for name, mrs := range newMessages { mm := me.managers[name] if mm == nil { continue } MessageStats.Add([]string{name, "Queued"}, int64(len(mrs))) for _, mr := range mrs { if mr.TimeNext > now { // We don't handle future messages yet. continue } mm.Add(mr) } } for name, ids := range changedMessages { mm := me.managers[name] if mm == nil { continue } mm.cache.Discard(ids) } }
[ "func", "(", "me", "*", "Engine", ")", "UpdateCaches", "(", "newMessages", "map", "[", "string", "]", "[", "]", "*", "MessageRow", ",", "changedMessages", "map", "[", "string", "]", "[", "]", "string", ")", "{", "// Short-circuit to avoid taking any locks if there's nothing to do.", "if", "len", "(", "newMessages", ")", "==", "0", "&&", "len", "(", "changedMessages", ")", "==", "0", "{", "return", "\n", "}", "\n\n", "me", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "me", ".", "mu", ".", "Unlock", "(", ")", "\n", "now", ":=", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", "\n", "for", "name", ",", "mrs", ":=", "range", "newMessages", "{", "mm", ":=", "me", ".", "managers", "[", "name", "]", "\n", "if", "mm", "==", "nil", "{", "continue", "\n", "}", "\n", "MessageStats", ".", "Add", "(", "[", "]", "string", "{", "name", ",", "\"", "\"", "}", ",", "int64", "(", "len", "(", "mrs", ")", ")", ")", "\n", "for", "_", ",", "mr", ":=", "range", "mrs", "{", "if", "mr", ".", "TimeNext", ">", "now", "{", "// We don't handle future messages yet.", "continue", "\n", "}", "\n", "mm", ".", "Add", "(", "mr", ")", "\n", "}", "\n", "}", "\n", "for", "name", ",", "ids", ":=", "range", "changedMessages", "{", "mm", ":=", "me", ".", "managers", "[", "name", "]", "\n", "if", "mm", "==", "nil", "{", "continue", "\n", "}", "\n", "mm", ".", "cache", ".", "Discard", "(", "ids", ")", "\n", "}", "\n", "}" ]
// UpdateCaches updates the caches for the committed changes.
[ "UpdateCaches", "updates", "the", "caches", "for", "the", "committed", "changes", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/messager/engine.go#L181-L211
train
vitessio/vitess
go/vt/vttablet/tabletserver/messager/engine.go
GenerateLoadMessagesQuery
func (me *Engine) GenerateLoadMessagesQuery(name string) (*sqlparser.ParsedQuery, error) { me.mu.Lock() defer me.mu.Unlock() mm := me.managers[name] if mm == nil { return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "message table %s not found in schema", name) } return mm.loadMessagesQuery, nil }
go
func (me *Engine) GenerateLoadMessagesQuery(name string) (*sqlparser.ParsedQuery, error) { me.mu.Lock() defer me.mu.Unlock() mm := me.managers[name] if mm == nil { return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "message table %s not found in schema", name) } return mm.loadMessagesQuery, nil }
[ "func", "(", "me", "*", "Engine", ")", "GenerateLoadMessagesQuery", "(", "name", "string", ")", "(", "*", "sqlparser", ".", "ParsedQuery", ",", "error", ")", "{", "me", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "me", ".", "mu", ".", "Unlock", "(", ")", "\n", "mm", ":=", "me", ".", "managers", "[", "name", "]", "\n", "if", "mm", "==", "nil", "{", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "return", "mm", ".", "loadMessagesQuery", ",", "nil", "\n", "}" ]
// GenerateLoadMessagesQuery returns the ParsedQuery for loading messages by pk. // The results of the query can be used in a BuildMessageRow call.
[ "GenerateLoadMessagesQuery", "returns", "the", "ParsedQuery", "for", "loading", "messages", "by", "pk", ".", "The", "results", "of", "the", "query", "can", "be", "used", "in", "a", "BuildMessageRow", "call", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/messager/engine.go#L215-L223
train
vitessio/vitess
go/vt/topo/zk2topo/zk_conn.go
Connect
func Connect(addr string) *ZkConn { return &ZkConn{ addr: addr, sem: sync2.NewSemaphore(*maxConcurrency, 0), } }
go
func Connect(addr string) *ZkConn { return &ZkConn{ addr: addr, sem: sync2.NewSemaphore(*maxConcurrency, 0), } }
[ "func", "Connect", "(", "addr", "string", ")", "*", "ZkConn", "{", "return", "&", "ZkConn", "{", "addr", ":", "addr", ",", "sem", ":", "sync2", ".", "NewSemaphore", "(", "*", "maxConcurrency", ",", "0", ")", ",", "}", "\n", "}" ]
// Connect to the Zookeeper servers specified in addr // addr can be a comma separated list of servers and each server can be a DNS entry with multiple values. // Connects to the endpoints in a randomized order to avoid hot spots.
[ "Connect", "to", "the", "Zookeeper", "servers", "specified", "in", "addr", "addr", "can", "be", "a", "comma", "separated", "list", "of", "servers", "and", "each", "server", "can", "be", "a", "DNS", "entry", "with", "multiple", "values", ".", "Connects", "to", "the", "endpoints", "in", "a", "randomized", "order", "to", "avoid", "hot", "spots", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/zk2topo/zk_conn.go#L96-L101
train
vitessio/vitess
go/vt/topo/zk2topo/zk_conn.go
Get
func (c *ZkConn) Get(ctx context.Context, path string) (data []byte, stat *zk.Stat, err error) { err = c.withRetry(ctx, func(conn *zk.Conn) error { data, stat, err = conn.Get(path) return err }) return }
go
func (c *ZkConn) Get(ctx context.Context, path string) (data []byte, stat *zk.Stat, err error) { err = c.withRetry(ctx, func(conn *zk.Conn) error { data, stat, err = conn.Get(path) return err }) return }
[ "func", "(", "c", "*", "ZkConn", ")", "Get", "(", "ctx", "context", ".", "Context", ",", "path", "string", ")", "(", "data", "[", "]", "byte", ",", "stat", "*", "zk", ".", "Stat", ",", "err", "error", ")", "{", "err", "=", "c", ".", "withRetry", "(", "ctx", ",", "func", "(", "conn", "*", "zk", ".", "Conn", ")", "error", "{", "data", ",", "stat", ",", "err", "=", "conn", ".", "Get", "(", "path", ")", "\n", "return", "err", "\n", "}", ")", "\n", "return", "\n", "}" ]
// Get is part of the Conn interface.
[ "Get", "is", "part", "of", "the", "Conn", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/zk2topo/zk_conn.go#L104-L110
train
vitessio/vitess
go/vt/topo/zk2topo/zk_conn.go
Children
func (c *ZkConn) Children(ctx context.Context, path string) (children []string, stat *zk.Stat, err error) { err = c.withRetry(ctx, func(conn *zk.Conn) error { children, stat, err = conn.Children(path) return err }) return }
go
func (c *ZkConn) Children(ctx context.Context, path string) (children []string, stat *zk.Stat, err error) { err = c.withRetry(ctx, func(conn *zk.Conn) error { children, stat, err = conn.Children(path) return err }) return }
[ "func", "(", "c", "*", "ZkConn", ")", "Children", "(", "ctx", "context", ".", "Context", ",", "path", "string", ")", "(", "children", "[", "]", "string", ",", "stat", "*", "zk", ".", "Stat", ",", "err", "error", ")", "{", "err", "=", "c", ".", "withRetry", "(", "ctx", ",", "func", "(", "conn", "*", "zk", ".", "Conn", ")", "error", "{", "children", ",", "stat", ",", "err", "=", "conn", ".", "Children", "(", "path", ")", "\n", "return", "err", "\n", "}", ")", "\n", "return", "\n", "}" ]
// Children is part of the Conn interface.
[ "Children", "is", "part", "of", "the", "Conn", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/zk2topo/zk_conn.go#L122-L128
train
vitessio/vitess
go/vt/topo/zk2topo/zk_conn.go
Exists
func (c *ZkConn) Exists(ctx context.Context, path string) (exists bool, stat *zk.Stat, err error) { err = c.withRetry(ctx, func(conn *zk.Conn) error { exists, stat, err = conn.Exists(path) return err }) return }
go
func (c *ZkConn) Exists(ctx context.Context, path string) (exists bool, stat *zk.Stat, err error) { err = c.withRetry(ctx, func(conn *zk.Conn) error { exists, stat, err = conn.Exists(path) return err }) return }
[ "func", "(", "c", "*", "ZkConn", ")", "Exists", "(", "ctx", "context", ".", "Context", ",", "path", "string", ")", "(", "exists", "bool", ",", "stat", "*", "zk", ".", "Stat", ",", "err", "error", ")", "{", "err", "=", "c", ".", "withRetry", "(", "ctx", ",", "func", "(", "conn", "*", "zk", ".", "Conn", ")", "error", "{", "exists", ",", "stat", ",", "err", "=", "conn", ".", "Exists", "(", "path", ")", "\n", "return", "err", "\n", "}", ")", "\n", "return", "\n", "}" ]
// Exists is part of the Conn interface.
[ "Exists", "is", "part", "of", "the", "Conn", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/zk2topo/zk_conn.go#L140-L146
train
vitessio/vitess
go/vt/topo/zk2topo/zk_conn.go
Create
func (c *ZkConn) Create(ctx context.Context, path string, value []byte, flags int32, aclv []zk.ACL) (pathCreated string, err error) { err = c.withRetry(ctx, func(conn *zk.Conn) error { pathCreated, err = conn.Create(path, value, flags, aclv) return err }) return }
go
func (c *ZkConn) Create(ctx context.Context, path string, value []byte, flags int32, aclv []zk.ACL) (pathCreated string, err error) { err = c.withRetry(ctx, func(conn *zk.Conn) error { pathCreated, err = conn.Create(path, value, flags, aclv) return err }) return }
[ "func", "(", "c", "*", "ZkConn", ")", "Create", "(", "ctx", "context", ".", "Context", ",", "path", "string", ",", "value", "[", "]", "byte", ",", "flags", "int32", ",", "aclv", "[", "]", "zk", ".", "ACL", ")", "(", "pathCreated", "string", ",", "err", "error", ")", "{", "err", "=", "c", ".", "withRetry", "(", "ctx", ",", "func", "(", "conn", "*", "zk", ".", "Conn", ")", "error", "{", "pathCreated", ",", "err", "=", "conn", ".", "Create", "(", "path", ",", "value", ",", "flags", ",", "aclv", ")", "\n", "return", "err", "\n", "}", ")", "\n", "return", "\n", "}" ]
// Create is part of the Conn interface.
[ "Create", "is", "part", "of", "the", "Conn", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/zk2topo/zk_conn.go#L158-L164
train
vitessio/vitess
go/vt/topo/zk2topo/zk_conn.go
Set
func (c *ZkConn) Set(ctx context.Context, path string, value []byte, version int32) (stat *zk.Stat, err error) { err = c.withRetry(ctx, func(conn *zk.Conn) error { stat, err = conn.Set(path, value, version) return err }) return }
go
func (c *ZkConn) Set(ctx context.Context, path string, value []byte, version int32) (stat *zk.Stat, err error) { err = c.withRetry(ctx, func(conn *zk.Conn) error { stat, err = conn.Set(path, value, version) return err }) return }
[ "func", "(", "c", "*", "ZkConn", ")", "Set", "(", "ctx", "context", ".", "Context", ",", "path", "string", ",", "value", "[", "]", "byte", ",", "version", "int32", ")", "(", "stat", "*", "zk", ".", "Stat", ",", "err", "error", ")", "{", "err", "=", "c", ".", "withRetry", "(", "ctx", ",", "func", "(", "conn", "*", "zk", ".", "Conn", ")", "error", "{", "stat", ",", "err", "=", "conn", ".", "Set", "(", "path", ",", "value", ",", "version", ")", "\n", "return", "err", "\n", "}", ")", "\n", "return", "\n", "}" ]
// Set is part of the Conn interface.
[ "Set", "is", "part", "of", "the", "Conn", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/zk2topo/zk_conn.go#L167-L173
train
vitessio/vitess
go/vt/topo/zk2topo/zk_conn.go
Delete
func (c *ZkConn) Delete(ctx context.Context, path string, version int32) error { return c.withRetry(ctx, func(conn *zk.Conn) error { return conn.Delete(path, version) }) }
go
func (c *ZkConn) Delete(ctx context.Context, path string, version int32) error { return c.withRetry(ctx, func(conn *zk.Conn) error { return conn.Delete(path, version) }) }
[ "func", "(", "c", "*", "ZkConn", ")", "Delete", "(", "ctx", "context", ".", "Context", ",", "path", "string", ",", "version", "int32", ")", "error", "{", "return", "c", ".", "withRetry", "(", "ctx", ",", "func", "(", "conn", "*", "zk", ".", "Conn", ")", "error", "{", "return", "conn", ".", "Delete", "(", "path", ",", "version", ")", "\n", "}", ")", "\n", "}" ]
// Delete is part of the Conn interface.
[ "Delete", "is", "part", "of", "the", "Conn", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/zk2topo/zk_conn.go#L176-L180
train
vitessio/vitess
go/vt/topo/zk2topo/zk_conn.go
GetACL
func (c *ZkConn) GetACL(ctx context.Context, path string) (aclv []zk.ACL, stat *zk.Stat, err error) { err = c.withRetry(ctx, func(conn *zk.Conn) error { aclv, stat, err = conn.GetACL(path) return err }) return }
go
func (c *ZkConn) GetACL(ctx context.Context, path string) (aclv []zk.ACL, stat *zk.Stat, err error) { err = c.withRetry(ctx, func(conn *zk.Conn) error { aclv, stat, err = conn.GetACL(path) return err }) return }
[ "func", "(", "c", "*", "ZkConn", ")", "GetACL", "(", "ctx", "context", ".", "Context", ",", "path", "string", ")", "(", "aclv", "[", "]", "zk", ".", "ACL", ",", "stat", "*", "zk", ".", "Stat", ",", "err", "error", ")", "{", "err", "=", "c", ".", "withRetry", "(", "ctx", ",", "func", "(", "conn", "*", "zk", ".", "Conn", ")", "error", "{", "aclv", ",", "stat", ",", "err", "=", "conn", ".", "GetACL", "(", "path", ")", "\n", "return", "err", "\n", "}", ")", "\n", "return", "\n", "}" ]
// GetACL is part of the Conn interface.
[ "GetACL", "is", "part", "of", "the", "Conn", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/zk2topo/zk_conn.go#L183-L189
train
vitessio/vitess
go/vt/topo/zk2topo/zk_conn.go
SetACL
func (c *ZkConn) SetACL(ctx context.Context, path string, aclv []zk.ACL, version int32) error { return c.withRetry(ctx, func(conn *zk.Conn) error { _, err := conn.SetACL(path, aclv, version) return err }) }
go
func (c *ZkConn) SetACL(ctx context.Context, path string, aclv []zk.ACL, version int32) error { return c.withRetry(ctx, func(conn *zk.Conn) error { _, err := conn.SetACL(path, aclv, version) return err }) }
[ "func", "(", "c", "*", "ZkConn", ")", "SetACL", "(", "ctx", "context", ".", "Context", ",", "path", "string", ",", "aclv", "[", "]", "zk", ".", "ACL", ",", "version", "int32", ")", "error", "{", "return", "c", ".", "withRetry", "(", "ctx", ",", "func", "(", "conn", "*", "zk", ".", "Conn", ")", "error", "{", "_", ",", "err", ":=", "conn", ".", "SetACL", "(", "path", ",", "aclv", ",", "version", ")", "\n", "return", "err", "\n", "}", ")", "\n", "}" ]
// SetACL is part of the Conn interface.
[ "SetACL", "is", "part", "of", "the", "Conn", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/zk2topo/zk_conn.go#L192-L197
train
vitessio/vitess
go/vt/topo/zk2topo/zk_conn.go
AddAuth
func (c *ZkConn) AddAuth(ctx context.Context, scheme string, auth []byte) error { return c.withRetry(ctx, func(conn *zk.Conn) error { err := conn.AddAuth(scheme, auth) return err }) }
go
func (c *ZkConn) AddAuth(ctx context.Context, scheme string, auth []byte) error { return c.withRetry(ctx, func(conn *zk.Conn) error { err := conn.AddAuth(scheme, auth) return err }) }
[ "func", "(", "c", "*", "ZkConn", ")", "AddAuth", "(", "ctx", "context", ".", "Context", ",", "scheme", "string", ",", "auth", "[", "]", "byte", ")", "error", "{", "return", "c", ".", "withRetry", "(", "ctx", ",", "func", "(", "conn", "*", "zk", ".", "Conn", ")", "error", "{", "err", ":=", "conn", ".", "AddAuth", "(", "scheme", ",", "auth", ")", "\n", "return", "err", "\n", "}", ")", "\n", "}" ]
// AddAuth is part of the Conn interface.
[ "AddAuth", "is", "part", "of", "the", "Conn", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/zk2topo/zk_conn.go#L200-L205
train
vitessio/vitess
go/vt/topo/zk2topo/zk_conn.go
Close
func (c *ZkConn) Close() error { c.mu.Lock() defer c.mu.Unlock() if c.conn != nil { c.conn.Close() } return nil }
go
func (c *ZkConn) Close() error { c.mu.Lock() defer c.mu.Unlock() if c.conn != nil { c.conn.Close() } return nil }
[ "func", "(", "c", "*", "ZkConn", ")", "Close", "(", ")", "error", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "c", ".", "conn", "!=", "nil", "{", "c", ".", "conn", ".", "Close", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close is part of the Conn interface.
[ "Close", "is", "part", "of", "the", "Conn", "interface", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/zk2topo/zk_conn.go#L208-L215
train
vitessio/vitess
go/vt/topo/zk2topo/zk_conn.go
getConn
func (c *ZkConn) getConn(ctx context.Context) (*zk.Conn, error) { c.mu.Lock() defer c.mu.Unlock() if c.conn == nil { conn, events, err := dialZk(ctx, c.addr) if err != nil { return nil, err } c.conn = conn go c.handleSessionEvents(conn, events) c.maybeAddAuth(ctx) } return c.conn, nil }
go
func (c *ZkConn) getConn(ctx context.Context) (*zk.Conn, error) { c.mu.Lock() defer c.mu.Unlock() if c.conn == nil { conn, events, err := dialZk(ctx, c.addr) if err != nil { return nil, err } c.conn = conn go c.handleSessionEvents(conn, events) c.maybeAddAuth(ctx) } return c.conn, nil }
[ "func", "(", "c", "*", "ZkConn", ")", "getConn", "(", "ctx", "context", ".", "Context", ")", "(", "*", "zk", ".", "Conn", ",", "error", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "c", ".", "conn", "==", "nil", "{", "conn", ",", "events", ",", "err", ":=", "dialZk", "(", "ctx", ",", "c", ".", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "c", ".", "conn", "=", "conn", "\n", "go", "c", ".", "handleSessionEvents", "(", "conn", ",", "events", ")", "\n", "c", ".", "maybeAddAuth", "(", "ctx", ")", "\n", "}", "\n", "return", "c", ".", "conn", ",", "nil", "\n", "}" ]
// getConn returns the connection in a thread safe way. It will try to connect // if not connected yet.
[ "getConn", "returns", "the", "connection", "in", "a", "thread", "safe", "way", ".", "It", "will", "try", "to", "connect", "if", "not", "connected", "yet", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/zk2topo/zk_conn.go#L272-L286
train
vitessio/vitess
go/vt/topo/zk2topo/zk_conn.go
maybeAddAuth
func (c *ZkConn) maybeAddAuth(ctx context.Context) { if *authFile == "" { return } authInfoBytes, err := ioutil.ReadFile(*authFile) if err != nil { log.Errorf("failed to read topo_zk_auth_file: %v", err) return } authInfo := string(authInfoBytes) authInfoParts := strings.SplitN(authInfo, ":", 2) if len(authInfoParts) != 2 { log.Errorf("failed to parse topo_zk_auth_file contents, expected format <scheme>:<auth> but saw: %s", authInfo) return } err = c.conn.AddAuth(authInfoParts[0], []byte(authInfoParts[1])) if err != nil { log.Errorf("failed to add auth from topo_zk_auth_file: %v", err) return } }
go
func (c *ZkConn) maybeAddAuth(ctx context.Context) { if *authFile == "" { return } authInfoBytes, err := ioutil.ReadFile(*authFile) if err != nil { log.Errorf("failed to read topo_zk_auth_file: %v", err) return } authInfo := string(authInfoBytes) authInfoParts := strings.SplitN(authInfo, ":", 2) if len(authInfoParts) != 2 { log.Errorf("failed to parse topo_zk_auth_file contents, expected format <scheme>:<auth> but saw: %s", authInfo) return } err = c.conn.AddAuth(authInfoParts[0], []byte(authInfoParts[1])) if err != nil { log.Errorf("failed to add auth from topo_zk_auth_file: %v", err) return } }
[ "func", "(", "c", "*", "ZkConn", ")", "maybeAddAuth", "(", "ctx", "context", ".", "Context", ")", "{", "if", "*", "authFile", "==", "\"", "\"", "{", "return", "\n", "}", "\n", "authInfoBytes", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "*", "authFile", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "authInfo", ":=", "string", "(", "authInfoBytes", ")", "\n", "authInfoParts", ":=", "strings", ".", "SplitN", "(", "authInfo", ",", "\"", "\"", ",", "2", ")", "\n", "if", "len", "(", "authInfoParts", ")", "!=", "2", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "authInfo", ")", "\n", "return", "\n", "}", "\n", "err", "=", "c", ".", "conn", ".", "AddAuth", "(", "authInfoParts", "[", "0", "]", ",", "[", "]", "byte", "(", "authInfoParts", "[", "1", "]", ")", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}" ]
// maybeAddAuth calls AddAuth if the `-topo_zk_auth_file` flag was specified
[ "maybeAddAuth", "calls", "AddAuth", "if", "the", "-", "topo_zk_auth_file", "flag", "was", "specified" ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/zk2topo/zk_conn.go#L289-L309
train
vitessio/vitess
go/vt/topo/zk2topo/zk_conn.go
handleSessionEvents
func (c *ZkConn) handleSessionEvents(conn *zk.Conn, session <-chan zk.Event) { for event := range session { closeRequired := false switch event.State { case zk.StateExpired, zk.StateConnecting: closeRequired = true fallthrough case zk.StateDisconnected: c.mu.Lock() if c.conn == conn { // The ZkConn still references this // connection, let's nil it. c.conn = nil } c.mu.Unlock() if closeRequired { conn.Close() } log.Infof("zk conn: session for addr %v ended: %v", c.addr, event) return } log.Infof("zk conn: session for addr %v event: %v", c.addr, event) } }
go
func (c *ZkConn) handleSessionEvents(conn *zk.Conn, session <-chan zk.Event) { for event := range session { closeRequired := false switch event.State { case zk.StateExpired, zk.StateConnecting: closeRequired = true fallthrough case zk.StateDisconnected: c.mu.Lock() if c.conn == conn { // The ZkConn still references this // connection, let's nil it. c.conn = nil } c.mu.Unlock() if closeRequired { conn.Close() } log.Infof("zk conn: session for addr %v ended: %v", c.addr, event) return } log.Infof("zk conn: session for addr %v event: %v", c.addr, event) } }
[ "func", "(", "c", "*", "ZkConn", ")", "handleSessionEvents", "(", "conn", "*", "zk", ".", "Conn", ",", "session", "<-", "chan", "zk", ".", "Event", ")", "{", "for", "event", ":=", "range", "session", "{", "closeRequired", ":=", "false", "\n\n", "switch", "event", ".", "State", "{", "case", "zk", ".", "StateExpired", ",", "zk", ".", "StateConnecting", ":", "closeRequired", "=", "true", "\n", "fallthrough", "\n", "case", "zk", ".", "StateDisconnected", ":", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "c", ".", "conn", "==", "conn", "{", "// The ZkConn still references this", "// connection, let's nil it.", "c", ".", "conn", "=", "nil", "\n", "}", "\n", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "closeRequired", "{", "conn", ".", "Close", "(", ")", "\n", "}", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "c", ".", "addr", ",", "event", ")", "\n", "return", "\n", "}", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "c", ".", "addr", ",", "event", ")", "\n", "}", "\n", "}" ]
// handleSessionEvents is processing events from the session channel. // When it detects that the connection is not working any more, it // clears out the connection record.
[ "handleSessionEvents", "is", "processing", "events", "from", "the", "session", "channel", ".", "When", "it", "detects", "that", "the", "connection", "is", "not", "working", "any", "more", "it", "clears", "out", "the", "connection", "record", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/zk2topo/zk_conn.go#L314-L338
train
vitessio/vitess
go/vt/topo/zk2topo/zk_conn.go
dialZk
func dialZk(ctx context.Context, addr string) (*zk.Conn, <-chan zk.Event, error) { servers := strings.Split(addr, ",") options := zk.WithDialer(net.DialTimeout) // If TLS is enabled use a TLS enabled dialer option if *certPath != "" && *keyPath != "" { if strings.Contains(addr, ",") { log.Fatalf("This TLS zk code requires that the all the zk servers validate to a single server name.") } serverName := strings.Split(addr, ":")[0] log.Infof("Using TLS ZK, connecting to %v server name %v", addr, serverName) cert, err := tls.LoadX509KeyPair(*certPath, *keyPath) if err != nil { log.Fatalf("Unable to load cert %v and key %v, err %v", *certPath, *keyPath, err) } clientCACert, err := ioutil.ReadFile(*caPath) if err != nil { log.Fatalf("Unable to open ca cert %v, err %v", *caPath, err) } clientCertPool := x509.NewCertPool() clientCertPool.AppendCertsFromPEM(clientCACert) tlsConfig := &tls.Config{ Certificates: []tls.Certificate{cert}, RootCAs: clientCertPool, ServerName: serverName, } tlsConfig.BuildNameToCertificate() options = zk.WithDialer(func(network, address string, timeout time.Duration) (net.Conn, error) { d := net.Dialer{Timeout: timeout} return tls.DialWithDialer(&d, network, address, tlsConfig) }) } // zk.Connect automatically shuffles the servers zconn, session, err := zk.Connect(servers, *baseTimeout, options) if err != nil { return nil, nil, err } // Wait for connection, skipping transition states. for { select { case <-ctx.Done(): zconn.Close() return nil, nil, ctx.Err() case event := <-session: switch event.State { case zk.StateConnected: // success return zconn, session, nil case zk.StateAuthFailed: // fast fail this one zconn.Close() return nil, nil, fmt.Errorf("zk connect failed: StateAuthFailed") } } } }
go
func dialZk(ctx context.Context, addr string) (*zk.Conn, <-chan zk.Event, error) { servers := strings.Split(addr, ",") options := zk.WithDialer(net.DialTimeout) // If TLS is enabled use a TLS enabled dialer option if *certPath != "" && *keyPath != "" { if strings.Contains(addr, ",") { log.Fatalf("This TLS zk code requires that the all the zk servers validate to a single server name.") } serverName := strings.Split(addr, ":")[0] log.Infof("Using TLS ZK, connecting to %v server name %v", addr, serverName) cert, err := tls.LoadX509KeyPair(*certPath, *keyPath) if err != nil { log.Fatalf("Unable to load cert %v and key %v, err %v", *certPath, *keyPath, err) } clientCACert, err := ioutil.ReadFile(*caPath) if err != nil { log.Fatalf("Unable to open ca cert %v, err %v", *caPath, err) } clientCertPool := x509.NewCertPool() clientCertPool.AppendCertsFromPEM(clientCACert) tlsConfig := &tls.Config{ Certificates: []tls.Certificate{cert}, RootCAs: clientCertPool, ServerName: serverName, } tlsConfig.BuildNameToCertificate() options = zk.WithDialer(func(network, address string, timeout time.Duration) (net.Conn, error) { d := net.Dialer{Timeout: timeout} return tls.DialWithDialer(&d, network, address, tlsConfig) }) } // zk.Connect automatically shuffles the servers zconn, session, err := zk.Connect(servers, *baseTimeout, options) if err != nil { return nil, nil, err } // Wait for connection, skipping transition states. for { select { case <-ctx.Done(): zconn.Close() return nil, nil, ctx.Err() case event := <-session: switch event.State { case zk.StateConnected: // success return zconn, session, nil case zk.StateAuthFailed: // fast fail this one zconn.Close() return nil, nil, fmt.Errorf("zk connect failed: StateAuthFailed") } } } }
[ "func", "dialZk", "(", "ctx", "context", ".", "Context", ",", "addr", "string", ")", "(", "*", "zk", ".", "Conn", ",", "<-", "chan", "zk", ".", "Event", ",", "error", ")", "{", "servers", ":=", "strings", ".", "Split", "(", "addr", ",", "\"", "\"", ")", "\n", "options", ":=", "zk", ".", "WithDialer", "(", "net", ".", "DialTimeout", ")", "\n", "// If TLS is enabled use a TLS enabled dialer option", "if", "*", "certPath", "!=", "\"", "\"", "&&", "*", "keyPath", "!=", "\"", "\"", "{", "if", "strings", ".", "Contains", "(", "addr", ",", "\"", "\"", ")", "{", "log", ".", "Fatalf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "serverName", ":=", "strings", ".", "Split", "(", "addr", ",", "\"", "\"", ")", "[", "0", "]", "\n\n", "log", ".", "Infof", "(", "\"", "\"", ",", "addr", ",", "serverName", ")", "\n", "cert", ",", "err", ":=", "tls", ".", "LoadX509KeyPair", "(", "*", "certPath", ",", "*", "keyPath", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "*", "certPath", ",", "*", "keyPath", ",", "err", ")", "\n", "}", "\n\n", "clientCACert", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "*", "caPath", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "*", "caPath", ",", "err", ")", "\n", "}", "\n\n", "clientCertPool", ":=", "x509", ".", "NewCertPool", "(", ")", "\n", "clientCertPool", ".", "AppendCertsFromPEM", "(", "clientCACert", ")", "\n\n", "tlsConfig", ":=", "&", "tls", ".", "Config", "{", "Certificates", ":", "[", "]", "tls", ".", "Certificate", "{", "cert", "}", ",", "RootCAs", ":", "clientCertPool", ",", "ServerName", ":", "serverName", ",", "}", "\n\n", "tlsConfig", ".", "BuildNameToCertificate", "(", ")", "\n\n", "options", "=", "zk", ".", "WithDialer", "(", "func", "(", "network", ",", "address", "string", ",", "timeout", "time", ".", "Duration", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "d", ":=", "net", ".", "Dialer", "{", "Timeout", ":", "timeout", "}", "\n\n", "return", "tls", ".", "DialWithDialer", "(", "&", "d", ",", "network", ",", "address", ",", "tlsConfig", ")", "\n", "}", ")", "\n", "}", "\n\n", "// zk.Connect automatically shuffles the servers", "zconn", ",", "session", ",", "err", ":=", "zk", ".", "Connect", "(", "servers", ",", "*", "baseTimeout", ",", "options", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "// Wait for connection, skipping transition states.", "for", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "zconn", ".", "Close", "(", ")", "\n", "return", "nil", ",", "nil", ",", "ctx", ".", "Err", "(", ")", "\n", "case", "event", ":=", "<-", "session", ":", "switch", "event", ".", "State", "{", "case", "zk", ".", "StateConnected", ":", "// success", "return", "zconn", ",", "session", ",", "nil", "\n\n", "case", "zk", ".", "StateAuthFailed", ":", "// fast fail this one", "zconn", ".", "Close", "(", ")", "\n", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// dialZk dials the server, and waits until connection.
[ "dialZk", "dials", "the", "server", "and", "waits", "until", "connection", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/zk2topo/zk_conn.go#L341-L406
train
vitessio/vitess
go/vt/vtgate/planbuilder/delete.go
buildDeletePlan
func buildDeletePlan(del *sqlparser.Delete, vschema ContextVSchema) (*engine.Delete, error) { edel := &engine.Delete{} pb := newPrimitiveBuilder(vschema, newJointab(sqlparser.GetBindvars(del))) ro, err := pb.processDMLTable(del.TableExprs) if err != nil { return nil, err } edel.Query = generateQuery(del) edel.Keyspace = ro.eroute.Keyspace if !edel.Keyspace.Sharded { // We only validate non-table subexpressions because the previous analysis has already validated them. if !pb.finalizeUnshardedDMLSubqueries(del.Targets, del.Where, del.OrderBy, del.Limit) { return nil, errors.New("unsupported: sharded subqueries in DML") } edel.Opcode = engine.DeleteUnsharded // Generate query after all the analysis. Otherwise table name substitutions for // routed tables won't happen. edel.Query = generateQuery(del) return edel, nil } if del.Targets != nil || ro.vschemaTable == nil { return nil, errors.New("unsupported: multi-table delete statement in sharded keyspace") } if hasSubquery(del) { return nil, errors.New("unsupported: subqueries in sharded DML") } edel.Table = ro.vschemaTable // Generate query after all the analysis. Otherwise table name substitutions for // routed tables won't happen. edel.Query = generateQuery(del) directives := sqlparser.ExtractCommentDirectives(del.Comments) if directives.IsSet(sqlparser.DirectiveMultiShardAutocommit) { edel.MultiShardAutocommit = true } edel.QueryTimeout = queryTimeout(directives) if ro.eroute.TargetDestination != nil { if ro.eroute.TargetTabletType != topodatapb.TabletType_MASTER { return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unsupported: DELETE statement with a replica target") } edel.Opcode = engine.DeleteByDestination edel.TargetDestination = ro.eroute.TargetDestination return edel, nil } edel.Vindex, edel.Values, err = getDMLRouting(del.Where, edel.Table) // We couldn't generate a route for a single shard // Execute a delete sharded if err != nil { edel.Opcode = engine.DeleteScatter } else { edel.Opcode = engine.DeleteEqual } if edel.Opcode == engine.DeleteScatter { if len(edel.Table.Owned) != 0 { return edel, errors.New("unsupported: multi shard delete on a table with owned lookup vindexes") } if del.Limit != nil { return edel, errors.New("unsupported: multi shard delete with limit") } } edel.OwnedVindexQuery = generateDeleteSubquery(del, edel.Table) return edel, nil }
go
func buildDeletePlan(del *sqlparser.Delete, vschema ContextVSchema) (*engine.Delete, error) { edel := &engine.Delete{} pb := newPrimitiveBuilder(vschema, newJointab(sqlparser.GetBindvars(del))) ro, err := pb.processDMLTable(del.TableExprs) if err != nil { return nil, err } edel.Query = generateQuery(del) edel.Keyspace = ro.eroute.Keyspace if !edel.Keyspace.Sharded { // We only validate non-table subexpressions because the previous analysis has already validated them. if !pb.finalizeUnshardedDMLSubqueries(del.Targets, del.Where, del.OrderBy, del.Limit) { return nil, errors.New("unsupported: sharded subqueries in DML") } edel.Opcode = engine.DeleteUnsharded // Generate query after all the analysis. Otherwise table name substitutions for // routed tables won't happen. edel.Query = generateQuery(del) return edel, nil } if del.Targets != nil || ro.vschemaTable == nil { return nil, errors.New("unsupported: multi-table delete statement in sharded keyspace") } if hasSubquery(del) { return nil, errors.New("unsupported: subqueries in sharded DML") } edel.Table = ro.vschemaTable // Generate query after all the analysis. Otherwise table name substitutions for // routed tables won't happen. edel.Query = generateQuery(del) directives := sqlparser.ExtractCommentDirectives(del.Comments) if directives.IsSet(sqlparser.DirectiveMultiShardAutocommit) { edel.MultiShardAutocommit = true } edel.QueryTimeout = queryTimeout(directives) if ro.eroute.TargetDestination != nil { if ro.eroute.TargetTabletType != topodatapb.TabletType_MASTER { return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "unsupported: DELETE statement with a replica target") } edel.Opcode = engine.DeleteByDestination edel.TargetDestination = ro.eroute.TargetDestination return edel, nil } edel.Vindex, edel.Values, err = getDMLRouting(del.Where, edel.Table) // We couldn't generate a route for a single shard // Execute a delete sharded if err != nil { edel.Opcode = engine.DeleteScatter } else { edel.Opcode = engine.DeleteEqual } if edel.Opcode == engine.DeleteScatter { if len(edel.Table.Owned) != 0 { return edel, errors.New("unsupported: multi shard delete on a table with owned lookup vindexes") } if del.Limit != nil { return edel, errors.New("unsupported: multi shard delete with limit") } } edel.OwnedVindexQuery = generateDeleteSubquery(del, edel.Table) return edel, nil }
[ "func", "buildDeletePlan", "(", "del", "*", "sqlparser", ".", "Delete", ",", "vschema", "ContextVSchema", ")", "(", "*", "engine", ".", "Delete", ",", "error", ")", "{", "edel", ":=", "&", "engine", ".", "Delete", "{", "}", "\n", "pb", ":=", "newPrimitiveBuilder", "(", "vschema", ",", "newJointab", "(", "sqlparser", ".", "GetBindvars", "(", "del", ")", ")", ")", "\n", "ro", ",", "err", ":=", "pb", ".", "processDMLTable", "(", "del", ".", "TableExprs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "edel", ".", "Query", "=", "generateQuery", "(", "del", ")", "\n", "edel", ".", "Keyspace", "=", "ro", ".", "eroute", ".", "Keyspace", "\n", "if", "!", "edel", ".", "Keyspace", ".", "Sharded", "{", "// We only validate non-table subexpressions because the previous analysis has already validated them.", "if", "!", "pb", ".", "finalizeUnshardedDMLSubqueries", "(", "del", ".", "Targets", ",", "del", ".", "Where", ",", "del", ".", "OrderBy", ",", "del", ".", "Limit", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "edel", ".", "Opcode", "=", "engine", ".", "DeleteUnsharded", "\n", "// Generate query after all the analysis. Otherwise table name substitutions for", "// routed tables won't happen.", "edel", ".", "Query", "=", "generateQuery", "(", "del", ")", "\n", "return", "edel", ",", "nil", "\n", "}", "\n", "if", "del", ".", "Targets", "!=", "nil", "||", "ro", ".", "vschemaTable", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "hasSubquery", "(", "del", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "edel", ".", "Table", "=", "ro", ".", "vschemaTable", "\n", "// Generate query after all the analysis. Otherwise table name substitutions for", "// routed tables won't happen.", "edel", ".", "Query", "=", "generateQuery", "(", "del", ")", "\n\n", "directives", ":=", "sqlparser", ".", "ExtractCommentDirectives", "(", "del", ".", "Comments", ")", "\n", "if", "directives", ".", "IsSet", "(", "sqlparser", ".", "DirectiveMultiShardAutocommit", ")", "{", "edel", ".", "MultiShardAutocommit", "=", "true", "\n", "}", "\n\n", "edel", ".", "QueryTimeout", "=", "queryTimeout", "(", "directives", ")", "\n", "if", "ro", ".", "eroute", ".", "TargetDestination", "!=", "nil", "{", "if", "ro", ".", "eroute", ".", "TargetTabletType", "!=", "topodatapb", ".", "TabletType_MASTER", "{", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", ")", "\n", "}", "\n", "edel", ".", "Opcode", "=", "engine", ".", "DeleteByDestination", "\n", "edel", ".", "TargetDestination", "=", "ro", ".", "eroute", ".", "TargetDestination", "\n", "return", "edel", ",", "nil", "\n", "}", "\n", "edel", ".", "Vindex", ",", "edel", ".", "Values", ",", "err", "=", "getDMLRouting", "(", "del", ".", "Where", ",", "edel", ".", "Table", ")", "\n", "// We couldn't generate a route for a single shard", "// Execute a delete sharded", "if", "err", "!=", "nil", "{", "edel", ".", "Opcode", "=", "engine", ".", "DeleteScatter", "\n", "}", "else", "{", "edel", ".", "Opcode", "=", "engine", ".", "DeleteEqual", "\n", "}", "\n\n", "if", "edel", ".", "Opcode", "==", "engine", ".", "DeleteScatter", "{", "if", "len", "(", "edel", ".", "Table", ".", "Owned", ")", "!=", "0", "{", "return", "edel", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "del", ".", "Limit", "!=", "nil", "{", "return", "edel", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "edel", ".", "OwnedVindexQuery", "=", "generateDeleteSubquery", "(", "del", ",", "edel", ".", "Table", ")", "\n", "return", "edel", ",", "nil", "\n", "}" ]
// buildDeletePlan builds the instructions for a DELETE statement.
[ "buildDeletePlan", "builds", "the", "instructions", "for", "a", "DELETE", "statement", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/delete.go#L32-L97
train
vitessio/vitess
go/vt/vtgate/planbuilder/delete.go
generateDeleteSubquery
func generateDeleteSubquery(del *sqlparser.Delete, table *vindexes.Table) string { if len(table.Owned) == 0 { return "" } buf := sqlparser.NewTrackedBuffer(nil) buf.WriteString("select ") for vIdx, cv := range table.Owned { for cIdx, column := range cv.Columns { if cIdx == 0 && vIdx == 0 { buf.Myprintf("%v", column) } else { buf.Myprintf(", %v", column) } } } buf.Myprintf(" from %v%v for update", table.Name, del.Where) return buf.String() }
go
func generateDeleteSubquery(del *sqlparser.Delete, table *vindexes.Table) string { if len(table.Owned) == 0 { return "" } buf := sqlparser.NewTrackedBuffer(nil) buf.WriteString("select ") for vIdx, cv := range table.Owned { for cIdx, column := range cv.Columns { if cIdx == 0 && vIdx == 0 { buf.Myprintf("%v", column) } else { buf.Myprintf(", %v", column) } } } buf.Myprintf(" from %v%v for update", table.Name, del.Where) return buf.String() }
[ "func", "generateDeleteSubquery", "(", "del", "*", "sqlparser", ".", "Delete", ",", "table", "*", "vindexes", ".", "Table", ")", "string", "{", "if", "len", "(", "table", ".", "Owned", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n", "buf", ":=", "sqlparser", ".", "NewTrackedBuffer", "(", "nil", ")", "\n", "buf", ".", "WriteString", "(", "\"", "\"", ")", "\n", "for", "vIdx", ",", "cv", ":=", "range", "table", ".", "Owned", "{", "for", "cIdx", ",", "column", ":=", "range", "cv", ".", "Columns", "{", "if", "cIdx", "==", "0", "&&", "vIdx", "==", "0", "{", "buf", ".", "Myprintf", "(", "\"", "\"", ",", "column", ")", "\n", "}", "else", "{", "buf", ".", "Myprintf", "(", "\"", "\"", ",", "column", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "buf", ".", "Myprintf", "(", "\"", "\"", ",", "table", ".", "Name", ",", "del", ".", "Where", ")", "\n", "return", "buf", ".", "String", "(", ")", "\n", "}" ]
// generateDeleteSubquery generates the query to fetch the rows // that will be deleted. This allows VTGate to clean up any // owned vindexes as needed.
[ "generateDeleteSubquery", "generates", "the", "query", "to", "fetch", "the", "rows", "that", "will", "be", "deleted", ".", "This", "allows", "VTGate", "to", "clean", "up", "any", "owned", "vindexes", "as", "needed", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/delete.go#L102-L119
train
vitessio/vitess
go/vt/vterrors/stack.go
file
func (f Frame) file() string { fn := runtime.FuncForPC(f.pc()) if fn == nil { return "unknown" } file, _ := fn.FileLine(f.pc()) return file }
go
func (f Frame) file() string { fn := runtime.FuncForPC(f.pc()) if fn == nil { return "unknown" } file, _ := fn.FileLine(f.pc()) return file }
[ "func", "(", "f", "Frame", ")", "file", "(", ")", "string", "{", "fn", ":=", "runtime", ".", "FuncForPC", "(", "f", ".", "pc", "(", ")", ")", "\n", "if", "fn", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "file", ",", "_", ":=", "fn", ".", "FileLine", "(", "f", ".", "pc", "(", ")", ")", "\n", "return", "file", "\n", "}" ]
// file returns the full path to the file that contains the // function for this Frame's pc.
[ "file", "returns", "the", "full", "path", "to", "the", "file", "that", "contains", "the", "function", "for", "this", "Frame", "s", "pc", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vterrors/stack.go#L22-L29
train
vitessio/vitess
go/vt/vterrors/stack.go
line
func (f Frame) line() int { fn := runtime.FuncForPC(f.pc()) if fn == nil { return 0 } _, line := fn.FileLine(f.pc()) return line }
go
func (f Frame) line() int { fn := runtime.FuncForPC(f.pc()) if fn == nil { return 0 } _, line := fn.FileLine(f.pc()) return line }
[ "func", "(", "f", "Frame", ")", "line", "(", ")", "int", "{", "fn", ":=", "runtime", ".", "FuncForPC", "(", "f", ".", "pc", "(", ")", ")", "\n", "if", "fn", "==", "nil", "{", "return", "0", "\n", "}", "\n", "_", ",", "line", ":=", "fn", ".", "FileLine", "(", "f", ".", "pc", "(", ")", ")", "\n", "return", "line", "\n", "}" ]
// line returns the line number of source code of the // function for this Frame's pc.
[ "line", "returns", "the", "line", "number", "of", "source", "code", "of", "the", "function", "for", "this", "Frame", "s", "pc", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vterrors/stack.go#L33-L40
train
vitessio/vitess
go/vt/vttablet/tabletserver/splitquery/equal_splits_algorithm.go
NewEqualSplitsAlgorithm
func NewEqualSplitsAlgorithm(splitParams *SplitParams, sqlExecuter SQLExecuter) ( *EqualSplitsAlgorithm, error) { if len(splitParams.splitColumns) == 0 { panic(fmt.Sprintf("len(splitParams.splitColumns) == 0." + " SplitParams should have defaulted the split columns to the primary key columns.")) } // This algorithm only uses the first splitColumn. // Note that we do not force the user to specify only one split column, since a common // use-case is not to specify split columns at all, which will make them default to the table // primary key columns, and there can be more than one primary key column for a table. if !sqltypes.IsFloat(splitParams.splitColumns[0].Type) && !sqltypes.IsIntegral(splitParams.splitColumns[0].Type) { return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "using the EQUAL_SPLITS algorithm in SplitQuery requires having"+ " a numeric (integral or float) split-column. Got type: %v", splitParams.splitColumns[0]) } if splitParams.splitCount <= 0 { return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "using the EQUAL_SPLITS algorithm in SplitQuery requires a positive"+ " splitParams.splitCount. Got: %v", splitParams.splitCount) } result := &EqualSplitsAlgorithm{ splitParams: splitParams, sqlExecuter: sqlExecuter, minMaxQuery: buildMinMaxQuery(splitParams), } return result, nil }
go
func NewEqualSplitsAlgorithm(splitParams *SplitParams, sqlExecuter SQLExecuter) ( *EqualSplitsAlgorithm, error) { if len(splitParams.splitColumns) == 0 { panic(fmt.Sprintf("len(splitParams.splitColumns) == 0." + " SplitParams should have defaulted the split columns to the primary key columns.")) } // This algorithm only uses the first splitColumn. // Note that we do not force the user to specify only one split column, since a common // use-case is not to specify split columns at all, which will make them default to the table // primary key columns, and there can be more than one primary key column for a table. if !sqltypes.IsFloat(splitParams.splitColumns[0].Type) && !sqltypes.IsIntegral(splitParams.splitColumns[0].Type) { return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "using the EQUAL_SPLITS algorithm in SplitQuery requires having"+ " a numeric (integral or float) split-column. Got type: %v", splitParams.splitColumns[0]) } if splitParams.splitCount <= 0 { return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "using the EQUAL_SPLITS algorithm in SplitQuery requires a positive"+ " splitParams.splitCount. Got: %v", splitParams.splitCount) } result := &EqualSplitsAlgorithm{ splitParams: splitParams, sqlExecuter: sqlExecuter, minMaxQuery: buildMinMaxQuery(splitParams), } return result, nil }
[ "func", "NewEqualSplitsAlgorithm", "(", "splitParams", "*", "SplitParams", ",", "sqlExecuter", "SQLExecuter", ")", "(", "*", "EqualSplitsAlgorithm", ",", "error", ")", "{", "if", "len", "(", "splitParams", ".", "splitColumns", ")", "==", "0", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "\"", "\"", ")", ")", "\n", "}", "\n", "// This algorithm only uses the first splitColumn.", "// Note that we do not force the user to specify only one split column, since a common", "// use-case is not to specify split columns at all, which will make them default to the table", "// primary key columns, and there can be more than one primary key column for a table.", "if", "!", "sqltypes", ".", "IsFloat", "(", "splitParams", ".", "splitColumns", "[", "0", "]", ".", "Type", ")", "&&", "!", "sqltypes", ".", "IsIntegral", "(", "splitParams", ".", "splitColumns", "[", "0", "]", ".", "Type", ")", "{", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", "+", "\"", "\"", ",", "splitParams", ".", "splitColumns", "[", "0", "]", ")", "\n", "}", "\n", "if", "splitParams", ".", "splitCount", "<=", "0", "{", "return", "nil", ",", "vterrors", ".", "Errorf", "(", "vtrpcpb", ".", "Code_INVALID_ARGUMENT", ",", "\"", "\"", "+", "\"", "\"", ",", "splitParams", ".", "splitCount", ")", "\n", "}", "\n", "result", ":=", "&", "EqualSplitsAlgorithm", "{", "splitParams", ":", "splitParams", ",", "sqlExecuter", ":", "sqlExecuter", ",", "minMaxQuery", ":", "buildMinMaxQuery", "(", "splitParams", ")", ",", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// NewEqualSplitsAlgorithm constructs a new equal splits algorithm. // It requires an SQLExecuter since it needs to execute a query to figure out the // minimum and maximum elements in the table.
[ "NewEqualSplitsAlgorithm", "constructs", "a", "new", "equal", "splits", "algorithm", ".", "It", "requires", "an", "SQLExecuter", "since", "it", "needs", "to", "execute", "a", "query", "to", "figure", "out", "the", "minimum", "and", "maximum", "elements", "in", "the", "table", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/splitquery/equal_splits_algorithm.go#L58-L87
train
vitessio/vitess
go/vt/vttablet/tabletserver/splitquery/equal_splits_algorithm.go
bigIntToSliceOfBytes
func bigIntToSliceOfBytes(bigInt *big.Int) []byte { // Go1.6 introduced the method bigInt.Append() which makes this conversion // a lot easier. // TODO(erez): Use bigInt.Append() once we switch to GO-1.6. result := strconv.AppendQuoteToASCII([]byte{}, bigInt.String()) // AppendQuoteToASCII adds a double-quoted string. We need to remove them. return result[1 : len(result)-1] }
go
func bigIntToSliceOfBytes(bigInt *big.Int) []byte { // Go1.6 introduced the method bigInt.Append() which makes this conversion // a lot easier. // TODO(erez): Use bigInt.Append() once we switch to GO-1.6. result := strconv.AppendQuoteToASCII([]byte{}, bigInt.String()) // AppendQuoteToASCII adds a double-quoted string. We need to remove them. return result[1 : len(result)-1] }
[ "func", "bigIntToSliceOfBytes", "(", "bigInt", "*", "big", ".", "Int", ")", "[", "]", "byte", "{", "// Go1.6 introduced the method bigInt.Append() which makes this conversion", "// a lot easier.", "// TODO(erez): Use bigInt.Append() once we switch to GO-1.6.", "result", ":=", "strconv", ".", "AppendQuoteToASCII", "(", "[", "]", "byte", "{", "}", ",", "bigInt", ".", "String", "(", ")", ")", "\n", "// AppendQuoteToASCII adds a double-quoted string. We need to remove them.", "return", "result", "[", "1", ":", "len", "(", "result", ")", "-", "1", "]", "\n", "}" ]
// Converts a big.Int into a slice of bytes.
[ "Converts", "a", "big", ".", "Int", "into", "a", "slice", "of", "bytes", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/splitquery/equal_splits_algorithm.go#L229-L236
train
vitessio/vitess
go/vt/worker/interactive.go
InitInteractiveMode
func (wi *Instance) InitInteractiveMode() { indexTemplate := mustParseTemplate("index", indexHTML) subIndexTemplate := mustParseTemplate("subIndex", subIndexHTML) // toplevel menu http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { if err := acl.CheckAccessHTTP(r, acl.ADMIN); err != nil { acl.SendError(w, err) return } executeTemplate(w, indexTemplate, commands) }) // command group menus for _, cg := range commands { // keep a local copy of the Command pointer for the // closure. pcg := cg http.HandleFunc("/"+cg.Name, func(w http.ResponseWriter, r *http.Request) { if err := acl.CheckAccessHTTP(r, acl.ADMIN); err != nil { acl.SendError(w, err) return } executeTemplate(w, subIndexTemplate, pcg) }) for _, c := range cg.Commands { // keep a local copy of the Command pointer for the closure. pc := c http.HandleFunc("/"+cg.Name+"/"+c.Name, func(w http.ResponseWriter, r *http.Request) { if err := acl.CheckAccessHTTP(r, acl.ADMIN); err != nil { acl.SendError(w, err) return } wrk, template, data, err := pc.Interactive(context.Background(), wi, wi.wr, w, r) if err != nil { httpError(w, "%s", err) } else if template != nil && data != nil { executeTemplate(w, template, data) return } if wrk == nil { httpError(w, "Internal server error. Command: %s did not return correct response.", c.Name) return } if _, err := wi.setAndStartWorker(context.Background(), wrk, wi.wr); err != nil { httpError(w, "Could not set %s worker: %s", c.Name, err) return } http.Redirect(w, r, servenv.StatusURLPath(), http.StatusTemporaryRedirect) }) } } log.Infof("Interactive mode ready") }
go
func (wi *Instance) InitInteractiveMode() { indexTemplate := mustParseTemplate("index", indexHTML) subIndexTemplate := mustParseTemplate("subIndex", subIndexHTML) // toplevel menu http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { if err := acl.CheckAccessHTTP(r, acl.ADMIN); err != nil { acl.SendError(w, err) return } executeTemplate(w, indexTemplate, commands) }) // command group menus for _, cg := range commands { // keep a local copy of the Command pointer for the // closure. pcg := cg http.HandleFunc("/"+cg.Name, func(w http.ResponseWriter, r *http.Request) { if err := acl.CheckAccessHTTP(r, acl.ADMIN); err != nil { acl.SendError(w, err) return } executeTemplate(w, subIndexTemplate, pcg) }) for _, c := range cg.Commands { // keep a local copy of the Command pointer for the closure. pc := c http.HandleFunc("/"+cg.Name+"/"+c.Name, func(w http.ResponseWriter, r *http.Request) { if err := acl.CheckAccessHTTP(r, acl.ADMIN); err != nil { acl.SendError(w, err) return } wrk, template, data, err := pc.Interactive(context.Background(), wi, wi.wr, w, r) if err != nil { httpError(w, "%s", err) } else if template != nil && data != nil { executeTemplate(w, template, data) return } if wrk == nil { httpError(w, "Internal server error. Command: %s did not return correct response.", c.Name) return } if _, err := wi.setAndStartWorker(context.Background(), wrk, wi.wr); err != nil { httpError(w, "Could not set %s worker: %s", c.Name, err) return } http.Redirect(w, r, servenv.StatusURLPath(), http.StatusTemporaryRedirect) }) } } log.Infof("Interactive mode ready") }
[ "func", "(", "wi", "*", "Instance", ")", "InitInteractiveMode", "(", ")", "{", "indexTemplate", ":=", "mustParseTemplate", "(", "\"", "\"", ",", "indexHTML", ")", "\n", "subIndexTemplate", ":=", "mustParseTemplate", "(", "\"", "\"", ",", "subIndexHTML", ")", "\n\n", "// toplevel menu", "http", ".", "HandleFunc", "(", "\"", "\"", ",", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "err", ":=", "acl", ".", "CheckAccessHTTP", "(", "r", ",", "acl", ".", "ADMIN", ")", ";", "err", "!=", "nil", "{", "acl", ".", "SendError", "(", "w", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "executeTemplate", "(", "w", ",", "indexTemplate", ",", "commands", ")", "\n", "}", ")", "\n\n", "// command group menus", "for", "_", ",", "cg", ":=", "range", "commands", "{", "// keep a local copy of the Command pointer for the", "// closure.", "pcg", ":=", "cg", "\n", "http", ".", "HandleFunc", "(", "\"", "\"", "+", "cg", ".", "Name", ",", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "err", ":=", "acl", ".", "CheckAccessHTTP", "(", "r", ",", "acl", ".", "ADMIN", ")", ";", "err", "!=", "nil", "{", "acl", ".", "SendError", "(", "w", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "executeTemplate", "(", "w", ",", "subIndexTemplate", ",", "pcg", ")", "\n", "}", ")", "\n\n", "for", "_", ",", "c", ":=", "range", "cg", ".", "Commands", "{", "// keep a local copy of the Command pointer for the closure.", "pc", ":=", "c", "\n", "http", ".", "HandleFunc", "(", "\"", "\"", "+", "cg", ".", "Name", "+", "\"", "\"", "+", "c", ".", "Name", ",", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "err", ":=", "acl", ".", "CheckAccessHTTP", "(", "r", ",", "acl", ".", "ADMIN", ")", ";", "err", "!=", "nil", "{", "acl", ".", "SendError", "(", "w", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "wrk", ",", "template", ",", "data", ",", "err", ":=", "pc", ".", "Interactive", "(", "context", ".", "Background", "(", ")", ",", "wi", ",", "wi", ".", "wr", ",", "w", ",", "r", ")", "\n", "if", "err", "!=", "nil", "{", "httpError", "(", "w", ",", "\"", "\"", ",", "err", ")", "\n", "}", "else", "if", "template", "!=", "nil", "&&", "data", "!=", "nil", "{", "executeTemplate", "(", "w", ",", "template", ",", "data", ")", "\n", "return", "\n", "}", "\n\n", "if", "wrk", "==", "nil", "{", "httpError", "(", "w", ",", "\"", "\"", ",", "c", ".", "Name", ")", "\n", "return", "\n", "}", "\n\n", "if", "_", ",", "err", ":=", "wi", ".", "setAndStartWorker", "(", "context", ".", "Background", "(", ")", ",", "wrk", ",", "wi", ".", "wr", ")", ";", "err", "!=", "nil", "{", "httpError", "(", "w", ",", "\"", "\"", ",", "c", ".", "Name", ",", "err", ")", "\n", "return", "\n", "}", "\n", "http", ".", "Redirect", "(", "w", ",", "r", ",", "servenv", ".", "StatusURLPath", "(", ")", ",", "http", ".", "StatusTemporaryRedirect", ")", "\n", "}", ")", "\n", "}", "\n", "}", "\n\n", "log", ".", "Infof", "(", "\"", "\"", ")", "\n", "}" ]
// InitInteractiveMode installs webserver handlers for each known command.
[ "InitInteractiveMode", "installs", "webserver", "handlers", "for", "each", "known", "command", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/interactive.go#L80-L140
train
vitessio/vitess
go/mysql/schema.go
ShowIndexFromTableRow
func ShowIndexFromTableRow(table string, unique bool, keyName string, seqInIndex int, columnName string, nullable bool) []sqltypes.Value { nonUnique := "1" if unique { nonUnique = "0" } nullableStr := "" if nullable { nullableStr = "YES" } return []sqltypes.Value{ sqltypes.MakeTrusted(sqltypes.VarChar, []byte(table)), sqltypes.MakeTrusted(sqltypes.Int64, []byte(nonUnique)), sqltypes.MakeTrusted(sqltypes.VarChar, []byte(keyName)), sqltypes.MakeTrusted(sqltypes.Int64, []byte(fmt.Sprintf("%v", seqInIndex))), sqltypes.MakeTrusted(sqltypes.VarChar, []byte(columnName)), sqltypes.MakeTrusted(sqltypes.VarChar, []byte("A")), // Collation sqltypes.MakeTrusted(sqltypes.Int64, []byte("0")), // Cardinality sqltypes.NULL, // Sub_part sqltypes.NULL, // Packed sqltypes.MakeTrusted(sqltypes.VarChar, []byte(nullableStr)), sqltypes.MakeTrusted(sqltypes.VarChar, []byte("BTREE")), // Index_type sqltypes.MakeTrusted(sqltypes.VarChar, []byte("")), // Comment sqltypes.MakeTrusted(sqltypes.VarChar, []byte("")), // Index_comment } }
go
func ShowIndexFromTableRow(table string, unique bool, keyName string, seqInIndex int, columnName string, nullable bool) []sqltypes.Value { nonUnique := "1" if unique { nonUnique = "0" } nullableStr := "" if nullable { nullableStr = "YES" } return []sqltypes.Value{ sqltypes.MakeTrusted(sqltypes.VarChar, []byte(table)), sqltypes.MakeTrusted(sqltypes.Int64, []byte(nonUnique)), sqltypes.MakeTrusted(sqltypes.VarChar, []byte(keyName)), sqltypes.MakeTrusted(sqltypes.Int64, []byte(fmt.Sprintf("%v", seqInIndex))), sqltypes.MakeTrusted(sqltypes.VarChar, []byte(columnName)), sqltypes.MakeTrusted(sqltypes.VarChar, []byte("A")), // Collation sqltypes.MakeTrusted(sqltypes.Int64, []byte("0")), // Cardinality sqltypes.NULL, // Sub_part sqltypes.NULL, // Packed sqltypes.MakeTrusted(sqltypes.VarChar, []byte(nullableStr)), sqltypes.MakeTrusted(sqltypes.VarChar, []byte("BTREE")), // Index_type sqltypes.MakeTrusted(sqltypes.VarChar, []byte("")), // Comment sqltypes.MakeTrusted(sqltypes.VarChar, []byte("")), // Index_comment } }
[ "func", "ShowIndexFromTableRow", "(", "table", "string", ",", "unique", "bool", ",", "keyName", "string", ",", "seqInIndex", "int", ",", "columnName", "string", ",", "nullable", "bool", ")", "[", "]", "sqltypes", ".", "Value", "{", "nonUnique", ":=", "\"", "\"", "\n", "if", "unique", "{", "nonUnique", "=", "\"", "\"", "\n", "}", "\n", "nullableStr", ":=", "\"", "\"", "\n", "if", "nullable", "{", "nullableStr", "=", "\"", "\"", "\n", "}", "\n", "return", "[", "]", "sqltypes", ".", "Value", "{", "sqltypes", ".", "MakeTrusted", "(", "sqltypes", ".", "VarChar", ",", "[", "]", "byte", "(", "table", ")", ")", ",", "sqltypes", ".", "MakeTrusted", "(", "sqltypes", ".", "Int64", ",", "[", "]", "byte", "(", "nonUnique", ")", ")", ",", "sqltypes", ".", "MakeTrusted", "(", "sqltypes", ".", "VarChar", ",", "[", "]", "byte", "(", "keyName", ")", ")", ",", "sqltypes", ".", "MakeTrusted", "(", "sqltypes", ".", "Int64", ",", "[", "]", "byte", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "seqInIndex", ")", ")", ")", ",", "sqltypes", ".", "MakeTrusted", "(", "sqltypes", ".", "VarChar", ",", "[", "]", "byte", "(", "columnName", ")", ")", ",", "sqltypes", ".", "MakeTrusted", "(", "sqltypes", ".", "VarChar", ",", "[", "]", "byte", "(", "\"", "\"", ")", ")", ",", "// Collation", "sqltypes", ".", "MakeTrusted", "(", "sqltypes", ".", "Int64", ",", "[", "]", "byte", "(", "\"", "\"", ")", ")", ",", "// Cardinality", "sqltypes", ".", "NULL", ",", "// Sub_part", "sqltypes", ".", "NULL", ",", "// Packed", "sqltypes", ".", "MakeTrusted", "(", "sqltypes", ".", "VarChar", ",", "[", "]", "byte", "(", "nullableStr", ")", ")", ",", "sqltypes", ".", "MakeTrusted", "(", "sqltypes", ".", "VarChar", ",", "[", "]", "byte", "(", "\"", "\"", ")", ")", ",", "// Index_type", "sqltypes", ".", "MakeTrusted", "(", "sqltypes", ".", "VarChar", ",", "[", "]", "byte", "(", "\"", "\"", ")", ")", ",", "// Comment", "sqltypes", ".", "MakeTrusted", "(", "sqltypes", ".", "VarChar", ",", "[", "]", "byte", "(", "\"", "\"", ")", ")", ",", "// Index_comment", "}", "\n", "}" ]
// ShowIndexFromTableRow returns the fields from a 'show index from table' // command. // 'table' is the table name. // 'unique' is true for unique indexes, false for non-unique indexes. // 'keyName' is 'PRIMARY' for PKs, otherwise the name of the index. // 'seqInIndex' is starting at 1 for first key in index. // 'columnName' is the name of the column this index applies to. // 'nullable' is true if this column can be null.
[ "ShowIndexFromTableRow", "returns", "the", "fields", "from", "a", "show", "index", "from", "table", "command", ".", "table", "is", "the", "table", "name", ".", "unique", "is", "true", "for", "unique", "indexes", "false", "for", "non", "-", "unique", "indexes", ".", "keyName", "is", "PRIMARY", "for", "PKs", "otherwise", "the", "name", "of", "the", "index", ".", "seqInIndex", "is", "starting", "at", "1", "for", "first", "key", "in", "index", ".", "columnName", "is", "the", "name", "of", "the", "column", "this", "index", "applies", "to", ".", "nullable", "is", "true", "if", "this", "column", "can", "be", "null", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/schema.go#L296-L320
train
vitessio/vitess
go/mysql/schema.go
BaseShowTablesRow
func BaseShowTablesRow(tableName string, isView bool, comment string) []sqltypes.Value { tableType := "BASE TABLE" if isView { tableType = "VIEW" } return []sqltypes.Value{ sqltypes.MakeTrusted(sqltypes.VarChar, []byte(tableName)), sqltypes.MakeTrusted(sqltypes.VarChar, []byte(tableType)), sqltypes.MakeTrusted(sqltypes.Int64, []byte("1427325875")), // unix_timestamp(create_time) sqltypes.MakeTrusted(sqltypes.VarChar, []byte(comment)), sqltypes.MakeTrusted(sqltypes.Uint64, []byte("0")), // table_rows sqltypes.MakeTrusted(sqltypes.Uint64, []byte("0")), // data_length sqltypes.MakeTrusted(sqltypes.Uint64, []byte("0")), // index_length sqltypes.MakeTrusted(sqltypes.Uint64, []byte("0")), // data_free sqltypes.MakeTrusted(sqltypes.Uint64, []byte("0")), // max_data_length } }
go
func BaseShowTablesRow(tableName string, isView bool, comment string) []sqltypes.Value { tableType := "BASE TABLE" if isView { tableType = "VIEW" } return []sqltypes.Value{ sqltypes.MakeTrusted(sqltypes.VarChar, []byte(tableName)), sqltypes.MakeTrusted(sqltypes.VarChar, []byte(tableType)), sqltypes.MakeTrusted(sqltypes.Int64, []byte("1427325875")), // unix_timestamp(create_time) sqltypes.MakeTrusted(sqltypes.VarChar, []byte(comment)), sqltypes.MakeTrusted(sqltypes.Uint64, []byte("0")), // table_rows sqltypes.MakeTrusted(sqltypes.Uint64, []byte("0")), // data_length sqltypes.MakeTrusted(sqltypes.Uint64, []byte("0")), // index_length sqltypes.MakeTrusted(sqltypes.Uint64, []byte("0")), // data_free sqltypes.MakeTrusted(sqltypes.Uint64, []byte("0")), // max_data_length } }
[ "func", "BaseShowTablesRow", "(", "tableName", "string", ",", "isView", "bool", ",", "comment", "string", ")", "[", "]", "sqltypes", ".", "Value", "{", "tableType", ":=", "\"", "\"", "\n", "if", "isView", "{", "tableType", "=", "\"", "\"", "\n", "}", "\n", "return", "[", "]", "sqltypes", ".", "Value", "{", "sqltypes", ".", "MakeTrusted", "(", "sqltypes", ".", "VarChar", ",", "[", "]", "byte", "(", "tableName", ")", ")", ",", "sqltypes", ".", "MakeTrusted", "(", "sqltypes", ".", "VarChar", ",", "[", "]", "byte", "(", "tableType", ")", ")", ",", "sqltypes", ".", "MakeTrusted", "(", "sqltypes", ".", "Int64", ",", "[", "]", "byte", "(", "\"", "\"", ")", ")", ",", "// unix_timestamp(create_time)", "sqltypes", ".", "MakeTrusted", "(", "sqltypes", ".", "VarChar", ",", "[", "]", "byte", "(", "comment", ")", ")", ",", "sqltypes", ".", "MakeTrusted", "(", "sqltypes", ".", "Uint64", ",", "[", "]", "byte", "(", "\"", "\"", ")", ")", ",", "// table_rows", "sqltypes", ".", "MakeTrusted", "(", "sqltypes", ".", "Uint64", ",", "[", "]", "byte", "(", "\"", "\"", ")", ")", ",", "// data_length", "sqltypes", ".", "MakeTrusted", "(", "sqltypes", ".", "Uint64", ",", "[", "]", "byte", "(", "\"", "\"", ")", ")", ",", "// index_length", "sqltypes", ".", "MakeTrusted", "(", "sqltypes", ".", "Uint64", ",", "[", "]", "byte", "(", "\"", "\"", ")", ")", ",", "// data_free", "sqltypes", ".", "MakeTrusted", "(", "sqltypes", ".", "Uint64", ",", "[", "]", "byte", "(", "\"", "\"", ")", ")", ",", "// max_data_length", "}", "\n", "}" ]
// BaseShowTablesRow returns the fields from a BaseShowTables or // BaseShowTablesForTable command.
[ "BaseShowTablesRow", "returns", "the", "fields", "from", "a", "BaseShowTables", "or", "BaseShowTablesForTable", "command", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/schema.go#L433-L449
train
vitessio/vitess
go/event/event.go
Dispatch
func Dispatch(ev interface{}) { listenersMutex.RLock() defer listenersMutex.RUnlock() evType := reflect.TypeOf(ev) vals := []reflect.Value{reflect.ValueOf(ev)} // call listeners for the actual static type callListeners(evType, vals) // also check if the type implements any of the registered interfaces for _, in := range interfaces { if evType.Implements(in) { callListeners(in, vals) } } }
go
func Dispatch(ev interface{}) { listenersMutex.RLock() defer listenersMutex.RUnlock() evType := reflect.TypeOf(ev) vals := []reflect.Value{reflect.ValueOf(ev)} // call listeners for the actual static type callListeners(evType, vals) // also check if the type implements any of the registered interfaces for _, in := range interfaces { if evType.Implements(in) { callListeners(in, vals) } } }
[ "func", "Dispatch", "(", "ev", "interface", "{", "}", ")", "{", "listenersMutex", ".", "RLock", "(", ")", "\n", "defer", "listenersMutex", ".", "RUnlock", "(", ")", "\n\n", "evType", ":=", "reflect", ".", "TypeOf", "(", "ev", ")", "\n", "vals", ":=", "[", "]", "reflect", ".", "Value", "{", "reflect", ".", "ValueOf", "(", "ev", ")", "}", "\n\n", "// call listeners for the actual static type", "callListeners", "(", "evType", ",", "vals", ")", "\n\n", "// also check if the type implements any of the registered interfaces", "for", "_", ",", "in", ":=", "range", "interfaces", "{", "if", "evType", ".", "Implements", "(", "in", ")", "{", "callListeners", "(", "in", ",", "vals", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Dispatch sends an event to all registered listeners that were declared // to accept values of the event's type, or interfaces that the value implements.
[ "Dispatch", "sends", "an", "event", "to", "all", "registered", "listeners", "that", "were", "declared", "to", "accept", "values", "of", "the", "event", "s", "type", "or", "interfaces", "that", "the", "value", "implements", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/event/event.go#L132-L148
train
vitessio/vitess
go/vt/vtgate/planbuilder/insert.go
buildInsertPlan
func buildInsertPlan(ins *sqlparser.Insert, vschema ContextVSchema) (*engine.Insert, error) { pb := newPrimitiveBuilder(vschema, newJointab(sqlparser.GetBindvars(ins))) exprs := sqlparser.TableExprs{&sqlparser.AliasedTableExpr{Expr: ins.Table}} ro, err := pb.processDMLTable(exprs) if err != nil { return nil, err } // The table might have been routed to a different one. ins.Table = exprs[0].(*sqlparser.AliasedTableExpr).Expr.(sqlparser.TableName) if ro.eroute.TargetDestination != nil { return nil, errors.New("unsupported: INSERT with a target destination") } if !ro.vschemaTable.Keyspace.Sharded { if !pb.finalizeUnshardedDMLSubqueries(ins) { return nil, errors.New("unsupported: sharded subquery in insert values") } return buildInsertUnshardedPlan(ins, ro.vschemaTable, vschema) } if ins.Action == sqlparser.ReplaceStr { return nil, errors.New("unsupported: REPLACE INTO with sharded schema") } return buildInsertShardedPlan(ins, ro.vschemaTable) }
go
func buildInsertPlan(ins *sqlparser.Insert, vschema ContextVSchema) (*engine.Insert, error) { pb := newPrimitiveBuilder(vschema, newJointab(sqlparser.GetBindvars(ins))) exprs := sqlparser.TableExprs{&sqlparser.AliasedTableExpr{Expr: ins.Table}} ro, err := pb.processDMLTable(exprs) if err != nil { return nil, err } // The table might have been routed to a different one. ins.Table = exprs[0].(*sqlparser.AliasedTableExpr).Expr.(sqlparser.TableName) if ro.eroute.TargetDestination != nil { return nil, errors.New("unsupported: INSERT with a target destination") } if !ro.vschemaTable.Keyspace.Sharded { if !pb.finalizeUnshardedDMLSubqueries(ins) { return nil, errors.New("unsupported: sharded subquery in insert values") } return buildInsertUnshardedPlan(ins, ro.vschemaTable, vschema) } if ins.Action == sqlparser.ReplaceStr { return nil, errors.New("unsupported: REPLACE INTO with sharded schema") } return buildInsertShardedPlan(ins, ro.vschemaTable) }
[ "func", "buildInsertPlan", "(", "ins", "*", "sqlparser", ".", "Insert", ",", "vschema", "ContextVSchema", ")", "(", "*", "engine", ".", "Insert", ",", "error", ")", "{", "pb", ":=", "newPrimitiveBuilder", "(", "vschema", ",", "newJointab", "(", "sqlparser", ".", "GetBindvars", "(", "ins", ")", ")", ")", "\n", "exprs", ":=", "sqlparser", ".", "TableExprs", "{", "&", "sqlparser", ".", "AliasedTableExpr", "{", "Expr", ":", "ins", ".", "Table", "}", "}", "\n", "ro", ",", "err", ":=", "pb", ".", "processDMLTable", "(", "exprs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// The table might have been routed to a different one.", "ins", ".", "Table", "=", "exprs", "[", "0", "]", ".", "(", "*", "sqlparser", ".", "AliasedTableExpr", ")", ".", "Expr", ".", "(", "sqlparser", ".", "TableName", ")", "\n", "if", "ro", ".", "eroute", ".", "TargetDestination", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "!", "ro", ".", "vschemaTable", ".", "Keyspace", ".", "Sharded", "{", "if", "!", "pb", ".", "finalizeUnshardedDMLSubqueries", "(", "ins", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "buildInsertUnshardedPlan", "(", "ins", ",", "ro", ".", "vschemaTable", ",", "vschema", ")", "\n", "}", "\n", "if", "ins", ".", "Action", "==", "sqlparser", ".", "ReplaceStr", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "buildInsertShardedPlan", "(", "ins", ",", "ro", ".", "vschemaTable", ")", "\n", "}" ]
// buildInsertPlan builds the route for an INSERT statement.
[ "buildInsertPlan", "builds", "the", "route", "for", "an", "INSERT", "statement", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/insert.go#L32-L54
train
vitessio/vitess
go/vt/vtgate/planbuilder/insert.go
modifyForAutoinc
func modifyForAutoinc(ins *sqlparser.Insert, eins *engine.Insert) error { pos := findOrAddColumn(ins, eins.Table.AutoIncrement.Column) autoIncValues, err := swapBindVariables(ins.Rows.(sqlparser.Values), pos, ":"+engine.SeqVarName) if err != nil { return err } eins.Generate = &engine.Generate{ Keyspace: eins.Table.AutoIncrement.Sequence.Keyspace, Query: fmt.Sprintf("select next :n values from %s", sqlparser.String(eins.Table.AutoIncrement.Sequence.Name)), Values: autoIncValues, } return nil }
go
func modifyForAutoinc(ins *sqlparser.Insert, eins *engine.Insert) error { pos := findOrAddColumn(ins, eins.Table.AutoIncrement.Column) autoIncValues, err := swapBindVariables(ins.Rows.(sqlparser.Values), pos, ":"+engine.SeqVarName) if err != nil { return err } eins.Generate = &engine.Generate{ Keyspace: eins.Table.AutoIncrement.Sequence.Keyspace, Query: fmt.Sprintf("select next :n values from %s", sqlparser.String(eins.Table.AutoIncrement.Sequence.Name)), Values: autoIncValues, } return nil }
[ "func", "modifyForAutoinc", "(", "ins", "*", "sqlparser", ".", "Insert", ",", "eins", "*", "engine", ".", "Insert", ")", "error", "{", "pos", ":=", "findOrAddColumn", "(", "ins", ",", "eins", ".", "Table", ".", "AutoIncrement", ".", "Column", ")", "\n", "autoIncValues", ",", "err", ":=", "swapBindVariables", "(", "ins", ".", "Rows", ".", "(", "sqlparser", ".", "Values", ")", ",", "pos", ",", "\"", "\"", "+", "engine", ".", "SeqVarName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "eins", ".", "Generate", "=", "&", "engine", ".", "Generate", "{", "Keyspace", ":", "eins", ".", "Table", ".", "AutoIncrement", ".", "Sequence", ".", "Keyspace", ",", "Query", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "sqlparser", ".", "String", "(", "eins", ".", "Table", ".", "AutoIncrement", ".", "Sequence", ".", "Name", ")", ")", ",", "Values", ":", "autoIncValues", ",", "}", "\n", "return", "nil", "\n", "}" ]
// modifyForAutoinc modfies the AST and the plan to generate // necessary autoinc values. It must be called only if eins.Table.AutoIncrement // is set.
[ "modifyForAutoinc", "modfies", "the", "AST", "and", "the", "plan", "to", "generate", "necessary", "autoinc", "values", ".", "It", "must", "be", "called", "only", "if", "eins", ".", "Table", ".", "AutoIncrement", "is", "set", "." ]
d568817542a413611801aa17a1c213aa95592182
https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/insert.go#L192-L204
train