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/trace/opentracing.go | New | func (jf openTracingService) New(parent Span, label string) Span {
var innerSpan opentracing.Span
if parent == nil {
innerSpan = jf.Tracer.StartSpan(label)
} else {
jaegerParent := parent.(openTracingSpan)
span := jaegerParent.otSpan
innerSpan = jf.Tracer.StartSpan(label, opentracing.ChildOf(span.Context()))
}
return openTracingSpan{otSpan: innerSpan}
} | go | func (jf openTracingService) New(parent Span, label string) Span {
var innerSpan opentracing.Span
if parent == nil {
innerSpan = jf.Tracer.StartSpan(label)
} else {
jaegerParent := parent.(openTracingSpan)
span := jaegerParent.otSpan
innerSpan = jf.Tracer.StartSpan(label, opentracing.ChildOf(span.Context()))
}
return openTracingSpan{otSpan: innerSpan}
} | [
"func",
"(",
"jf",
"openTracingService",
")",
"New",
"(",
"parent",
"Span",
",",
"label",
"string",
")",
"Span",
"{",
"var",
"innerSpan",
"opentracing",
".",
"Span",
"\n",
"if",
"parent",
"==",
"nil",
"{",
"innerSpan",
"=",
"jf",
".",
"Tracer",
".",
"StartSpan",
"(",
"label",
")",
"\n",
"}",
"else",
"{",
"jaegerParent",
":=",
"parent",
".",
"(",
"openTracingSpan",
")",
"\n",
"span",
":=",
"jaegerParent",
".",
"otSpan",
"\n",
"innerSpan",
"=",
"jf",
".",
"Tracer",
".",
"StartSpan",
"(",
"label",
",",
"opentracing",
".",
"ChildOf",
"(",
"span",
".",
"Context",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"return",
"openTracingSpan",
"{",
"otSpan",
":",
"innerSpan",
"}",
"\n",
"}"
] | // New is part of an interface implementation | [
"New",
"is",
"part",
"of",
"an",
"interface",
"implementation"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/trace/opentracing.go#L65-L75 | train |
vitessio/vitess | go/trace/opentracing.go | FromContext | func (jf openTracingService) FromContext(ctx context.Context) (Span, bool) {
innerSpan := opentracing.SpanFromContext(ctx)
if innerSpan != nil {
return openTracingSpan{otSpan: innerSpan}, true
} else {
return nil, false
}
} | go | func (jf openTracingService) FromContext(ctx context.Context) (Span, bool) {
innerSpan := opentracing.SpanFromContext(ctx)
if innerSpan != nil {
return openTracingSpan{otSpan: innerSpan}, true
} else {
return nil, false
}
} | [
"func",
"(",
"jf",
"openTracingService",
")",
"FromContext",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"Span",
",",
"bool",
")",
"{",
"innerSpan",
":=",
"opentracing",
".",
"SpanFromContext",
"(",
"ctx",
")",
"\n\n",
"if",
"innerSpan",
"!=",
"nil",
"{",
"return",
"openTracingSpan",
"{",
"otSpan",
":",
"innerSpan",
"}",
",",
"true",
"\n",
"}",
"else",
"{",
"return",
"nil",
",",
"false",
"\n",
"}",
"\n",
"}"
] | // FromContext is part of an interface implementation | [
"FromContext",
"is",
"part",
"of",
"an",
"interface",
"implementation"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/trace/opentracing.go#L78-L86 | train |
vitessio/vitess | go/trace/opentracing.go | NewContext | func (jf openTracingService) NewContext(parent context.Context, s Span) context.Context {
span, ok := s.(openTracingSpan)
if !ok {
return nil
}
return opentracing.ContextWithSpan(parent, span.otSpan)
} | go | func (jf openTracingService) NewContext(parent context.Context, s Span) context.Context {
span, ok := s.(openTracingSpan)
if !ok {
return nil
}
return opentracing.ContextWithSpan(parent, span.otSpan)
} | [
"func",
"(",
"jf",
"openTracingService",
")",
"NewContext",
"(",
"parent",
"context",
".",
"Context",
",",
"s",
"Span",
")",
"context",
".",
"Context",
"{",
"span",
",",
"ok",
":=",
"s",
".",
"(",
"openTracingSpan",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"opentracing",
".",
"ContextWithSpan",
"(",
"parent",
",",
"span",
".",
"otSpan",
")",
"\n",
"}"
] | // NewContext is part of an interface implementation | [
"NewContext",
"is",
"part",
"of",
"an",
"interface",
"implementation"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/trace/opentracing.go#L89-L95 | train |
vitessio/vitess | go/vt/topo/server.go | RegisterFactory | func RegisterFactory(name string, factory Factory) {
if factories[name] != nil {
log.Fatalf("Duplicate topo.Factory registration for %v", name)
}
factories[name] = factory
} | go | func RegisterFactory(name string, factory Factory) {
if factories[name] != nil {
log.Fatalf("Duplicate topo.Factory registration for %v", name)
}
factories[name] = factory
} | [
"func",
"RegisterFactory",
"(",
"name",
"string",
",",
"factory",
"Factory",
")",
"{",
"if",
"factories",
"[",
"name",
"]",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"factories",
"[",
"name",
"]",
"=",
"factory",
"\n",
"}"
] | // RegisterFactory registers a Factory for an implementation for a Server.
// If an implementation with that name already exists, it log.Fatals out.
// Call this in the 'init' function in your topology implementation module. | [
"RegisterFactory",
"registers",
"a",
"Factory",
"for",
"an",
"implementation",
"for",
"a",
"Server",
".",
"If",
"an",
"implementation",
"with",
"that",
"name",
"already",
"exists",
"it",
"log",
".",
"Fatals",
"out",
".",
"Call",
"this",
"in",
"the",
"init",
"function",
"in",
"your",
"topology",
"implementation",
"module",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/server.go#L169-L174 | train |
vitessio/vitess | go/vt/topo/server.go | NewWithFactory | func NewWithFactory(factory Factory, serverAddress, root string) (*Server, error) {
conn, err := factory.Create(GlobalCell, serverAddress, root)
if err != nil {
return nil, err
}
conn = NewStatsConn(GlobalCell, conn)
var connReadOnly Conn
if factory.HasGlobalReadOnlyCell(serverAddress, root) {
connReadOnly, err = factory.Create(GlobalReadOnlyCell, serverAddress, root)
if err != nil {
return nil, err
}
connReadOnly = NewStatsConn(GlobalReadOnlyCell, connReadOnly)
} else {
connReadOnly = conn
}
return &Server{
globalCell: conn,
globalReadOnlyCell: connReadOnly,
factory: factory,
cells: make(map[string]Conn),
}, nil
} | go | func NewWithFactory(factory Factory, serverAddress, root string) (*Server, error) {
conn, err := factory.Create(GlobalCell, serverAddress, root)
if err != nil {
return nil, err
}
conn = NewStatsConn(GlobalCell, conn)
var connReadOnly Conn
if factory.HasGlobalReadOnlyCell(serverAddress, root) {
connReadOnly, err = factory.Create(GlobalReadOnlyCell, serverAddress, root)
if err != nil {
return nil, err
}
connReadOnly = NewStatsConn(GlobalReadOnlyCell, connReadOnly)
} else {
connReadOnly = conn
}
return &Server{
globalCell: conn,
globalReadOnlyCell: connReadOnly,
factory: factory,
cells: make(map[string]Conn),
}, nil
} | [
"func",
"NewWithFactory",
"(",
"factory",
"Factory",
",",
"serverAddress",
",",
"root",
"string",
")",
"(",
"*",
"Server",
",",
"error",
")",
"{",
"conn",
",",
"err",
":=",
"factory",
".",
"Create",
"(",
"GlobalCell",
",",
"serverAddress",
",",
"root",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"conn",
"=",
"NewStatsConn",
"(",
"GlobalCell",
",",
"conn",
")",
"\n\n",
"var",
"connReadOnly",
"Conn",
"\n",
"if",
"factory",
".",
"HasGlobalReadOnlyCell",
"(",
"serverAddress",
",",
"root",
")",
"{",
"connReadOnly",
",",
"err",
"=",
"factory",
".",
"Create",
"(",
"GlobalReadOnlyCell",
",",
"serverAddress",
",",
"root",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"connReadOnly",
"=",
"NewStatsConn",
"(",
"GlobalReadOnlyCell",
",",
"connReadOnly",
")",
"\n",
"}",
"else",
"{",
"connReadOnly",
"=",
"conn",
"\n",
"}",
"\n\n",
"return",
"&",
"Server",
"{",
"globalCell",
":",
"conn",
",",
"globalReadOnlyCell",
":",
"connReadOnly",
",",
"factory",
":",
"factory",
",",
"cells",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"Conn",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewWithFactory creates a new Server based on the given Factory.
// It also opens the global cell connection. | [
"NewWithFactory",
"creates",
"a",
"new",
"Server",
"based",
"on",
"the",
"given",
"Factory",
".",
"It",
"also",
"opens",
"the",
"global",
"cell",
"connection",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/server.go#L178-L202 | train |
vitessio/vitess | go/vt/topo/server.go | OpenServer | func OpenServer(implementation, serverAddress, root string) (*Server, error) {
factory, ok := factories[implementation]
if !ok {
return nil, NewError(NoImplementation, implementation)
}
return NewWithFactory(factory, serverAddress, root)
} | go | func OpenServer(implementation, serverAddress, root string) (*Server, error) {
factory, ok := factories[implementation]
if !ok {
return nil, NewError(NoImplementation, implementation)
}
return NewWithFactory(factory, serverAddress, root)
} | [
"func",
"OpenServer",
"(",
"implementation",
",",
"serverAddress",
",",
"root",
"string",
")",
"(",
"*",
"Server",
",",
"error",
")",
"{",
"factory",
",",
"ok",
":=",
"factories",
"[",
"implementation",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"NewError",
"(",
"NoImplementation",
",",
"implementation",
")",
"\n",
"}",
"\n",
"return",
"NewWithFactory",
"(",
"factory",
",",
"serverAddress",
",",
"root",
")",
"\n",
"}"
] | // OpenServer returns a Server using the provided implementation,
// address and root for the global server. | [
"OpenServer",
"returns",
"a",
"Server",
"using",
"the",
"provided",
"implementation",
"address",
"and",
"root",
"for",
"the",
"global",
"server",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/server.go#L206-L212 | train |
vitessio/vitess | go/vt/topo/server.go | Open | func Open() *Server {
if *topoGlobalServerAddress == "" {
log.Exitf("topo_global_server_address must be configured")
}
ts, err := OpenServer(*topoImplementation, *topoGlobalServerAddress, *topoGlobalRoot)
if err != nil {
log.Exitf("Failed to open topo server (%v,%v,%v): %v", *topoImplementation, *topoGlobalServerAddress, *topoGlobalRoot, err)
}
return ts
} | go | func Open() *Server {
if *topoGlobalServerAddress == "" {
log.Exitf("topo_global_server_address must be configured")
}
ts, err := OpenServer(*topoImplementation, *topoGlobalServerAddress, *topoGlobalRoot)
if err != nil {
log.Exitf("Failed to open topo server (%v,%v,%v): %v", *topoImplementation, *topoGlobalServerAddress, *topoGlobalRoot, err)
}
return ts
} | [
"func",
"Open",
"(",
")",
"*",
"Server",
"{",
"if",
"*",
"topoGlobalServerAddress",
"==",
"\"",
"\"",
"{",
"log",
".",
"Exitf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"ts",
",",
"err",
":=",
"OpenServer",
"(",
"*",
"topoImplementation",
",",
"*",
"topoGlobalServerAddress",
",",
"*",
"topoGlobalRoot",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Exitf",
"(",
"\"",
"\"",
",",
"*",
"topoImplementation",
",",
"*",
"topoGlobalServerAddress",
",",
"*",
"topoGlobalRoot",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"ts",
"\n",
"}"
] | // Open returns a Server using the command line parameter flags
// for implementation, address and root. It log.Exits out if an error occurs. | [
"Open",
"returns",
"a",
"Server",
"using",
"the",
"command",
"line",
"parameter",
"flags",
"for",
"implementation",
"address",
"and",
"root",
".",
"It",
"log",
".",
"Exits",
"out",
"if",
"an",
"error",
"occurs",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/server.go#L216-L225 | train |
vitessio/vitess | go/vt/topo/server.go | ConnForCell | func (ts *Server) ConnForCell(ctx context.Context, cell string) (Conn, error) {
// Global cell is the easy case.
if cell == GlobalCell {
return ts.globalCell, nil
}
// Return a cached client if present.
ts.mu.Lock()
conn, ok := ts.cells[cell]
ts.mu.Unlock()
if ok {
return conn, nil
}
// Fetch cell cluster addresses from the global cluster.
// These can proceed concurrently (we've released the lock).
// We can use the GlobalReadOnlyCell for this call.
ci, err := ts.GetCellInfo(ctx, cell, false /*strongRead*/)
if err != nil {
return nil, err
}
// Connect to the cell topo server, while holding the lock.
// This ensures only one connection is established at any given time.
ts.mu.Lock()
defer ts.mu.Unlock()
// Check if another goroutine beat us to creating a client for
// this cell.
if conn, ok = ts.cells[cell]; ok {
return conn, nil
}
// Create the connection.
conn, err = ts.factory.Create(cell, ci.ServerAddress, ci.Root)
switch {
case err == nil:
conn = NewStatsConn(cell, conn)
ts.cells[cell] = conn
return conn, nil
case IsErrType(err, NoNode):
err = vterrors.Wrap(err, fmt.Sprintf("failed to create topo connection to %v, %v", ci.ServerAddress, ci.Root))
return nil, NewError(NoNode, err.Error())
default:
return nil, vterrors.Wrap(err, fmt.Sprintf("failed to create topo connection to %v, %v", ci.ServerAddress, ci.Root))
}
} | go | func (ts *Server) ConnForCell(ctx context.Context, cell string) (Conn, error) {
// Global cell is the easy case.
if cell == GlobalCell {
return ts.globalCell, nil
}
// Return a cached client if present.
ts.mu.Lock()
conn, ok := ts.cells[cell]
ts.mu.Unlock()
if ok {
return conn, nil
}
// Fetch cell cluster addresses from the global cluster.
// These can proceed concurrently (we've released the lock).
// We can use the GlobalReadOnlyCell for this call.
ci, err := ts.GetCellInfo(ctx, cell, false /*strongRead*/)
if err != nil {
return nil, err
}
// Connect to the cell topo server, while holding the lock.
// This ensures only one connection is established at any given time.
ts.mu.Lock()
defer ts.mu.Unlock()
// Check if another goroutine beat us to creating a client for
// this cell.
if conn, ok = ts.cells[cell]; ok {
return conn, nil
}
// Create the connection.
conn, err = ts.factory.Create(cell, ci.ServerAddress, ci.Root)
switch {
case err == nil:
conn = NewStatsConn(cell, conn)
ts.cells[cell] = conn
return conn, nil
case IsErrType(err, NoNode):
err = vterrors.Wrap(err, fmt.Sprintf("failed to create topo connection to %v, %v", ci.ServerAddress, ci.Root))
return nil, NewError(NoNode, err.Error())
default:
return nil, vterrors.Wrap(err, fmt.Sprintf("failed to create topo connection to %v, %v", ci.ServerAddress, ci.Root))
}
} | [
"func",
"(",
"ts",
"*",
"Server",
")",
"ConnForCell",
"(",
"ctx",
"context",
".",
"Context",
",",
"cell",
"string",
")",
"(",
"Conn",
",",
"error",
")",
"{",
"// Global cell is the easy case.",
"if",
"cell",
"==",
"GlobalCell",
"{",
"return",
"ts",
".",
"globalCell",
",",
"nil",
"\n",
"}",
"\n\n",
"// Return a cached client if present.",
"ts",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"conn",
",",
"ok",
":=",
"ts",
".",
"cells",
"[",
"cell",
"]",
"\n",
"ts",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"ok",
"{",
"return",
"conn",
",",
"nil",
"\n",
"}",
"\n\n",
"// Fetch cell cluster addresses from the global cluster.",
"// These can proceed concurrently (we've released the lock).",
"// We can use the GlobalReadOnlyCell for this call.",
"ci",
",",
"err",
":=",
"ts",
".",
"GetCellInfo",
"(",
"ctx",
",",
"cell",
",",
"false",
"/*strongRead*/",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Connect to the cell topo server, while holding the lock.",
"// This ensures only one connection is established at any given time.",
"ts",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"ts",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"// Check if another goroutine beat us to creating a client for",
"// this cell.",
"if",
"conn",
",",
"ok",
"=",
"ts",
".",
"cells",
"[",
"cell",
"]",
";",
"ok",
"{",
"return",
"conn",
",",
"nil",
"\n",
"}",
"\n\n",
"// Create the connection.",
"conn",
",",
"err",
"=",
"ts",
".",
"factory",
".",
"Create",
"(",
"cell",
",",
"ci",
".",
"ServerAddress",
",",
"ci",
".",
"Root",
")",
"\n",
"switch",
"{",
"case",
"err",
"==",
"nil",
":",
"conn",
"=",
"NewStatsConn",
"(",
"cell",
",",
"conn",
")",
"\n",
"ts",
".",
"cells",
"[",
"cell",
"]",
"=",
"conn",
"\n",
"return",
"conn",
",",
"nil",
"\n",
"case",
"IsErrType",
"(",
"err",
",",
"NoNode",
")",
":",
"err",
"=",
"vterrors",
".",
"Wrap",
"(",
"err",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"ci",
".",
"ServerAddress",
",",
"ci",
".",
"Root",
")",
")",
"\n",
"return",
"nil",
",",
"NewError",
"(",
"NoNode",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"default",
":",
"return",
"nil",
",",
"vterrors",
".",
"Wrap",
"(",
"err",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"ci",
".",
"ServerAddress",
",",
"ci",
".",
"Root",
")",
")",
"\n",
"}",
"\n",
"}"
] | // ConnForCell returns a Conn object for the given cell.
// It caches Conn objects from previously requested cells. | [
"ConnForCell",
"returns",
"a",
"Conn",
"object",
"for",
"the",
"given",
"cell",
".",
"It",
"caches",
"Conn",
"objects",
"from",
"previously",
"requested",
"cells",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/server.go#L229-L275 | train |
vitessio/vitess | go/vt/topo/server.go | GetAliasByCell | func GetAliasByCell(ctx context.Context, ts *Server, cell string) string {
cellsAliases.mu.Lock()
defer cellsAliases.mu.Unlock()
if region, ok := cellsAliases.cellsToAliases[cell]; ok {
return region
}
if ts != nil {
// lazily get the region from cell info if `aliases` are available
cellAliases, err := ts.GetCellsAliases(ctx, false)
if err != nil {
// for backward compatibility
return cell
}
for alias, cellsAlias := range cellAliases {
for _, cellAlias := range cellsAlias.Cells {
if cellAlias == cell {
cellsAliases.cellsToAliases[cell] = alias
return alias
}
}
}
}
// for backward compatibility
return cell
} | go | func GetAliasByCell(ctx context.Context, ts *Server, cell string) string {
cellsAliases.mu.Lock()
defer cellsAliases.mu.Unlock()
if region, ok := cellsAliases.cellsToAliases[cell]; ok {
return region
}
if ts != nil {
// lazily get the region from cell info if `aliases` are available
cellAliases, err := ts.GetCellsAliases(ctx, false)
if err != nil {
// for backward compatibility
return cell
}
for alias, cellsAlias := range cellAliases {
for _, cellAlias := range cellsAlias.Cells {
if cellAlias == cell {
cellsAliases.cellsToAliases[cell] = alias
return alias
}
}
}
}
// for backward compatibility
return cell
} | [
"func",
"GetAliasByCell",
"(",
"ctx",
"context",
".",
"Context",
",",
"ts",
"*",
"Server",
",",
"cell",
"string",
")",
"string",
"{",
"cellsAliases",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"cellsAliases",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"region",
",",
"ok",
":=",
"cellsAliases",
".",
"cellsToAliases",
"[",
"cell",
"]",
";",
"ok",
"{",
"return",
"region",
"\n",
"}",
"\n",
"if",
"ts",
"!=",
"nil",
"{",
"// lazily get the region from cell info if `aliases` are available",
"cellAliases",
",",
"err",
":=",
"ts",
".",
"GetCellsAliases",
"(",
"ctx",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// for backward compatibility",
"return",
"cell",
"\n",
"}",
"\n\n",
"for",
"alias",
",",
"cellsAlias",
":=",
"range",
"cellAliases",
"{",
"for",
"_",
",",
"cellAlias",
":=",
"range",
"cellsAlias",
".",
"Cells",
"{",
"if",
"cellAlias",
"==",
"cell",
"{",
"cellsAliases",
".",
"cellsToAliases",
"[",
"cell",
"]",
"=",
"alias",
"\n",
"return",
"alias",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"// for backward compatibility",
"return",
"cell",
"\n",
"}"
] | // GetAliasByCell returns the alias group this `cell` belongs to, if there's none, it returns the `cell` as alias. | [
"GetAliasByCell",
"returns",
"the",
"alias",
"group",
"this",
"cell",
"belongs",
"to",
"if",
"there",
"s",
"none",
"it",
"returns",
"the",
"cell",
"as",
"alias",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/server.go#L278-L303 | train |
vitessio/vitess | go/vt/topo/server.go | Close | func (ts *Server) Close() {
ts.globalCell.Close()
if ts.globalReadOnlyCell != ts.globalCell {
ts.globalReadOnlyCell.Close()
}
ts.globalCell = nil
ts.globalReadOnlyCell = nil
ts.mu.Lock()
defer ts.mu.Unlock()
for _, conn := range ts.cells {
conn.Close()
}
ts.cells = make(map[string]Conn)
} | go | func (ts *Server) Close() {
ts.globalCell.Close()
if ts.globalReadOnlyCell != ts.globalCell {
ts.globalReadOnlyCell.Close()
}
ts.globalCell = nil
ts.globalReadOnlyCell = nil
ts.mu.Lock()
defer ts.mu.Unlock()
for _, conn := range ts.cells {
conn.Close()
}
ts.cells = make(map[string]Conn)
} | [
"func",
"(",
"ts",
"*",
"Server",
")",
"Close",
"(",
")",
"{",
"ts",
".",
"globalCell",
".",
"Close",
"(",
")",
"\n",
"if",
"ts",
".",
"globalReadOnlyCell",
"!=",
"ts",
".",
"globalCell",
"{",
"ts",
".",
"globalReadOnlyCell",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"ts",
".",
"globalCell",
"=",
"nil",
"\n",
"ts",
".",
"globalReadOnlyCell",
"=",
"nil",
"\n",
"ts",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"ts",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"for",
"_",
",",
"conn",
":=",
"range",
"ts",
".",
"cells",
"{",
"conn",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"ts",
".",
"cells",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"Conn",
")",
"\n",
"}"
] | // Close will close all connections to underlying topo Server.
// It will nil all member variables, so any further access will panic. | [
"Close",
"will",
"close",
"all",
"connections",
"to",
"underlying",
"topo",
"Server",
".",
"It",
"will",
"nil",
"all",
"member",
"variables",
"so",
"any",
"further",
"access",
"will",
"panic",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/server.go#L307-L320 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/planbuilder/permission.go | BuildPermissions | func BuildPermissions(stmt sqlparser.Statement) []Permission {
var permissions []Permission
// All Statement types myst be covered here.
switch node := stmt.(type) {
case *sqlparser.Union, *sqlparser.Select:
permissions = buildSubqueryPermissions(node, tableacl.READER, permissions)
case *sqlparser.Insert:
permissions = buildTableNamePermissions(node.Table, tableacl.WRITER, permissions)
permissions = buildSubqueryPermissions(node, tableacl.READER, permissions)
case *sqlparser.Update:
permissions = buildTableExprsPermissions(node.TableExprs, tableacl.WRITER, permissions)
permissions = buildSubqueryPermissions(node, tableacl.READER, permissions)
case *sqlparser.Delete:
permissions = buildTableExprsPermissions(node.TableExprs, tableacl.WRITER, permissions)
permissions = buildSubqueryPermissions(node, tableacl.READER, permissions)
case *sqlparser.Set, *sqlparser.Show, *sqlparser.OtherRead:
// no-op
case *sqlparser.DDL:
for _, t := range node.AffectedTables() {
permissions = buildTableNamePermissions(t, tableacl.ADMIN, permissions)
}
case *sqlparser.OtherAdmin:
// no op
case *sqlparser.Begin, *sqlparser.Commit, *sqlparser.Rollback:
// no op
default:
panic(fmt.Errorf("BUG: unexpected statement type: %T", node))
}
return permissions
} | go | func BuildPermissions(stmt sqlparser.Statement) []Permission {
var permissions []Permission
// All Statement types myst be covered here.
switch node := stmt.(type) {
case *sqlparser.Union, *sqlparser.Select:
permissions = buildSubqueryPermissions(node, tableacl.READER, permissions)
case *sqlparser.Insert:
permissions = buildTableNamePermissions(node.Table, tableacl.WRITER, permissions)
permissions = buildSubqueryPermissions(node, tableacl.READER, permissions)
case *sqlparser.Update:
permissions = buildTableExprsPermissions(node.TableExprs, tableacl.WRITER, permissions)
permissions = buildSubqueryPermissions(node, tableacl.READER, permissions)
case *sqlparser.Delete:
permissions = buildTableExprsPermissions(node.TableExprs, tableacl.WRITER, permissions)
permissions = buildSubqueryPermissions(node, tableacl.READER, permissions)
case *sqlparser.Set, *sqlparser.Show, *sqlparser.OtherRead:
// no-op
case *sqlparser.DDL:
for _, t := range node.AffectedTables() {
permissions = buildTableNamePermissions(t, tableacl.ADMIN, permissions)
}
case *sqlparser.OtherAdmin:
// no op
case *sqlparser.Begin, *sqlparser.Commit, *sqlparser.Rollback:
// no op
default:
panic(fmt.Errorf("BUG: unexpected statement type: %T", node))
}
return permissions
} | [
"func",
"BuildPermissions",
"(",
"stmt",
"sqlparser",
".",
"Statement",
")",
"[",
"]",
"Permission",
"{",
"var",
"permissions",
"[",
"]",
"Permission",
"\n",
"// All Statement types myst be covered here.",
"switch",
"node",
":=",
"stmt",
".",
"(",
"type",
")",
"{",
"case",
"*",
"sqlparser",
".",
"Union",
",",
"*",
"sqlparser",
".",
"Select",
":",
"permissions",
"=",
"buildSubqueryPermissions",
"(",
"node",
",",
"tableacl",
".",
"READER",
",",
"permissions",
")",
"\n",
"case",
"*",
"sqlparser",
".",
"Insert",
":",
"permissions",
"=",
"buildTableNamePermissions",
"(",
"node",
".",
"Table",
",",
"tableacl",
".",
"WRITER",
",",
"permissions",
")",
"\n",
"permissions",
"=",
"buildSubqueryPermissions",
"(",
"node",
",",
"tableacl",
".",
"READER",
",",
"permissions",
")",
"\n",
"case",
"*",
"sqlparser",
".",
"Update",
":",
"permissions",
"=",
"buildTableExprsPermissions",
"(",
"node",
".",
"TableExprs",
",",
"tableacl",
".",
"WRITER",
",",
"permissions",
")",
"\n",
"permissions",
"=",
"buildSubqueryPermissions",
"(",
"node",
",",
"tableacl",
".",
"READER",
",",
"permissions",
")",
"\n",
"case",
"*",
"sqlparser",
".",
"Delete",
":",
"permissions",
"=",
"buildTableExprsPermissions",
"(",
"node",
".",
"TableExprs",
",",
"tableacl",
".",
"WRITER",
",",
"permissions",
")",
"\n",
"permissions",
"=",
"buildSubqueryPermissions",
"(",
"node",
",",
"tableacl",
".",
"READER",
",",
"permissions",
")",
"\n",
"case",
"*",
"sqlparser",
".",
"Set",
",",
"*",
"sqlparser",
".",
"Show",
",",
"*",
"sqlparser",
".",
"OtherRead",
":",
"// no-op",
"case",
"*",
"sqlparser",
".",
"DDL",
":",
"for",
"_",
",",
"t",
":=",
"range",
"node",
".",
"AffectedTables",
"(",
")",
"{",
"permissions",
"=",
"buildTableNamePermissions",
"(",
"t",
",",
"tableacl",
".",
"ADMIN",
",",
"permissions",
")",
"\n",
"}",
"\n",
"case",
"*",
"sqlparser",
".",
"OtherAdmin",
":",
"// no op",
"case",
"*",
"sqlparser",
".",
"Begin",
",",
"*",
"sqlparser",
".",
"Commit",
",",
"*",
"sqlparser",
".",
"Rollback",
":",
"// no op",
"default",
":",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"node",
")",
")",
"\n",
"}",
"\n",
"return",
"permissions",
"\n",
"}"
] | // BuildPermissions builds the list of required permissions for all the
// tables referenced in a query. | [
"BuildPermissions",
"builds",
"the",
"list",
"of",
"required",
"permissions",
"for",
"all",
"the",
"tables",
"referenced",
"in",
"a",
"query",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/planbuilder/permission.go#L35-L64 | train |
vitessio/vitess | go/sqltypes/plan_value.go | IsNull | func (pv PlanValue) IsNull() bool {
return pv.Key == "" && pv.Value.IsNull() && pv.ListKey == "" && pv.Values == nil
} | go | func (pv PlanValue) IsNull() bool {
return pv.Key == "" && pv.Value.IsNull() && pv.ListKey == "" && pv.Values == nil
} | [
"func",
"(",
"pv",
"PlanValue",
")",
"IsNull",
"(",
")",
"bool",
"{",
"return",
"pv",
".",
"Key",
"==",
"\"",
"\"",
"&&",
"pv",
".",
"Value",
".",
"IsNull",
"(",
")",
"&&",
"pv",
".",
"ListKey",
"==",
"\"",
"\"",
"&&",
"pv",
".",
"Values",
"==",
"nil",
"\n",
"}"
] | // IsNull returns true if the PlanValue is NULL. | [
"IsNull",
"returns",
"true",
"if",
"the",
"PlanValue",
"is",
"NULL",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/plan_value.go#L67-L69 | train |
vitessio/vitess | go/sqltypes/plan_value.go | ResolveList | func (pv PlanValue) ResolveList(bindVars map[string]*querypb.BindVariable) ([]Value, error) {
switch {
case pv.ListKey != "":
bv, err := pv.lookupList(bindVars)
if err != nil {
return nil, err
}
values := make([]Value, 0, len(bv.Values))
for _, val := range bv.Values {
values = append(values, MakeTrusted(val.Type, val.Value))
}
return values, nil
case pv.Values != nil:
values := make([]Value, 0, len(pv.Values))
for _, val := range pv.Values {
v, err := val.ResolveValue(bindVars)
if err != nil {
return nil, err
}
values = append(values, v)
}
return values, nil
}
// This code is unreachable because the parser does not allow
// single value constructs where multiple values are expected.
return nil, vterrors.New(vtrpcpb.Code_INVALID_ARGUMENT, "a single value was supplied where a list was expected")
} | go | func (pv PlanValue) ResolveList(bindVars map[string]*querypb.BindVariable) ([]Value, error) {
switch {
case pv.ListKey != "":
bv, err := pv.lookupList(bindVars)
if err != nil {
return nil, err
}
values := make([]Value, 0, len(bv.Values))
for _, val := range bv.Values {
values = append(values, MakeTrusted(val.Type, val.Value))
}
return values, nil
case pv.Values != nil:
values := make([]Value, 0, len(pv.Values))
for _, val := range pv.Values {
v, err := val.ResolveValue(bindVars)
if err != nil {
return nil, err
}
values = append(values, v)
}
return values, nil
}
// This code is unreachable because the parser does not allow
// single value constructs where multiple values are expected.
return nil, vterrors.New(vtrpcpb.Code_INVALID_ARGUMENT, "a single value was supplied where a list was expected")
} | [
"func",
"(",
"pv",
"PlanValue",
")",
"ResolveList",
"(",
"bindVars",
"map",
"[",
"string",
"]",
"*",
"querypb",
".",
"BindVariable",
")",
"(",
"[",
"]",
"Value",
",",
"error",
")",
"{",
"switch",
"{",
"case",
"pv",
".",
"ListKey",
"!=",
"\"",
"\"",
":",
"bv",
",",
"err",
":=",
"pv",
".",
"lookupList",
"(",
"bindVars",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"values",
":=",
"make",
"(",
"[",
"]",
"Value",
",",
"0",
",",
"len",
"(",
"bv",
".",
"Values",
")",
")",
"\n",
"for",
"_",
",",
"val",
":=",
"range",
"bv",
".",
"Values",
"{",
"values",
"=",
"append",
"(",
"values",
",",
"MakeTrusted",
"(",
"val",
".",
"Type",
",",
"val",
".",
"Value",
")",
")",
"\n",
"}",
"\n",
"return",
"values",
",",
"nil",
"\n",
"case",
"pv",
".",
"Values",
"!=",
"nil",
":",
"values",
":=",
"make",
"(",
"[",
"]",
"Value",
",",
"0",
",",
"len",
"(",
"pv",
".",
"Values",
")",
")",
"\n",
"for",
"_",
",",
"val",
":=",
"range",
"pv",
".",
"Values",
"{",
"v",
",",
"err",
":=",
"val",
".",
"ResolveValue",
"(",
"bindVars",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"values",
"=",
"append",
"(",
"values",
",",
"v",
")",
"\n",
"}",
"\n",
"return",
"values",
",",
"nil",
"\n",
"}",
"\n",
"// This code is unreachable because the parser does not allow",
"// single value constructs where multiple values are expected.",
"return",
"nil",
",",
"vterrors",
".",
"New",
"(",
"vtrpcpb",
".",
"Code_INVALID_ARGUMENT",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // ResolveList resolves a PlanValue as a list of values based on the supplied bindvars. | [
"ResolveList",
"resolves",
"a",
"PlanValue",
"as",
"a",
"list",
"of",
"values",
"based",
"on",
"the",
"supplied",
"bindvars",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/plan_value.go#L107-L133 | train |
vitessio/vitess | go/sqltypes/plan_value.go | MarshalJSON | func (pv PlanValue) MarshalJSON() ([]byte, error) {
switch {
case pv.Key != "":
return json.Marshal(":" + pv.Key)
case !pv.Value.IsNull():
if pv.Value.IsIntegral() {
return pv.Value.ToBytes(), nil
}
return json.Marshal(pv.Value.ToString())
case pv.ListKey != "":
return json.Marshal("::" + pv.ListKey)
case pv.Values != nil:
return json.Marshal(pv.Values)
}
return []byte("null"), nil
} | go | func (pv PlanValue) MarshalJSON() ([]byte, error) {
switch {
case pv.Key != "":
return json.Marshal(":" + pv.Key)
case !pv.Value.IsNull():
if pv.Value.IsIntegral() {
return pv.Value.ToBytes(), nil
}
return json.Marshal(pv.Value.ToString())
case pv.ListKey != "":
return json.Marshal("::" + pv.ListKey)
case pv.Values != nil:
return json.Marshal(pv.Values)
}
return []byte("null"), nil
} | [
"func",
"(",
"pv",
"PlanValue",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"switch",
"{",
"case",
"pv",
".",
"Key",
"!=",
"\"",
"\"",
":",
"return",
"json",
".",
"Marshal",
"(",
"\"",
"\"",
"+",
"pv",
".",
"Key",
")",
"\n",
"case",
"!",
"pv",
".",
"Value",
".",
"IsNull",
"(",
")",
":",
"if",
"pv",
".",
"Value",
".",
"IsIntegral",
"(",
")",
"{",
"return",
"pv",
".",
"Value",
".",
"ToBytes",
"(",
")",
",",
"nil",
"\n",
"}",
"\n",
"return",
"json",
".",
"Marshal",
"(",
"pv",
".",
"Value",
".",
"ToString",
"(",
")",
")",
"\n",
"case",
"pv",
".",
"ListKey",
"!=",
"\"",
"\"",
":",
"return",
"json",
".",
"Marshal",
"(",
"\"",
"\"",
"+",
"pv",
".",
"ListKey",
")",
"\n",
"case",
"pv",
".",
"Values",
"!=",
"nil",
":",
"return",
"json",
".",
"Marshal",
"(",
"pv",
".",
"Values",
")",
"\n",
"}",
"\n",
"return",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
",",
"nil",
"\n",
"}"
] | // MarshalJSON should be used only for testing. | [
"MarshalJSON",
"should",
"be",
"used",
"only",
"for",
"testing",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/sqltypes/plan_value.go#L147-L162 | train |
vitessio/vitess | go/vt/discovery/healthcheck.go | ParseTabletURLTemplateFromFlag | func ParseTabletURLTemplateFromFlag() {
tabletURLTemplate = template.New("")
_, err := tabletURLTemplate.Parse(*tabletURLTemplateString)
if err != nil {
log.Exitf("error parsing template: %v", err)
}
} | go | func ParseTabletURLTemplateFromFlag() {
tabletURLTemplate = template.New("")
_, err := tabletURLTemplate.Parse(*tabletURLTemplateString)
if err != nil {
log.Exitf("error parsing template: %v", err)
}
} | [
"func",
"ParseTabletURLTemplateFromFlag",
"(",
")",
"{",
"tabletURLTemplate",
"=",
"template",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"_",
",",
"err",
":=",
"tabletURLTemplate",
".",
"Parse",
"(",
"*",
"tabletURLTemplateString",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Exitf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // ParseTabletURLTemplateFromFlag loads or reloads the URL template. | [
"ParseTabletURLTemplateFromFlag",
"loads",
"or",
"reloads",
"the",
"URL",
"template",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/healthcheck.go#L128-L134 | train |
vitessio/vitess | go/vt/discovery/healthcheck.go | DeepEqual | func (e *TabletStats) DeepEqual(f *TabletStats) bool {
return e.Key == f.Key &&
proto.Equal(e.Tablet, f.Tablet) &&
e.Name == f.Name &&
proto.Equal(e.Target, f.Target) &&
e.Up == f.Up &&
e.Serving == f.Serving &&
e.TabletExternallyReparentedTimestamp == f.TabletExternallyReparentedTimestamp &&
proto.Equal(e.Stats, f.Stats) &&
((e.LastError == nil && f.LastError == nil) ||
(e.LastError != nil && f.LastError != nil && e.LastError.Error() == f.LastError.Error()))
} | go | func (e *TabletStats) DeepEqual(f *TabletStats) bool {
return e.Key == f.Key &&
proto.Equal(e.Tablet, f.Tablet) &&
e.Name == f.Name &&
proto.Equal(e.Target, f.Target) &&
e.Up == f.Up &&
e.Serving == f.Serving &&
e.TabletExternallyReparentedTimestamp == f.TabletExternallyReparentedTimestamp &&
proto.Equal(e.Stats, f.Stats) &&
((e.LastError == nil && f.LastError == nil) ||
(e.LastError != nil && f.LastError != nil && e.LastError.Error() == f.LastError.Error()))
} | [
"func",
"(",
"e",
"*",
"TabletStats",
")",
"DeepEqual",
"(",
"f",
"*",
"TabletStats",
")",
"bool",
"{",
"return",
"e",
".",
"Key",
"==",
"f",
".",
"Key",
"&&",
"proto",
".",
"Equal",
"(",
"e",
".",
"Tablet",
",",
"f",
".",
"Tablet",
")",
"&&",
"e",
".",
"Name",
"==",
"f",
".",
"Name",
"&&",
"proto",
".",
"Equal",
"(",
"e",
".",
"Target",
",",
"f",
".",
"Target",
")",
"&&",
"e",
".",
"Up",
"==",
"f",
".",
"Up",
"&&",
"e",
".",
"Serving",
"==",
"f",
".",
"Serving",
"&&",
"e",
".",
"TabletExternallyReparentedTimestamp",
"==",
"f",
".",
"TabletExternallyReparentedTimestamp",
"&&",
"proto",
".",
"Equal",
"(",
"e",
".",
"Stats",
",",
"f",
".",
"Stats",
")",
"&&",
"(",
"(",
"e",
".",
"LastError",
"==",
"nil",
"&&",
"f",
".",
"LastError",
"==",
"nil",
")",
"||",
"(",
"e",
".",
"LastError",
"!=",
"nil",
"&&",
"f",
".",
"LastError",
"!=",
"nil",
"&&",
"e",
".",
"LastError",
".",
"Error",
"(",
")",
"==",
"f",
".",
"LastError",
".",
"Error",
"(",
")",
")",
")",
"\n",
"}"
] | // DeepEqual compares two TabletStats. Since we include protos, we
// need to use proto.Equal on these. | [
"DeepEqual",
"compares",
"two",
"TabletStats",
".",
"Since",
"we",
"include",
"protos",
"we",
"need",
"to",
"use",
"proto",
".",
"Equal",
"on",
"these",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/healthcheck.go#L193-L204 | train |
vitessio/vitess | go/vt/discovery/healthcheck.go | GetTabletHostPort | func (e TabletStats) GetTabletHostPort() string {
vtPort := e.Tablet.PortMap["vt"]
return netutil.JoinHostPort(e.Tablet.Hostname, vtPort)
} | go | func (e TabletStats) GetTabletHostPort() string {
vtPort := e.Tablet.PortMap["vt"]
return netutil.JoinHostPort(e.Tablet.Hostname, vtPort)
} | [
"func",
"(",
"e",
"TabletStats",
")",
"GetTabletHostPort",
"(",
")",
"string",
"{",
"vtPort",
":=",
"e",
".",
"Tablet",
".",
"PortMap",
"[",
"\"",
"\"",
"]",
"\n",
"return",
"netutil",
".",
"JoinHostPort",
"(",
"e",
".",
"Tablet",
".",
"Hostname",
",",
"vtPort",
")",
"\n",
"}"
] | // GetTabletHostPort formats a tablet host port address. | [
"GetTabletHostPort",
"formats",
"a",
"tablet",
"host",
"port",
"address",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/healthcheck.go#L213-L216 | train |
vitessio/vitess | go/vt/discovery/healthcheck.go | GetHostNameLevel | func (e TabletStats) GetHostNameLevel(level int) string {
chunkedHostname := strings.Split(e.Tablet.Hostname, ".")
if level < 0 {
return chunkedHostname[0]
} else if level >= len(chunkedHostname) {
return chunkedHostname[len(chunkedHostname)-1]
} else {
return chunkedHostname[level]
}
} | go | func (e TabletStats) GetHostNameLevel(level int) string {
chunkedHostname := strings.Split(e.Tablet.Hostname, ".")
if level < 0 {
return chunkedHostname[0]
} else if level >= len(chunkedHostname) {
return chunkedHostname[len(chunkedHostname)-1]
} else {
return chunkedHostname[level]
}
} | [
"func",
"(",
"e",
"TabletStats",
")",
"GetHostNameLevel",
"(",
"level",
"int",
")",
"string",
"{",
"chunkedHostname",
":=",
"strings",
".",
"Split",
"(",
"e",
".",
"Tablet",
".",
"Hostname",
",",
"\"",
"\"",
")",
"\n\n",
"if",
"level",
"<",
"0",
"{",
"return",
"chunkedHostname",
"[",
"0",
"]",
"\n",
"}",
"else",
"if",
"level",
">=",
"len",
"(",
"chunkedHostname",
")",
"{",
"return",
"chunkedHostname",
"[",
"len",
"(",
"chunkedHostname",
")",
"-",
"1",
"]",
"\n",
"}",
"else",
"{",
"return",
"chunkedHostname",
"[",
"level",
"]",
"\n",
"}",
"\n",
"}"
] | // GetHostNameLevel returns the specified hostname level. If the level does not exist it will pick the closest level.
// This seems unused but can be utilized by certain url formatting templates. See getTabletDebugURL for more details. | [
"GetHostNameLevel",
"returns",
"the",
"specified",
"hostname",
"level",
".",
"If",
"the",
"level",
"does",
"not",
"exist",
"it",
"will",
"pick",
"the",
"closest",
"level",
".",
"This",
"seems",
"unused",
"but",
"can",
"be",
"utilized",
"by",
"certain",
"url",
"formatting",
"templates",
".",
"See",
"getTabletDebugURL",
"for",
"more",
"details",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/healthcheck.go#L220-L230 | train |
vitessio/vitess | go/vt/discovery/healthcheck.go | RegisterStats | func (hc *HealthCheckImpl) RegisterStats() {
stats.NewGaugesFuncWithMultiLabels(
"HealthcheckConnections",
"the number of healthcheck connections registered",
[]string{"Keyspace", "ShardName", "TabletType"},
hc.servingConnStats)
stats.NewGaugeFunc(
"HealthcheckChecksum",
"crc32 checksum of the current healthcheck state",
hc.stateChecksum)
} | go | func (hc *HealthCheckImpl) RegisterStats() {
stats.NewGaugesFuncWithMultiLabels(
"HealthcheckConnections",
"the number of healthcheck connections registered",
[]string{"Keyspace", "ShardName", "TabletType"},
hc.servingConnStats)
stats.NewGaugeFunc(
"HealthcheckChecksum",
"crc32 checksum of the current healthcheck state",
hc.stateChecksum)
} | [
"func",
"(",
"hc",
"*",
"HealthCheckImpl",
")",
"RegisterStats",
"(",
")",
"{",
"stats",
".",
"NewGaugesFuncWithMultiLabels",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"hc",
".",
"servingConnStats",
")",
"\n\n",
"stats",
".",
"NewGaugeFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"hc",
".",
"stateChecksum",
")",
"\n",
"}"
] | // RegisterStats registers the connection counts stats | [
"RegisterStats",
"registers",
"the",
"connection",
"counts",
"stats"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/healthcheck.go#L378-L389 | train |
vitessio/vitess | go/vt/discovery/healthcheck.go | ServeHTTP | func (hc *HealthCheckImpl) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
status := hc.cacheStatusMap()
b, err := json.MarshalIndent(status, "", " ")
if err != nil {
w.Write([]byte(err.Error()))
return
}
buf := bytes.NewBuffer(nil)
json.HTMLEscape(buf, b)
w.Write(buf.Bytes())
} | go | func (hc *HealthCheckImpl) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
status := hc.cacheStatusMap()
b, err := json.MarshalIndent(status, "", " ")
if err != nil {
w.Write([]byte(err.Error()))
return
}
buf := bytes.NewBuffer(nil)
json.HTMLEscape(buf, b)
w.Write(buf.Bytes())
} | [
"func",
"(",
"hc",
"*",
"HealthCheckImpl",
")",
"ServeHTTP",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"_",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"status",
":=",
"hc",
".",
"cacheStatusMap",
"(",
")",
"\n",
"b",
",",
"err",
":=",
"json",
".",
"MarshalIndent",
"(",
"status",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"err",
".",
"Error",
"(",
")",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"buf",
":=",
"bytes",
".",
"NewBuffer",
"(",
"nil",
")",
"\n",
"json",
".",
"HTMLEscape",
"(",
"buf",
",",
"b",
")",
"\n",
"w",
".",
"Write",
"(",
"buf",
".",
"Bytes",
"(",
")",
")",
"\n",
"}"
] | // ServeHTTP is part of the http.Handler interface. It renders the current state of the discovery gateway tablet cache into json. | [
"ServeHTTP",
"is",
"part",
"of",
"the",
"http",
".",
"Handler",
"interface",
".",
"It",
"renders",
"the",
"current",
"state",
"of",
"the",
"discovery",
"gateway",
"tablet",
"cache",
"into",
"json",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/healthcheck.go#L392-L404 | train |
vitessio/vitess | go/vt/discovery/healthcheck.go | stateChecksum | func (hc *HealthCheckImpl) stateChecksum() int64 {
// CacheStatus is sorted so this should be stable across vtgates
cacheStatus := hc.CacheStatus()
var buf bytes.Buffer
for _, st := range cacheStatus {
fmt.Fprintf(&buf,
"%v%v%v%v\n",
st.Cell,
st.Target.Keyspace,
st.Target.Shard,
st.Target.TabletType.String(),
)
sort.Sort(st.TabletsStats)
for _, ts := range st.TabletsStats {
fmt.Fprintf(&buf, "%v%v%v\n", ts.Up, ts.Serving, ts.TabletExternallyReparentedTimestamp)
}
}
return int64(crc32.ChecksumIEEE(buf.Bytes()))
} | go | func (hc *HealthCheckImpl) stateChecksum() int64 {
// CacheStatus is sorted so this should be stable across vtgates
cacheStatus := hc.CacheStatus()
var buf bytes.Buffer
for _, st := range cacheStatus {
fmt.Fprintf(&buf,
"%v%v%v%v\n",
st.Cell,
st.Target.Keyspace,
st.Target.Shard,
st.Target.TabletType.String(),
)
sort.Sort(st.TabletsStats)
for _, ts := range st.TabletsStats {
fmt.Fprintf(&buf, "%v%v%v\n", ts.Up, ts.Serving, ts.TabletExternallyReparentedTimestamp)
}
}
return int64(crc32.ChecksumIEEE(buf.Bytes()))
} | [
"func",
"(",
"hc",
"*",
"HealthCheckImpl",
")",
"stateChecksum",
"(",
")",
"int64",
"{",
"// CacheStatus is sorted so this should be stable across vtgates",
"cacheStatus",
":=",
"hc",
".",
"CacheStatus",
"(",
")",
"\n",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"for",
"_",
",",
"st",
":=",
"range",
"cacheStatus",
"{",
"fmt",
".",
"Fprintf",
"(",
"&",
"buf",
",",
"\"",
"\\n",
"\"",
",",
"st",
".",
"Cell",
",",
"st",
".",
"Target",
".",
"Keyspace",
",",
"st",
".",
"Target",
".",
"Shard",
",",
"st",
".",
"Target",
".",
"TabletType",
".",
"String",
"(",
")",
",",
")",
"\n",
"sort",
".",
"Sort",
"(",
"st",
".",
"TabletsStats",
")",
"\n",
"for",
"_",
",",
"ts",
":=",
"range",
"st",
".",
"TabletsStats",
"{",
"fmt",
".",
"Fprintf",
"(",
"&",
"buf",
",",
"\"",
"\\n",
"\"",
",",
"ts",
".",
"Up",
",",
"ts",
".",
"Serving",
",",
"ts",
".",
"TabletExternallyReparentedTimestamp",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"int64",
"(",
"crc32",
".",
"ChecksumIEEE",
"(",
"buf",
".",
"Bytes",
"(",
")",
")",
")",
"\n",
"}"
] | // stateChecksum returns a crc32 checksum of the healthcheck state | [
"stateChecksum",
"returns",
"a",
"crc32",
"checksum",
"of",
"the",
"healthcheck",
"state"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/healthcheck.go#L422-L441 | train |
vitessio/vitess | go/vt/discovery/healthcheck.go | updateHealth | func (hc *HealthCheckImpl) updateHealth(ts *TabletStats, conn queryservice.QueryService) {
// Unconditionally send the received update at the end.
defer func() {
if hc.listener != nil {
hc.listener.StatsUpdate(ts)
}
}()
hc.mu.Lock()
th, ok := hc.addrToHealth[ts.Key]
if !ok {
// This can happen on delete because the entry is removed first,
// or if HealthCheckImpl has been closed.
hc.mu.Unlock()
return
}
oldts := th.latestTabletStats
th.latestTabletStats = *ts
th.conn = conn
hc.mu.Unlock()
// In the case where a tablet changes type (but not for the
// initial message), we want to log it, and maybe advertise it too.
if oldts.Target.TabletType != topodatapb.TabletType_UNKNOWN && oldts.Target.TabletType != ts.Target.TabletType {
// Log and maybe notify
log.Infof("HealthCheckUpdate(Type Change): %v, tablet: %s, target %+v => %+v, reparent time: %v",
oldts.Name, topotools.TabletIdent(oldts.Tablet), topotools.TargetIdent(oldts.Target), topotools.TargetIdent(ts.Target), ts.TabletExternallyReparentedTimestamp)
if hc.listener != nil && hc.sendDownEvents {
oldts.Up = false
hc.listener.StatsUpdate(&oldts)
}
// Track how often a tablet gets promoted to master. It is used for
// comparing against the variables in go/vtgate/buffer/variables.go.
if oldts.Target.TabletType != topodatapb.TabletType_MASTER && ts.Target.TabletType == topodatapb.TabletType_MASTER {
hcMasterPromotedCounters.Add([]string{ts.Target.Keyspace, ts.Target.Shard}, 1)
}
}
} | go | func (hc *HealthCheckImpl) updateHealth(ts *TabletStats, conn queryservice.QueryService) {
// Unconditionally send the received update at the end.
defer func() {
if hc.listener != nil {
hc.listener.StatsUpdate(ts)
}
}()
hc.mu.Lock()
th, ok := hc.addrToHealth[ts.Key]
if !ok {
// This can happen on delete because the entry is removed first,
// or if HealthCheckImpl has been closed.
hc.mu.Unlock()
return
}
oldts := th.latestTabletStats
th.latestTabletStats = *ts
th.conn = conn
hc.mu.Unlock()
// In the case where a tablet changes type (but not for the
// initial message), we want to log it, and maybe advertise it too.
if oldts.Target.TabletType != topodatapb.TabletType_UNKNOWN && oldts.Target.TabletType != ts.Target.TabletType {
// Log and maybe notify
log.Infof("HealthCheckUpdate(Type Change): %v, tablet: %s, target %+v => %+v, reparent time: %v",
oldts.Name, topotools.TabletIdent(oldts.Tablet), topotools.TargetIdent(oldts.Target), topotools.TargetIdent(ts.Target), ts.TabletExternallyReparentedTimestamp)
if hc.listener != nil && hc.sendDownEvents {
oldts.Up = false
hc.listener.StatsUpdate(&oldts)
}
// Track how often a tablet gets promoted to master. It is used for
// comparing against the variables in go/vtgate/buffer/variables.go.
if oldts.Target.TabletType != topodatapb.TabletType_MASTER && ts.Target.TabletType == topodatapb.TabletType_MASTER {
hcMasterPromotedCounters.Add([]string{ts.Target.Keyspace, ts.Target.Shard}, 1)
}
}
} | [
"func",
"(",
"hc",
"*",
"HealthCheckImpl",
")",
"updateHealth",
"(",
"ts",
"*",
"TabletStats",
",",
"conn",
"queryservice",
".",
"QueryService",
")",
"{",
"// Unconditionally send the received update at the end.",
"defer",
"func",
"(",
")",
"{",
"if",
"hc",
".",
"listener",
"!=",
"nil",
"{",
"hc",
".",
"listener",
".",
"StatsUpdate",
"(",
"ts",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"hc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"th",
",",
"ok",
":=",
"hc",
".",
"addrToHealth",
"[",
"ts",
".",
"Key",
"]",
"\n",
"if",
"!",
"ok",
"{",
"// This can happen on delete because the entry is removed first,",
"// or if HealthCheckImpl has been closed.",
"hc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"oldts",
":=",
"th",
".",
"latestTabletStats",
"\n",
"th",
".",
"latestTabletStats",
"=",
"*",
"ts",
"\n",
"th",
".",
"conn",
"=",
"conn",
"\n",
"hc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"// In the case where a tablet changes type (but not for the",
"// initial message), we want to log it, and maybe advertise it too.",
"if",
"oldts",
".",
"Target",
".",
"TabletType",
"!=",
"topodatapb",
".",
"TabletType_UNKNOWN",
"&&",
"oldts",
".",
"Target",
".",
"TabletType",
"!=",
"ts",
".",
"Target",
".",
"TabletType",
"{",
"// Log and maybe notify",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"oldts",
".",
"Name",
",",
"topotools",
".",
"TabletIdent",
"(",
"oldts",
".",
"Tablet",
")",
",",
"topotools",
".",
"TargetIdent",
"(",
"oldts",
".",
"Target",
")",
",",
"topotools",
".",
"TargetIdent",
"(",
"ts",
".",
"Target",
")",
",",
"ts",
".",
"TabletExternallyReparentedTimestamp",
")",
"\n",
"if",
"hc",
".",
"listener",
"!=",
"nil",
"&&",
"hc",
".",
"sendDownEvents",
"{",
"oldts",
".",
"Up",
"=",
"false",
"\n",
"hc",
".",
"listener",
".",
"StatsUpdate",
"(",
"&",
"oldts",
")",
"\n",
"}",
"\n\n",
"// Track how often a tablet gets promoted to master. It is used for",
"// comparing against the variables in go/vtgate/buffer/variables.go.",
"if",
"oldts",
".",
"Target",
".",
"TabletType",
"!=",
"topodatapb",
".",
"TabletType_MASTER",
"&&",
"ts",
".",
"Target",
".",
"TabletType",
"==",
"topodatapb",
".",
"TabletType_MASTER",
"{",
"hcMasterPromotedCounters",
".",
"Add",
"(",
"[",
"]",
"string",
"{",
"ts",
".",
"Target",
".",
"Keyspace",
",",
"ts",
".",
"Target",
".",
"Shard",
"}",
",",
"1",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // updateHealth updates the tabletHealth record and transmits the tablet stats
// to the listener. | [
"updateHealth",
"updates",
"the",
"tabletHealth",
"record",
"and",
"transmits",
"the",
"tablet",
"stats",
"to",
"the",
"listener",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/healthcheck.go#L445-L483 | train |
vitessio/vitess | go/vt/discovery/healthcheck.go | checkConn | func (hc *HealthCheckImpl) checkConn(hcc *healthCheckConn, name string) {
defer hc.connsWG.Done()
defer hc.finalizeConn(hcc)
// Initial notification for downstream about the tablet existence.
hc.updateHealth(hcc.tabletStats.Copy(), hcc.conn)
hc.initialUpdatesWG.Done()
retryDelay := hc.retryDelay
for {
streamCtx, streamCancel := context.WithCancel(hcc.ctx)
// Setup a watcher that restarts the timer every time an update is received.
// If a timeout occurs for a serving tablet, we make it non-serving and send
// a status update. The stream is also terminated so it can be retried.
// servingStatus feeds into the serving var, which keeps track of the serving
// status transmitted by the tablet.
servingStatus := make(chan bool, 1)
// timedout is accessed atomically because there could be a race
// between the goroutine that sets it and the check for its value
// later.
timedout := sync2.NewAtomicBool(false)
go func() {
for {
select {
case <-servingStatus:
continue
case <-time.After(hc.healthCheckTimeout):
timedout.Set(true)
streamCancel()
return
case <-streamCtx.Done():
// If the stream is done, stop watching.
return
}
}
}()
// Read stream health responses.
hcc.stream(streamCtx, hc, func(shr *querypb.StreamHealthResponse) error {
// We received a message. Reset the back-off.
retryDelay = hc.retryDelay
// Don't block on send to avoid deadlocks.
select {
case servingStatus <- shr.Serving:
default:
}
return hcc.processResponse(hc, shr)
})
// streamCancel to make sure the watcher goroutine terminates.
streamCancel()
// If there was a timeout send an error. We do this after stream has returned.
// This will ensure that this update prevails over any previous message that
// stream could have sent.
if timedout.Get() {
hcc.tabletStats.LastError = fmt.Errorf("healthcheck timed out (latest %v)", hcc.lastResponseTimestamp)
hcc.setServingState(false, hcc.tabletStats.LastError.Error())
hc.updateHealth(hcc.tabletStats.Copy(), hcc.conn)
hcErrorCounters.Add([]string{hcc.tabletStats.Target.Keyspace, hcc.tabletStats.Target.Shard, topoproto.TabletTypeLString(hcc.tabletStats.Target.TabletType)}, 1)
}
// Streaming RPC failed e.g. because vttablet was restarted or took too long.
// Sleep until the next retry is up or the context is done/canceled.
select {
case <-hcc.ctx.Done():
return
case <-time.After(retryDelay):
// Exponentially back-off to prevent tight-loop.
retryDelay *= 2
// Limit the retry delay backoff to the health check timeout
if retryDelay > hc.healthCheckTimeout {
retryDelay = hc.healthCheckTimeout
}
}
}
} | go | func (hc *HealthCheckImpl) checkConn(hcc *healthCheckConn, name string) {
defer hc.connsWG.Done()
defer hc.finalizeConn(hcc)
// Initial notification for downstream about the tablet existence.
hc.updateHealth(hcc.tabletStats.Copy(), hcc.conn)
hc.initialUpdatesWG.Done()
retryDelay := hc.retryDelay
for {
streamCtx, streamCancel := context.WithCancel(hcc.ctx)
// Setup a watcher that restarts the timer every time an update is received.
// If a timeout occurs for a serving tablet, we make it non-serving and send
// a status update. The stream is also terminated so it can be retried.
// servingStatus feeds into the serving var, which keeps track of the serving
// status transmitted by the tablet.
servingStatus := make(chan bool, 1)
// timedout is accessed atomically because there could be a race
// between the goroutine that sets it and the check for its value
// later.
timedout := sync2.NewAtomicBool(false)
go func() {
for {
select {
case <-servingStatus:
continue
case <-time.After(hc.healthCheckTimeout):
timedout.Set(true)
streamCancel()
return
case <-streamCtx.Done():
// If the stream is done, stop watching.
return
}
}
}()
// Read stream health responses.
hcc.stream(streamCtx, hc, func(shr *querypb.StreamHealthResponse) error {
// We received a message. Reset the back-off.
retryDelay = hc.retryDelay
// Don't block on send to avoid deadlocks.
select {
case servingStatus <- shr.Serving:
default:
}
return hcc.processResponse(hc, shr)
})
// streamCancel to make sure the watcher goroutine terminates.
streamCancel()
// If there was a timeout send an error. We do this after stream has returned.
// This will ensure that this update prevails over any previous message that
// stream could have sent.
if timedout.Get() {
hcc.tabletStats.LastError = fmt.Errorf("healthcheck timed out (latest %v)", hcc.lastResponseTimestamp)
hcc.setServingState(false, hcc.tabletStats.LastError.Error())
hc.updateHealth(hcc.tabletStats.Copy(), hcc.conn)
hcErrorCounters.Add([]string{hcc.tabletStats.Target.Keyspace, hcc.tabletStats.Target.Shard, topoproto.TabletTypeLString(hcc.tabletStats.Target.TabletType)}, 1)
}
// Streaming RPC failed e.g. because vttablet was restarted or took too long.
// Sleep until the next retry is up or the context is done/canceled.
select {
case <-hcc.ctx.Done():
return
case <-time.After(retryDelay):
// Exponentially back-off to prevent tight-loop.
retryDelay *= 2
// Limit the retry delay backoff to the health check timeout
if retryDelay > hc.healthCheckTimeout {
retryDelay = hc.healthCheckTimeout
}
}
}
} | [
"func",
"(",
"hc",
"*",
"HealthCheckImpl",
")",
"checkConn",
"(",
"hcc",
"*",
"healthCheckConn",
",",
"name",
"string",
")",
"{",
"defer",
"hc",
".",
"connsWG",
".",
"Done",
"(",
")",
"\n",
"defer",
"hc",
".",
"finalizeConn",
"(",
"hcc",
")",
"\n\n",
"// Initial notification for downstream about the tablet existence.",
"hc",
".",
"updateHealth",
"(",
"hcc",
".",
"tabletStats",
".",
"Copy",
"(",
")",
",",
"hcc",
".",
"conn",
")",
"\n",
"hc",
".",
"initialUpdatesWG",
".",
"Done",
"(",
")",
"\n\n",
"retryDelay",
":=",
"hc",
".",
"retryDelay",
"\n",
"for",
"{",
"streamCtx",
",",
"streamCancel",
":=",
"context",
".",
"WithCancel",
"(",
"hcc",
".",
"ctx",
")",
"\n\n",
"// Setup a watcher that restarts the timer every time an update is received.",
"// If a timeout occurs for a serving tablet, we make it non-serving and send",
"// a status update. The stream is also terminated so it can be retried.",
"// servingStatus feeds into the serving var, which keeps track of the serving",
"// status transmitted by the tablet.",
"servingStatus",
":=",
"make",
"(",
"chan",
"bool",
",",
"1",
")",
"\n",
"// timedout is accessed atomically because there could be a race",
"// between the goroutine that sets it and the check for its value",
"// later.",
"timedout",
":=",
"sync2",
".",
"NewAtomicBool",
"(",
"false",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"<-",
"servingStatus",
":",
"continue",
"\n",
"case",
"<-",
"time",
".",
"After",
"(",
"hc",
".",
"healthCheckTimeout",
")",
":",
"timedout",
".",
"Set",
"(",
"true",
")",
"\n",
"streamCancel",
"(",
")",
"\n",
"return",
"\n",
"case",
"<-",
"streamCtx",
".",
"Done",
"(",
")",
":",
"// If the stream is done, stop watching.",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"// Read stream health responses.",
"hcc",
".",
"stream",
"(",
"streamCtx",
",",
"hc",
",",
"func",
"(",
"shr",
"*",
"querypb",
".",
"StreamHealthResponse",
")",
"error",
"{",
"// We received a message. Reset the back-off.",
"retryDelay",
"=",
"hc",
".",
"retryDelay",
"\n",
"// Don't block on send to avoid deadlocks.",
"select",
"{",
"case",
"servingStatus",
"<-",
"shr",
".",
"Serving",
":",
"default",
":",
"}",
"\n",
"return",
"hcc",
".",
"processResponse",
"(",
"hc",
",",
"shr",
")",
"\n",
"}",
")",
"\n\n",
"// streamCancel to make sure the watcher goroutine terminates.",
"streamCancel",
"(",
")",
"\n\n",
"// If there was a timeout send an error. We do this after stream has returned.",
"// This will ensure that this update prevails over any previous message that",
"// stream could have sent.",
"if",
"timedout",
".",
"Get",
"(",
")",
"{",
"hcc",
".",
"tabletStats",
".",
"LastError",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"hcc",
".",
"lastResponseTimestamp",
")",
"\n",
"hcc",
".",
"setServingState",
"(",
"false",
",",
"hcc",
".",
"tabletStats",
".",
"LastError",
".",
"Error",
"(",
")",
")",
"\n",
"hc",
".",
"updateHealth",
"(",
"hcc",
".",
"tabletStats",
".",
"Copy",
"(",
")",
",",
"hcc",
".",
"conn",
")",
"\n",
"hcErrorCounters",
".",
"Add",
"(",
"[",
"]",
"string",
"{",
"hcc",
".",
"tabletStats",
".",
"Target",
".",
"Keyspace",
",",
"hcc",
".",
"tabletStats",
".",
"Target",
".",
"Shard",
",",
"topoproto",
".",
"TabletTypeLString",
"(",
"hcc",
".",
"tabletStats",
".",
"Target",
".",
"TabletType",
")",
"}",
",",
"1",
")",
"\n",
"}",
"\n\n",
"// Streaming RPC failed e.g. because vttablet was restarted or took too long.",
"// Sleep until the next retry is up or the context is done/canceled.",
"select",
"{",
"case",
"<-",
"hcc",
".",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"\n",
"case",
"<-",
"time",
".",
"After",
"(",
"retryDelay",
")",
":",
"// Exponentially back-off to prevent tight-loop.",
"retryDelay",
"*=",
"2",
"\n",
"// Limit the retry delay backoff to the health check timeout",
"if",
"retryDelay",
">",
"hc",
".",
"healthCheckTimeout",
"{",
"retryDelay",
"=",
"hc",
".",
"healthCheckTimeout",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // checkConn performs health checking on the given tablet. | [
"checkConn",
"performs",
"health",
"checking",
"on",
"the",
"given",
"tablet",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/healthcheck.go#L506-L583 | train |
vitessio/vitess | go/vt/discovery/healthcheck.go | setServingState | func (hcc *healthCheckConn) setServingState(serving bool, reason string) {
if !hcc.loggedServingState || (serving != hcc.tabletStats.Serving) {
// Emit the log from a separate goroutine to avoid holding
// the hcc lock while logging is happening
go log.Infof("HealthCheckUpdate(Serving State): %v, tablet: %v serving => %v for %v/%v (%v) reason: %s",
hcc.tabletStats.Name,
topotools.TabletIdent(hcc.tabletStats.Tablet),
serving,
hcc.tabletStats.Tablet.GetKeyspace(),
hcc.tabletStats.Tablet.GetShard(),
hcc.tabletStats.Target.GetTabletType(),
reason,
)
hcc.loggedServingState = true
}
hcc.tabletStats.Serving = serving
} | go | func (hcc *healthCheckConn) setServingState(serving bool, reason string) {
if !hcc.loggedServingState || (serving != hcc.tabletStats.Serving) {
// Emit the log from a separate goroutine to avoid holding
// the hcc lock while logging is happening
go log.Infof("HealthCheckUpdate(Serving State): %v, tablet: %v serving => %v for %v/%v (%v) reason: %s",
hcc.tabletStats.Name,
topotools.TabletIdent(hcc.tabletStats.Tablet),
serving,
hcc.tabletStats.Tablet.GetKeyspace(),
hcc.tabletStats.Tablet.GetShard(),
hcc.tabletStats.Target.GetTabletType(),
reason,
)
hcc.loggedServingState = true
}
hcc.tabletStats.Serving = serving
} | [
"func",
"(",
"hcc",
"*",
"healthCheckConn",
")",
"setServingState",
"(",
"serving",
"bool",
",",
"reason",
"string",
")",
"{",
"if",
"!",
"hcc",
".",
"loggedServingState",
"||",
"(",
"serving",
"!=",
"hcc",
".",
"tabletStats",
".",
"Serving",
")",
"{",
"// Emit the log from a separate goroutine to avoid holding",
"// the hcc lock while logging is happening",
"go",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"hcc",
".",
"tabletStats",
".",
"Name",
",",
"topotools",
".",
"TabletIdent",
"(",
"hcc",
".",
"tabletStats",
".",
"Tablet",
")",
",",
"serving",
",",
"hcc",
".",
"tabletStats",
".",
"Tablet",
".",
"GetKeyspace",
"(",
")",
",",
"hcc",
".",
"tabletStats",
".",
"Tablet",
".",
"GetShard",
"(",
")",
",",
"hcc",
".",
"tabletStats",
".",
"Target",
".",
"GetTabletType",
"(",
")",
",",
"reason",
",",
")",
"\n",
"hcc",
".",
"loggedServingState",
"=",
"true",
"\n",
"}",
"\n\n",
"hcc",
".",
"tabletStats",
".",
"Serving",
"=",
"serving",
"\n",
"}"
] | // setServingState sets the tablet state to the given value.
//
// If the state changes, it logs the change so that failures
// from the health check connection are logged the first time,
// but don't continue to log if the connection stays down.
//
// hcc.mu must be locked before calling this function | [
"setServingState",
"sets",
"the",
"tablet",
"state",
"to",
"the",
"given",
"value",
".",
"If",
"the",
"state",
"changes",
"it",
"logs",
"the",
"change",
"so",
"that",
"failures",
"from",
"the",
"health",
"check",
"connection",
"are",
"logged",
"the",
"first",
"time",
"but",
"don",
"t",
"continue",
"to",
"log",
"if",
"the",
"connection",
"stays",
"down",
".",
"hcc",
".",
"mu",
"must",
"be",
"locked",
"before",
"calling",
"this",
"function"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/healthcheck.go#L592-L609 | train |
vitessio/vitess | go/vt/discovery/healthcheck.go | stream | func (hcc *healthCheckConn) stream(ctx context.Context, hc *HealthCheckImpl, callback func(*querypb.StreamHealthResponse) error) {
if hcc.conn == nil {
conn, err := tabletconn.GetDialer()(hcc.tabletStats.Tablet, grpcclient.FailFast(true))
if err != nil {
hcc.tabletStats.LastError = err
return
}
hcc.conn = conn
hcc.tabletStats.LastError = nil
}
if err := hcc.conn.StreamHealth(ctx, callback); err != nil {
hcc.setServingState(false, err.Error())
hcc.tabletStats.LastError = err
// Send nil because we intend to close the connection.
hc.updateHealth(hcc.tabletStats.Copy(), nil)
hcc.conn.Close(ctx)
hcc.conn = nil
}
} | go | func (hcc *healthCheckConn) stream(ctx context.Context, hc *HealthCheckImpl, callback func(*querypb.StreamHealthResponse) error) {
if hcc.conn == nil {
conn, err := tabletconn.GetDialer()(hcc.tabletStats.Tablet, grpcclient.FailFast(true))
if err != nil {
hcc.tabletStats.LastError = err
return
}
hcc.conn = conn
hcc.tabletStats.LastError = nil
}
if err := hcc.conn.StreamHealth(ctx, callback); err != nil {
hcc.setServingState(false, err.Error())
hcc.tabletStats.LastError = err
// Send nil because we intend to close the connection.
hc.updateHealth(hcc.tabletStats.Copy(), nil)
hcc.conn.Close(ctx)
hcc.conn = nil
}
} | [
"func",
"(",
"hcc",
"*",
"healthCheckConn",
")",
"stream",
"(",
"ctx",
"context",
".",
"Context",
",",
"hc",
"*",
"HealthCheckImpl",
",",
"callback",
"func",
"(",
"*",
"querypb",
".",
"StreamHealthResponse",
")",
"error",
")",
"{",
"if",
"hcc",
".",
"conn",
"==",
"nil",
"{",
"conn",
",",
"err",
":=",
"tabletconn",
".",
"GetDialer",
"(",
")",
"(",
"hcc",
".",
"tabletStats",
".",
"Tablet",
",",
"grpcclient",
".",
"FailFast",
"(",
"true",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"hcc",
".",
"tabletStats",
".",
"LastError",
"=",
"err",
"\n",
"return",
"\n",
"}",
"\n",
"hcc",
".",
"conn",
"=",
"conn",
"\n",
"hcc",
".",
"tabletStats",
".",
"LastError",
"=",
"nil",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"hcc",
".",
"conn",
".",
"StreamHealth",
"(",
"ctx",
",",
"callback",
")",
";",
"err",
"!=",
"nil",
"{",
"hcc",
".",
"setServingState",
"(",
"false",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"hcc",
".",
"tabletStats",
".",
"LastError",
"=",
"err",
"\n",
"// Send nil because we intend to close the connection.",
"hc",
".",
"updateHealth",
"(",
"hcc",
".",
"tabletStats",
".",
"Copy",
"(",
")",
",",
"nil",
")",
"\n",
"hcc",
".",
"conn",
".",
"Close",
"(",
"ctx",
")",
"\n",
"hcc",
".",
"conn",
"=",
"nil",
"\n",
"}",
"\n",
"}"
] | // stream streams healthcheck responses to callback. | [
"stream",
"streams",
"healthcheck",
"responses",
"to",
"callback",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/healthcheck.go#L612-L631 | train |
vitessio/vitess | go/vt/discovery/healthcheck.go | processResponse | func (hcc *healthCheckConn) processResponse(hc *HealthCheckImpl, shr *querypb.StreamHealthResponse) error {
select {
case <-hcc.ctx.Done():
return hcc.ctx.Err()
default:
}
// Check for invalid data, better than panicking.
if shr.Target == nil || shr.RealtimeStats == nil {
return fmt.Errorf("health stats is not valid: %v", shr)
}
// an app-level error from tablet, force serving state.
var healthErr error
serving := shr.Serving
if shr.RealtimeStats.HealthError != "" {
healthErr = fmt.Errorf("vttablet error: %v", shr.RealtimeStats.HealthError)
serving = false
}
// hcc.TabletStats.Tablet.Alias.Uid may be 0 because the youtube internal mechanism uses a different
// code path to initialize this value. If so, we should skip this check.
if shr.TabletAlias != nil && hcc.tabletStats.Tablet.Alias.Uid != 0 && !proto.Equal(shr.TabletAlias, hcc.tabletStats.Tablet.Alias) {
return fmt.Errorf("health stats mismatch, tablet %+v alias does not match response alias %v", hcc.tabletStats.Tablet, shr.TabletAlias)
}
// In this case where a new tablet is initialized or a tablet type changes, we want to
// initialize the counter so the rate can be calculated correctly.
if hcc.tabletStats.Target.TabletType != shr.Target.TabletType {
hcErrorCounters.Add([]string{shr.Target.Keyspace, shr.Target.Shard, topoproto.TabletTypeLString(shr.Target.TabletType)}, 0)
}
// Update our record, and notify downstream for tabletType and
// realtimeStats change.
hcc.lastResponseTimestamp = time.Now()
hcc.tabletStats.Target = shr.Target
hcc.tabletStats.TabletExternallyReparentedTimestamp = shr.TabletExternallyReparentedTimestamp
hcc.tabletStats.Stats = shr.RealtimeStats
hcc.tabletStats.LastError = healthErr
reason := "healthCheck update"
if healthErr != nil {
reason = "healthCheck update error: " + healthErr.Error()
}
hcc.setServingState(serving, reason)
hc.updateHealth(hcc.tabletStats.Copy(), hcc.conn)
return nil
} | go | func (hcc *healthCheckConn) processResponse(hc *HealthCheckImpl, shr *querypb.StreamHealthResponse) error {
select {
case <-hcc.ctx.Done():
return hcc.ctx.Err()
default:
}
// Check for invalid data, better than panicking.
if shr.Target == nil || shr.RealtimeStats == nil {
return fmt.Errorf("health stats is not valid: %v", shr)
}
// an app-level error from tablet, force serving state.
var healthErr error
serving := shr.Serving
if shr.RealtimeStats.HealthError != "" {
healthErr = fmt.Errorf("vttablet error: %v", shr.RealtimeStats.HealthError)
serving = false
}
// hcc.TabletStats.Tablet.Alias.Uid may be 0 because the youtube internal mechanism uses a different
// code path to initialize this value. If so, we should skip this check.
if shr.TabletAlias != nil && hcc.tabletStats.Tablet.Alias.Uid != 0 && !proto.Equal(shr.TabletAlias, hcc.tabletStats.Tablet.Alias) {
return fmt.Errorf("health stats mismatch, tablet %+v alias does not match response alias %v", hcc.tabletStats.Tablet, shr.TabletAlias)
}
// In this case where a new tablet is initialized or a tablet type changes, we want to
// initialize the counter so the rate can be calculated correctly.
if hcc.tabletStats.Target.TabletType != shr.Target.TabletType {
hcErrorCounters.Add([]string{shr.Target.Keyspace, shr.Target.Shard, topoproto.TabletTypeLString(shr.Target.TabletType)}, 0)
}
// Update our record, and notify downstream for tabletType and
// realtimeStats change.
hcc.lastResponseTimestamp = time.Now()
hcc.tabletStats.Target = shr.Target
hcc.tabletStats.TabletExternallyReparentedTimestamp = shr.TabletExternallyReparentedTimestamp
hcc.tabletStats.Stats = shr.RealtimeStats
hcc.tabletStats.LastError = healthErr
reason := "healthCheck update"
if healthErr != nil {
reason = "healthCheck update error: " + healthErr.Error()
}
hcc.setServingState(serving, reason)
hc.updateHealth(hcc.tabletStats.Copy(), hcc.conn)
return nil
} | [
"func",
"(",
"hcc",
"*",
"healthCheckConn",
")",
"processResponse",
"(",
"hc",
"*",
"HealthCheckImpl",
",",
"shr",
"*",
"querypb",
".",
"StreamHealthResponse",
")",
"error",
"{",
"select",
"{",
"case",
"<-",
"hcc",
".",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"hcc",
".",
"ctx",
".",
"Err",
"(",
")",
"\n",
"default",
":",
"}",
"\n\n",
"// Check for invalid data, better than panicking.",
"if",
"shr",
".",
"Target",
"==",
"nil",
"||",
"shr",
".",
"RealtimeStats",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"shr",
")",
"\n",
"}",
"\n\n",
"// an app-level error from tablet, force serving state.",
"var",
"healthErr",
"error",
"\n",
"serving",
":=",
"shr",
".",
"Serving",
"\n",
"if",
"shr",
".",
"RealtimeStats",
".",
"HealthError",
"!=",
"\"",
"\"",
"{",
"healthErr",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"shr",
".",
"RealtimeStats",
".",
"HealthError",
")",
"\n",
"serving",
"=",
"false",
"\n",
"}",
"\n\n",
"// hcc.TabletStats.Tablet.Alias.Uid may be 0 because the youtube internal mechanism uses a different",
"// code path to initialize this value. If so, we should skip this check.",
"if",
"shr",
".",
"TabletAlias",
"!=",
"nil",
"&&",
"hcc",
".",
"tabletStats",
".",
"Tablet",
".",
"Alias",
".",
"Uid",
"!=",
"0",
"&&",
"!",
"proto",
".",
"Equal",
"(",
"shr",
".",
"TabletAlias",
",",
"hcc",
".",
"tabletStats",
".",
"Tablet",
".",
"Alias",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"hcc",
".",
"tabletStats",
".",
"Tablet",
",",
"shr",
".",
"TabletAlias",
")",
"\n",
"}",
"\n\n",
"// In this case where a new tablet is initialized or a tablet type changes, we want to",
"// initialize the counter so the rate can be calculated correctly.",
"if",
"hcc",
".",
"tabletStats",
".",
"Target",
".",
"TabletType",
"!=",
"shr",
".",
"Target",
".",
"TabletType",
"{",
"hcErrorCounters",
".",
"Add",
"(",
"[",
"]",
"string",
"{",
"shr",
".",
"Target",
".",
"Keyspace",
",",
"shr",
".",
"Target",
".",
"Shard",
",",
"topoproto",
".",
"TabletTypeLString",
"(",
"shr",
".",
"Target",
".",
"TabletType",
")",
"}",
",",
"0",
")",
"\n",
"}",
"\n\n",
"// Update our record, and notify downstream for tabletType and",
"// realtimeStats change.",
"hcc",
".",
"lastResponseTimestamp",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"hcc",
".",
"tabletStats",
".",
"Target",
"=",
"shr",
".",
"Target",
"\n",
"hcc",
".",
"tabletStats",
".",
"TabletExternallyReparentedTimestamp",
"=",
"shr",
".",
"TabletExternallyReparentedTimestamp",
"\n",
"hcc",
".",
"tabletStats",
".",
"Stats",
"=",
"shr",
".",
"RealtimeStats",
"\n",
"hcc",
".",
"tabletStats",
".",
"LastError",
"=",
"healthErr",
"\n",
"reason",
":=",
"\"",
"\"",
"\n",
"if",
"healthErr",
"!=",
"nil",
"{",
"reason",
"=",
"\"",
"\"",
"+",
"healthErr",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"hcc",
".",
"setServingState",
"(",
"serving",
",",
"reason",
")",
"\n",
"hc",
".",
"updateHealth",
"(",
"hcc",
".",
"tabletStats",
".",
"Copy",
"(",
")",
",",
"hcc",
".",
"conn",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // processResponse reads one health check response, and notifies HealthCheckStatsListener. | [
"processResponse",
"reads",
"one",
"health",
"check",
"response",
"and",
"notifies",
"HealthCheckStatsListener",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/healthcheck.go#L634-L680 | train |
vitessio/vitess | go/vt/discovery/healthcheck.go | ReplaceTablet | func (hc *HealthCheckImpl) ReplaceTablet(old, new *topodatapb.Tablet, name string) {
go func() {
hc.deleteConn(old)
hc.AddTablet(new, name)
}()
} | go | func (hc *HealthCheckImpl) ReplaceTablet(old, new *topodatapb.Tablet, name string) {
go func() {
hc.deleteConn(old)
hc.AddTablet(new, name)
}()
} | [
"func",
"(",
"hc",
"*",
"HealthCheckImpl",
")",
"ReplaceTablet",
"(",
"old",
",",
"new",
"*",
"topodatapb",
".",
"Tablet",
",",
"name",
"string",
")",
"{",
"go",
"func",
"(",
")",
"{",
"hc",
".",
"deleteConn",
"(",
"old",
")",
"\n",
"hc",
".",
"AddTablet",
"(",
"new",
",",
"name",
")",
"\n",
"}",
"(",
")",
"\n",
"}"
] | // ReplaceTablet removes the old tablet and adds the new tablet. | [
"ReplaceTablet",
"removes",
"the",
"old",
"tablet",
"and",
"adds",
"the",
"new",
"tablet",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/healthcheck.go#L759-L764 | train |
vitessio/vitess | go/vt/discovery/healthcheck.go | StatusAsHTML | func (tcs *TabletsCacheStatus) StatusAsHTML() template.HTML {
tLinks := make([]string, 0, 1)
if tcs.TabletsStats != nil {
sort.Sort(tcs.TabletsStats)
}
for _, ts := range tcs.TabletsStats {
color := "green"
extra := ""
if ts.LastError != nil {
color = "red"
extra = fmt.Sprintf(" (%v)", ts.LastError)
} else if !ts.Serving {
color = "red"
extra = " (Not Serving)"
} else if !ts.Up {
color = "red"
extra = " (Down)"
} else if ts.Target.TabletType == topodatapb.TabletType_MASTER {
extra = fmt.Sprintf(" (MasterTS: %v)", ts.TabletExternallyReparentedTimestamp)
} else {
extra = fmt.Sprintf(" (RepLag: %v)", ts.Stats.SecondsBehindMaster)
}
name := ts.Name
if name == "" {
name = ts.GetTabletHostPort()
}
tLinks = append(tLinks, fmt.Sprintf(`<a href="%s" style="color:%v">%v</a>%v`, ts.getTabletDebugURL(), color, name, extra))
}
return template.HTML(strings.Join(tLinks, "<br>"))
} | go | func (tcs *TabletsCacheStatus) StatusAsHTML() template.HTML {
tLinks := make([]string, 0, 1)
if tcs.TabletsStats != nil {
sort.Sort(tcs.TabletsStats)
}
for _, ts := range tcs.TabletsStats {
color := "green"
extra := ""
if ts.LastError != nil {
color = "red"
extra = fmt.Sprintf(" (%v)", ts.LastError)
} else if !ts.Serving {
color = "red"
extra = " (Not Serving)"
} else if !ts.Up {
color = "red"
extra = " (Down)"
} else if ts.Target.TabletType == topodatapb.TabletType_MASTER {
extra = fmt.Sprintf(" (MasterTS: %v)", ts.TabletExternallyReparentedTimestamp)
} else {
extra = fmt.Sprintf(" (RepLag: %v)", ts.Stats.SecondsBehindMaster)
}
name := ts.Name
if name == "" {
name = ts.GetTabletHostPort()
}
tLinks = append(tLinks, fmt.Sprintf(`<a href="%s" style="color:%v">%v</a>%v`, ts.getTabletDebugURL(), color, name, extra))
}
return template.HTML(strings.Join(tLinks, "<br>"))
} | [
"func",
"(",
"tcs",
"*",
"TabletsCacheStatus",
")",
"StatusAsHTML",
"(",
")",
"template",
".",
"HTML",
"{",
"tLinks",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"1",
")",
"\n",
"if",
"tcs",
".",
"TabletsStats",
"!=",
"nil",
"{",
"sort",
".",
"Sort",
"(",
"tcs",
".",
"TabletsStats",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"ts",
":=",
"range",
"tcs",
".",
"TabletsStats",
"{",
"color",
":=",
"\"",
"\"",
"\n",
"extra",
":=",
"\"",
"\"",
"\n",
"if",
"ts",
".",
"LastError",
"!=",
"nil",
"{",
"color",
"=",
"\"",
"\"",
"\n",
"extra",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"ts",
".",
"LastError",
")",
"\n",
"}",
"else",
"if",
"!",
"ts",
".",
"Serving",
"{",
"color",
"=",
"\"",
"\"",
"\n",
"extra",
"=",
"\"",
"\"",
"\n",
"}",
"else",
"if",
"!",
"ts",
".",
"Up",
"{",
"color",
"=",
"\"",
"\"",
"\n",
"extra",
"=",
"\"",
"\"",
"\n",
"}",
"else",
"if",
"ts",
".",
"Target",
".",
"TabletType",
"==",
"topodatapb",
".",
"TabletType_MASTER",
"{",
"extra",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"ts",
".",
"TabletExternallyReparentedTimestamp",
")",
"\n",
"}",
"else",
"{",
"extra",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"ts",
".",
"Stats",
".",
"SecondsBehindMaster",
")",
"\n",
"}",
"\n",
"name",
":=",
"ts",
".",
"Name",
"\n",
"if",
"name",
"==",
"\"",
"\"",
"{",
"name",
"=",
"ts",
".",
"GetTabletHostPort",
"(",
")",
"\n",
"}",
"\n",
"tLinks",
"=",
"append",
"(",
"tLinks",
",",
"fmt",
".",
"Sprintf",
"(",
"`<a href=\"%s\" style=\"color:%v\">%v</a>%v`",
",",
"ts",
".",
"getTabletDebugURL",
"(",
")",
",",
"color",
",",
"name",
",",
"extra",
")",
")",
"\n",
"}",
"\n",
"return",
"template",
".",
"HTML",
"(",
"strings",
".",
"Join",
"(",
"tLinks",
",",
"\"",
"\"",
")",
")",
"\n",
"}"
] | // StatusAsHTML returns an HTML version of the status. | [
"StatusAsHTML",
"returns",
"an",
"HTML",
"version",
"of",
"the",
"status",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/healthcheck.go#L818-L847 | train |
vitessio/vitess | go/vt/discovery/healthcheck.go | CacheStatus | func (hc *HealthCheckImpl) CacheStatus() TabletsCacheStatusList {
tcsMap := hc.cacheStatusMap()
tcsl := make(TabletsCacheStatusList, 0, len(tcsMap))
for _, tcs := range tcsMap {
tcsl = append(tcsl, tcs)
}
sort.Sort(tcsl)
return tcsl
} | go | func (hc *HealthCheckImpl) CacheStatus() TabletsCacheStatusList {
tcsMap := hc.cacheStatusMap()
tcsl := make(TabletsCacheStatusList, 0, len(tcsMap))
for _, tcs := range tcsMap {
tcsl = append(tcsl, tcs)
}
sort.Sort(tcsl)
return tcsl
} | [
"func",
"(",
"hc",
"*",
"HealthCheckImpl",
")",
"CacheStatus",
"(",
")",
"TabletsCacheStatusList",
"{",
"tcsMap",
":=",
"hc",
".",
"cacheStatusMap",
"(",
")",
"\n",
"tcsl",
":=",
"make",
"(",
"TabletsCacheStatusList",
",",
"0",
",",
"len",
"(",
"tcsMap",
")",
")",
"\n",
"for",
"_",
",",
"tcs",
":=",
"range",
"tcsMap",
"{",
"tcsl",
"=",
"append",
"(",
"tcsl",
",",
"tcs",
")",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"tcsl",
")",
"\n",
"return",
"tcsl",
"\n",
"}"
] | // CacheStatus returns a displayable version of the cache. | [
"CacheStatus",
"returns",
"a",
"displayable",
"version",
"of",
"the",
"cache",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/healthcheck.go#L869-L877 | train |
vitessio/vitess | go/vt/discovery/healthcheck.go | TabletToMapKey | func TabletToMapKey(tablet *topodatapb.Tablet) string {
parts := make([]string, 0, 1)
for name, port := range tablet.PortMap {
parts = append(parts, netutil.JoinHostPort(name, port))
}
sort.Strings(parts)
parts = append([]string{tablet.Hostname}, parts...)
return strings.Join(parts, ",")
} | go | func TabletToMapKey(tablet *topodatapb.Tablet) string {
parts := make([]string, 0, 1)
for name, port := range tablet.PortMap {
parts = append(parts, netutil.JoinHostPort(name, port))
}
sort.Strings(parts)
parts = append([]string{tablet.Hostname}, parts...)
return strings.Join(parts, ",")
} | [
"func",
"TabletToMapKey",
"(",
"tablet",
"*",
"topodatapb",
".",
"Tablet",
")",
"string",
"{",
"parts",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"1",
")",
"\n",
"for",
"name",
",",
"port",
":=",
"range",
"tablet",
".",
"PortMap",
"{",
"parts",
"=",
"append",
"(",
"parts",
",",
"netutil",
".",
"JoinHostPort",
"(",
"name",
",",
"port",
")",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"parts",
")",
"\n",
"parts",
"=",
"append",
"(",
"[",
"]",
"string",
"{",
"tablet",
".",
"Hostname",
"}",
",",
"parts",
"...",
")",
"\n",
"return",
"strings",
".",
"Join",
"(",
"parts",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // TabletToMapKey creates a key to the map from tablet's host and ports.
// It should only be used in discovery and related module. | [
"TabletToMapKey",
"creates",
"a",
"key",
"to",
"the",
"map",
"from",
"tablet",
"s",
"host",
"and",
"ports",
".",
"It",
"should",
"only",
"be",
"used",
"in",
"discovery",
"and",
"related",
"module",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/discovery/healthcheck.go#L922-L930 | train |
vitessio/vitess | go/vt/vterrors/grpc.go | CodeToLegacyErrorCode | func CodeToLegacyErrorCode(code vtrpcpb.Code) vtrpcpb.LegacyErrorCode {
switch code {
case vtrpcpb.Code_OK:
return vtrpcpb.LegacyErrorCode_SUCCESS_LEGACY
case vtrpcpb.Code_CANCELED:
return vtrpcpb.LegacyErrorCode_CANCELLED_LEGACY
case vtrpcpb.Code_UNKNOWN:
return vtrpcpb.LegacyErrorCode_UNKNOWN_ERROR_LEGACY
case vtrpcpb.Code_INVALID_ARGUMENT:
return vtrpcpb.LegacyErrorCode_BAD_INPUT_LEGACY
case vtrpcpb.Code_DEADLINE_EXCEEDED:
return vtrpcpb.LegacyErrorCode_DEADLINE_EXCEEDED_LEGACY
case vtrpcpb.Code_ALREADY_EXISTS:
return vtrpcpb.LegacyErrorCode_INTEGRITY_ERROR_LEGACY
case vtrpcpb.Code_PERMISSION_DENIED:
return vtrpcpb.LegacyErrorCode_PERMISSION_DENIED_LEGACY
case vtrpcpb.Code_RESOURCE_EXHAUSTED:
return vtrpcpb.LegacyErrorCode_RESOURCE_EXHAUSTED_LEGACY
case vtrpcpb.Code_FAILED_PRECONDITION:
return vtrpcpb.LegacyErrorCode_QUERY_NOT_SERVED_LEGACY
case vtrpcpb.Code_ABORTED:
return vtrpcpb.LegacyErrorCode_NOT_IN_TX_LEGACY
case vtrpcpb.Code_INTERNAL:
return vtrpcpb.LegacyErrorCode_INTERNAL_ERROR_LEGACY
case vtrpcpb.Code_UNAVAILABLE:
// Legacy code assumes Unavailable errors are sent as Internal.
return vtrpcpb.LegacyErrorCode_INTERNAL_ERROR_LEGACY
case vtrpcpb.Code_UNAUTHENTICATED:
return vtrpcpb.LegacyErrorCode_UNAUTHENTICATED_LEGACY
default:
return vtrpcpb.LegacyErrorCode_UNKNOWN_ERROR_LEGACY
}
} | go | func CodeToLegacyErrorCode(code vtrpcpb.Code) vtrpcpb.LegacyErrorCode {
switch code {
case vtrpcpb.Code_OK:
return vtrpcpb.LegacyErrorCode_SUCCESS_LEGACY
case vtrpcpb.Code_CANCELED:
return vtrpcpb.LegacyErrorCode_CANCELLED_LEGACY
case vtrpcpb.Code_UNKNOWN:
return vtrpcpb.LegacyErrorCode_UNKNOWN_ERROR_LEGACY
case vtrpcpb.Code_INVALID_ARGUMENT:
return vtrpcpb.LegacyErrorCode_BAD_INPUT_LEGACY
case vtrpcpb.Code_DEADLINE_EXCEEDED:
return vtrpcpb.LegacyErrorCode_DEADLINE_EXCEEDED_LEGACY
case vtrpcpb.Code_ALREADY_EXISTS:
return vtrpcpb.LegacyErrorCode_INTEGRITY_ERROR_LEGACY
case vtrpcpb.Code_PERMISSION_DENIED:
return vtrpcpb.LegacyErrorCode_PERMISSION_DENIED_LEGACY
case vtrpcpb.Code_RESOURCE_EXHAUSTED:
return vtrpcpb.LegacyErrorCode_RESOURCE_EXHAUSTED_LEGACY
case vtrpcpb.Code_FAILED_PRECONDITION:
return vtrpcpb.LegacyErrorCode_QUERY_NOT_SERVED_LEGACY
case vtrpcpb.Code_ABORTED:
return vtrpcpb.LegacyErrorCode_NOT_IN_TX_LEGACY
case vtrpcpb.Code_INTERNAL:
return vtrpcpb.LegacyErrorCode_INTERNAL_ERROR_LEGACY
case vtrpcpb.Code_UNAVAILABLE:
// Legacy code assumes Unavailable errors are sent as Internal.
return vtrpcpb.LegacyErrorCode_INTERNAL_ERROR_LEGACY
case vtrpcpb.Code_UNAUTHENTICATED:
return vtrpcpb.LegacyErrorCode_UNAUTHENTICATED_LEGACY
default:
return vtrpcpb.LegacyErrorCode_UNKNOWN_ERROR_LEGACY
}
} | [
"func",
"CodeToLegacyErrorCode",
"(",
"code",
"vtrpcpb",
".",
"Code",
")",
"vtrpcpb",
".",
"LegacyErrorCode",
"{",
"switch",
"code",
"{",
"case",
"vtrpcpb",
".",
"Code_OK",
":",
"return",
"vtrpcpb",
".",
"LegacyErrorCode_SUCCESS_LEGACY",
"\n",
"case",
"vtrpcpb",
".",
"Code_CANCELED",
":",
"return",
"vtrpcpb",
".",
"LegacyErrorCode_CANCELLED_LEGACY",
"\n",
"case",
"vtrpcpb",
".",
"Code_UNKNOWN",
":",
"return",
"vtrpcpb",
".",
"LegacyErrorCode_UNKNOWN_ERROR_LEGACY",
"\n",
"case",
"vtrpcpb",
".",
"Code_INVALID_ARGUMENT",
":",
"return",
"vtrpcpb",
".",
"LegacyErrorCode_BAD_INPUT_LEGACY",
"\n",
"case",
"vtrpcpb",
".",
"Code_DEADLINE_EXCEEDED",
":",
"return",
"vtrpcpb",
".",
"LegacyErrorCode_DEADLINE_EXCEEDED_LEGACY",
"\n",
"case",
"vtrpcpb",
".",
"Code_ALREADY_EXISTS",
":",
"return",
"vtrpcpb",
".",
"LegacyErrorCode_INTEGRITY_ERROR_LEGACY",
"\n",
"case",
"vtrpcpb",
".",
"Code_PERMISSION_DENIED",
":",
"return",
"vtrpcpb",
".",
"LegacyErrorCode_PERMISSION_DENIED_LEGACY",
"\n",
"case",
"vtrpcpb",
".",
"Code_RESOURCE_EXHAUSTED",
":",
"return",
"vtrpcpb",
".",
"LegacyErrorCode_RESOURCE_EXHAUSTED_LEGACY",
"\n",
"case",
"vtrpcpb",
".",
"Code_FAILED_PRECONDITION",
":",
"return",
"vtrpcpb",
".",
"LegacyErrorCode_QUERY_NOT_SERVED_LEGACY",
"\n",
"case",
"vtrpcpb",
".",
"Code_ABORTED",
":",
"return",
"vtrpcpb",
".",
"LegacyErrorCode_NOT_IN_TX_LEGACY",
"\n",
"case",
"vtrpcpb",
".",
"Code_INTERNAL",
":",
"return",
"vtrpcpb",
".",
"LegacyErrorCode_INTERNAL_ERROR_LEGACY",
"\n",
"case",
"vtrpcpb",
".",
"Code_UNAVAILABLE",
":",
"// Legacy code assumes Unavailable errors are sent as Internal.",
"return",
"vtrpcpb",
".",
"LegacyErrorCode_INTERNAL_ERROR_LEGACY",
"\n",
"case",
"vtrpcpb",
".",
"Code_UNAUTHENTICATED",
":",
"return",
"vtrpcpb",
".",
"LegacyErrorCode_UNAUTHENTICATED_LEGACY",
"\n",
"default",
":",
"return",
"vtrpcpb",
".",
"LegacyErrorCode_UNKNOWN_ERROR_LEGACY",
"\n",
"}",
"\n",
"}"
] | // This file contains functions to convert errors to and from gRPC codes.
// Use these methods to return an error through gRPC and still
// retain its code.
// CodeToLegacyErrorCode maps a vtrpcpb.Code to a vtrpcpb.LegacyErrorCode. | [
"This",
"file",
"contains",
"functions",
"to",
"convert",
"errors",
"to",
"and",
"from",
"gRPC",
"codes",
".",
"Use",
"these",
"methods",
"to",
"return",
"an",
"error",
"through",
"gRPC",
"and",
"still",
"retain",
"its",
"code",
".",
"CodeToLegacyErrorCode",
"maps",
"a",
"vtrpcpb",
".",
"Code",
"to",
"a",
"vtrpcpb",
".",
"LegacyErrorCode",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vterrors/grpc.go#L34-L66 | train |
vitessio/vitess | go/vt/vterrors/grpc.go | truncateError | func truncateError(err error) string {
// For more details see: https://github.com/grpc/grpc-go/issues/443
// The gRPC spec says "Clients may limit the size of Response-Headers,
// Trailers, and Trailers-Only, with a default of 8 KiB each suggested."
// Therefore, we assume 8 KiB minus some headroom.
GRPCErrorLimit := 8*1024 - 512
if len(err.Error()) <= GRPCErrorLimit {
return err.Error()
}
truncateInfo := "[...] [remainder of the error is truncated because gRPC has a size limit on errors.]"
truncatedErr := err.Error()[:GRPCErrorLimit]
return fmt.Sprintf("%v %v", truncatedErr, truncateInfo)
} | go | func truncateError(err error) string {
// For more details see: https://github.com/grpc/grpc-go/issues/443
// The gRPC spec says "Clients may limit the size of Response-Headers,
// Trailers, and Trailers-Only, with a default of 8 KiB each suggested."
// Therefore, we assume 8 KiB minus some headroom.
GRPCErrorLimit := 8*1024 - 512
if len(err.Error()) <= GRPCErrorLimit {
return err.Error()
}
truncateInfo := "[...] [remainder of the error is truncated because gRPC has a size limit on errors.]"
truncatedErr := err.Error()[:GRPCErrorLimit]
return fmt.Sprintf("%v %v", truncatedErr, truncateInfo)
} | [
"func",
"truncateError",
"(",
"err",
"error",
")",
"string",
"{",
"// For more details see: https://github.com/grpc/grpc-go/issues/443",
"// The gRPC spec says \"Clients may limit the size of Response-Headers,",
"// Trailers, and Trailers-Only, with a default of 8 KiB each suggested.\"",
"// Therefore, we assume 8 KiB minus some headroom.",
"GRPCErrorLimit",
":=",
"8",
"*",
"1024",
"-",
"512",
"\n",
"if",
"len",
"(",
"err",
".",
"Error",
"(",
")",
")",
"<=",
"GRPCErrorLimit",
"{",
"return",
"err",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"truncateInfo",
":=",
"\"",
"\"",
"\n",
"truncatedErr",
":=",
"err",
".",
"Error",
"(",
")",
"[",
":",
"GRPCErrorLimit",
"]",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"truncatedErr",
",",
"truncateInfo",
")",
"\n",
"}"
] | // truncateError shortens errors because gRPC has a size restriction on them. | [
"truncateError",
"shortens",
"errors",
"because",
"gRPC",
"has",
"a",
"size",
"restriction",
"on",
"them",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vterrors/grpc.go#L104-L116 | train |
vitessio/vitess | go/vt/vterrors/grpc.go | ToGRPC | func ToGRPC(err error) error {
if err == nil {
return nil
}
return status.Errorf(codes.Code(Code(err)), "%v", truncateError(err))
} | go | func ToGRPC(err error) error {
if err == nil {
return nil
}
return status.Errorf(codes.Code(Code(err)), "%v", truncateError(err))
} | [
"func",
"ToGRPC",
"(",
"err",
"error",
")",
"error",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"status",
".",
"Errorf",
"(",
"codes",
".",
"Code",
"(",
"Code",
"(",
"err",
")",
")",
",",
"\"",
"\"",
",",
"truncateError",
"(",
"err",
")",
")",
"\n",
"}"
] | // ToGRPC returns an error as a gRPC error, with the appropriate error code. | [
"ToGRPC",
"returns",
"an",
"error",
"as",
"a",
"gRPC",
"error",
"with",
"the",
"appropriate",
"error",
"code",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vterrors/grpc.go#L119-L124 | train |
vitessio/vitess | go/vt/vterrors/grpc.go | FromGRPC | func FromGRPC(err error) error {
if err == nil {
return nil
}
if err == io.EOF {
// Do not wrap io.EOF because we compare against it for finished streams.
return err
}
code := codes.Unknown
if s, ok := status.FromError(err); ok {
code = s.Code()
}
return New(vtrpcpb.Code(code), err.Error())
} | go | func FromGRPC(err error) error {
if err == nil {
return nil
}
if err == io.EOF {
// Do not wrap io.EOF because we compare against it for finished streams.
return err
}
code := codes.Unknown
if s, ok := status.FromError(err); ok {
code = s.Code()
}
return New(vtrpcpb.Code(code), err.Error())
} | [
"func",
"FromGRPC",
"(",
"err",
"error",
")",
"error",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"==",
"io",
".",
"EOF",
"{",
"// Do not wrap io.EOF because we compare against it for finished streams.",
"return",
"err",
"\n",
"}",
"\n",
"code",
":=",
"codes",
".",
"Unknown",
"\n",
"if",
"s",
",",
"ok",
":=",
"status",
".",
"FromError",
"(",
"err",
")",
";",
"ok",
"{",
"code",
"=",
"s",
".",
"Code",
"(",
")",
"\n",
"}",
"\n",
"return",
"New",
"(",
"vtrpcpb",
".",
"Code",
"(",
"code",
")",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}"
] | // FromGRPC returns a gRPC error as a vtError, translating between error codes.
// However, there are a few errors which are not translated and passed as they
// are. For example, io.EOF since our code base checks for this error to find
// out that a stream has finished. | [
"FromGRPC",
"returns",
"a",
"gRPC",
"error",
"as",
"a",
"vtError",
"translating",
"between",
"error",
"codes",
".",
"However",
"there",
"are",
"a",
"few",
"errors",
"which",
"are",
"not",
"translated",
"and",
"passed",
"as",
"they",
"are",
".",
"For",
"example",
"io",
".",
"EOF",
"since",
"our",
"code",
"base",
"checks",
"for",
"this",
"error",
"to",
"find",
"out",
"that",
"a",
"stream",
"has",
"finished",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vterrors/grpc.go#L130-L143 | train |
vitessio/vitess | go/vt/worker/legacy_row_splitter.go | NewRowSplitter | func NewRowSplitter(shardInfos []*topo.ShardInfo, keyResolver keyspaceIDResolver) *RowSplitter {
result := &RowSplitter{
KeyResolver: keyResolver,
KeyRanges: make([]*topodatapb.KeyRange, len(shardInfos)),
}
for i, si := range shardInfos {
result.KeyRanges[i] = si.KeyRange
}
return result
} | go | func NewRowSplitter(shardInfos []*topo.ShardInfo, keyResolver keyspaceIDResolver) *RowSplitter {
result := &RowSplitter{
KeyResolver: keyResolver,
KeyRanges: make([]*topodatapb.KeyRange, len(shardInfos)),
}
for i, si := range shardInfos {
result.KeyRanges[i] = si.KeyRange
}
return result
} | [
"func",
"NewRowSplitter",
"(",
"shardInfos",
"[",
"]",
"*",
"topo",
".",
"ShardInfo",
",",
"keyResolver",
"keyspaceIDResolver",
")",
"*",
"RowSplitter",
"{",
"result",
":=",
"&",
"RowSplitter",
"{",
"KeyResolver",
":",
"keyResolver",
",",
"KeyRanges",
":",
"make",
"(",
"[",
"]",
"*",
"topodatapb",
".",
"KeyRange",
",",
"len",
"(",
"shardInfos",
")",
")",
",",
"}",
"\n",
"for",
"i",
",",
"si",
":=",
"range",
"shardInfos",
"{",
"result",
".",
"KeyRanges",
"[",
"i",
"]",
"=",
"si",
".",
"KeyRange",
"\n",
"}",
"\n",
"return",
"result",
"\n",
"}"
] | // NewRowSplitter returns a new row splitter for the given shard distribution. | [
"NewRowSplitter",
"returns",
"a",
"new",
"row",
"splitter",
"for",
"the",
"given",
"shard",
"distribution",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/legacy_row_splitter.go#L39-L48 | train |
vitessio/vitess | go/vt/worker/legacy_row_splitter.go | StartSplit | func (rs *RowSplitter) StartSplit() [][][]sqltypes.Value {
return make([][][]sqltypes.Value, len(rs.KeyRanges))
} | go | func (rs *RowSplitter) StartSplit() [][][]sqltypes.Value {
return make([][][]sqltypes.Value, len(rs.KeyRanges))
} | [
"func",
"(",
"rs",
"*",
"RowSplitter",
")",
"StartSplit",
"(",
")",
"[",
"]",
"[",
"]",
"[",
"]",
"sqltypes",
".",
"Value",
"{",
"return",
"make",
"(",
"[",
"]",
"[",
"]",
"[",
"]",
"sqltypes",
".",
"Value",
",",
"len",
"(",
"rs",
".",
"KeyRanges",
")",
")",
"\n",
"}"
] | // StartSplit starts a new split. Split can then be called multiple times. | [
"StartSplit",
"starts",
"a",
"new",
"split",
".",
"Split",
"can",
"then",
"be",
"called",
"multiple",
"times",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/legacy_row_splitter.go#L51-L53 | train |
vitessio/vitess | go/vt/worker/legacy_row_splitter.go | Split | func (rs *RowSplitter) Split(result [][][]sqltypes.Value, rows [][]sqltypes.Value) error {
for _, row := range rows {
k, err := rs.KeyResolver.keyspaceID(row)
if err != nil {
return err
}
for i, kr := range rs.KeyRanges {
if key.KeyRangeContains(kr, k) {
result[i] = append(result[i], row)
break
}
}
}
return nil
} | go | func (rs *RowSplitter) Split(result [][][]sqltypes.Value, rows [][]sqltypes.Value) error {
for _, row := range rows {
k, err := rs.KeyResolver.keyspaceID(row)
if err != nil {
return err
}
for i, kr := range rs.KeyRanges {
if key.KeyRangeContains(kr, k) {
result[i] = append(result[i], row)
break
}
}
}
return nil
} | [
"func",
"(",
"rs",
"*",
"RowSplitter",
")",
"Split",
"(",
"result",
"[",
"]",
"[",
"]",
"[",
"]",
"sqltypes",
".",
"Value",
",",
"rows",
"[",
"]",
"[",
"]",
"sqltypes",
".",
"Value",
")",
"error",
"{",
"for",
"_",
",",
"row",
":=",
"range",
"rows",
"{",
"k",
",",
"err",
":=",
"rs",
".",
"KeyResolver",
".",
"keyspaceID",
"(",
"row",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"i",
",",
"kr",
":=",
"range",
"rs",
".",
"KeyRanges",
"{",
"if",
"key",
".",
"KeyRangeContains",
"(",
"kr",
",",
"k",
")",
"{",
"result",
"[",
"i",
"]",
"=",
"append",
"(",
"result",
"[",
"i",
"]",
",",
"row",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Split will split the rows into subset for each distribution | [
"Split",
"will",
"split",
"the",
"rows",
"into",
"subset",
"for",
"each",
"distribution"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/legacy_row_splitter.go#L56-L70 | train |
vitessio/vitess | go/vt/worker/legacy_row_splitter.go | Send | func (rs *RowSplitter) Send(fields []*querypb.Field, result [][][]sqltypes.Value, baseCmds []string, insertChannels []chan string, abort <-chan struct{}) bool {
for i, c := range insertChannels {
// one of the chunks might be empty, so no need
// to send data in that case
if len(result[i]) > 0 {
cmd := baseCmds[i] + makeValueString(fields, result[i])
// also check on abort, so we don't wait forever
select {
case c <- cmd:
case <-abort:
return true
}
}
}
return false
} | go | func (rs *RowSplitter) Send(fields []*querypb.Field, result [][][]sqltypes.Value, baseCmds []string, insertChannels []chan string, abort <-chan struct{}) bool {
for i, c := range insertChannels {
// one of the chunks might be empty, so no need
// to send data in that case
if len(result[i]) > 0 {
cmd := baseCmds[i] + makeValueString(fields, result[i])
// also check on abort, so we don't wait forever
select {
case c <- cmd:
case <-abort:
return true
}
}
}
return false
} | [
"func",
"(",
"rs",
"*",
"RowSplitter",
")",
"Send",
"(",
"fields",
"[",
"]",
"*",
"querypb",
".",
"Field",
",",
"result",
"[",
"]",
"[",
"]",
"[",
"]",
"sqltypes",
".",
"Value",
",",
"baseCmds",
"[",
"]",
"string",
",",
"insertChannels",
"[",
"]",
"chan",
"string",
",",
"abort",
"<-",
"chan",
"struct",
"{",
"}",
")",
"bool",
"{",
"for",
"i",
",",
"c",
":=",
"range",
"insertChannels",
"{",
"// one of the chunks might be empty, so no need",
"// to send data in that case",
"if",
"len",
"(",
"result",
"[",
"i",
"]",
")",
">",
"0",
"{",
"cmd",
":=",
"baseCmds",
"[",
"i",
"]",
"+",
"makeValueString",
"(",
"fields",
",",
"result",
"[",
"i",
"]",
")",
"\n",
"// also check on abort, so we don't wait forever",
"select",
"{",
"case",
"c",
"<-",
"cmd",
":",
"case",
"<-",
"abort",
":",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // Send will send the rows to the list of channels. Returns true if aborted. | [
"Send",
"will",
"send",
"the",
"rows",
"to",
"the",
"list",
"of",
"channels",
".",
"Returns",
"true",
"if",
"aborted",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/legacy_row_splitter.go#L73-L88 | train |
vitessio/vitess | go/vt/vttablet/heartbeat/writer.go | NewWriter | func NewWriter(checker connpool.MySQLChecker, alias topodatapb.TabletAlias, config tabletenv.TabletConfig) *Writer {
if !config.HeartbeatEnable {
return &Writer{}
}
return &Writer{
enabled: true,
tabletAlias: alias,
now: time.Now,
interval: config.HeartbeatInterval,
ticks: timer.NewTimer(config.HeartbeatInterval),
errorLog: logutil.NewThrottledLogger("HeartbeatWriter", 60*time.Second),
pool: connpool.New(config.PoolNamePrefix+"HeartbeatWritePool", 1, time.Duration(config.IdleTimeout*1e9), checker),
}
} | go | func NewWriter(checker connpool.MySQLChecker, alias topodatapb.TabletAlias, config tabletenv.TabletConfig) *Writer {
if !config.HeartbeatEnable {
return &Writer{}
}
return &Writer{
enabled: true,
tabletAlias: alias,
now: time.Now,
interval: config.HeartbeatInterval,
ticks: timer.NewTimer(config.HeartbeatInterval),
errorLog: logutil.NewThrottledLogger("HeartbeatWriter", 60*time.Second),
pool: connpool.New(config.PoolNamePrefix+"HeartbeatWritePool", 1, time.Duration(config.IdleTimeout*1e9), checker),
}
} | [
"func",
"NewWriter",
"(",
"checker",
"connpool",
".",
"MySQLChecker",
",",
"alias",
"topodatapb",
".",
"TabletAlias",
",",
"config",
"tabletenv",
".",
"TabletConfig",
")",
"*",
"Writer",
"{",
"if",
"!",
"config",
".",
"HeartbeatEnable",
"{",
"return",
"&",
"Writer",
"{",
"}",
"\n",
"}",
"\n",
"return",
"&",
"Writer",
"{",
"enabled",
":",
"true",
",",
"tabletAlias",
":",
"alias",
",",
"now",
":",
"time",
".",
"Now",
",",
"interval",
":",
"config",
".",
"HeartbeatInterval",
",",
"ticks",
":",
"timer",
".",
"NewTimer",
"(",
"config",
".",
"HeartbeatInterval",
")",
",",
"errorLog",
":",
"logutil",
".",
"NewThrottledLogger",
"(",
"\"",
"\"",
",",
"60",
"*",
"time",
".",
"Second",
")",
",",
"pool",
":",
"connpool",
".",
"New",
"(",
"config",
".",
"PoolNamePrefix",
"+",
"\"",
"\"",
",",
"1",
",",
"time",
".",
"Duration",
"(",
"config",
".",
"IdleTimeout",
"*",
"1e9",
")",
",",
"checker",
")",
",",
"}",
"\n",
"}"
] | // NewWriter creates a new Writer. | [
"NewWriter",
"creates",
"a",
"new",
"Writer",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/heartbeat/writer.go#L77-L90 | train |
vitessio/vitess | go/vt/vttablet/heartbeat/writer.go | Init | func (w *Writer) Init(target querypb.Target) error {
if !w.enabled {
return nil
}
w.mu.Lock()
defer w.mu.Unlock()
log.Info("Initializing heartbeat table.")
w.dbName = sqlescape.EscapeID(w.dbconfigs.SidecarDBName.Get())
w.keyspaceShard = fmt.Sprintf("%s:%s", target.Keyspace, target.Shard)
err := w.initializeTables(w.dbconfigs.DbaWithDB())
if err != nil {
w.recordError(err)
return err
}
return nil
} | go | func (w *Writer) Init(target querypb.Target) error {
if !w.enabled {
return nil
}
w.mu.Lock()
defer w.mu.Unlock()
log.Info("Initializing heartbeat table.")
w.dbName = sqlescape.EscapeID(w.dbconfigs.SidecarDBName.Get())
w.keyspaceShard = fmt.Sprintf("%s:%s", target.Keyspace, target.Shard)
err := w.initializeTables(w.dbconfigs.DbaWithDB())
if err != nil {
w.recordError(err)
return err
}
return nil
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"Init",
"(",
"target",
"querypb",
".",
"Target",
")",
"error",
"{",
"if",
"!",
"w",
".",
"enabled",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"w",
".",
"dbName",
"=",
"sqlescape",
".",
"EscapeID",
"(",
"w",
".",
"dbconfigs",
".",
"SidecarDBName",
".",
"Get",
"(",
")",
")",
"\n",
"w",
".",
"keyspaceShard",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"target",
".",
"Keyspace",
",",
"target",
".",
"Shard",
")",
"\n",
"err",
":=",
"w",
".",
"initializeTables",
"(",
"w",
".",
"dbconfigs",
".",
"DbaWithDB",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"w",
".",
"recordError",
"(",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Init runs at tablet startup and last minute initialization of db settings, and
// creates the necessary tables for heartbeat. | [
"Init",
"runs",
"at",
"tablet",
"startup",
"and",
"last",
"minute",
"initialization",
"of",
"db",
"settings",
"and",
"creates",
"the",
"necessary",
"tables",
"for",
"heartbeat",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/heartbeat/writer.go#L99-L115 | train |
vitessio/vitess | go/vt/vttablet/heartbeat/writer.go | Open | func (w *Writer) Open() {
if !w.enabled {
return
}
w.mu.Lock()
defer w.mu.Unlock()
if w.isOpen {
return
}
log.Info("Beginning heartbeat writes")
w.pool.Open(w.dbconfigs.AppWithDB(), w.dbconfigs.DbaWithDB(), w.dbconfigs.AppDebugWithDB())
w.ticks.Start(func() { w.writeHeartbeat() })
w.isOpen = true
} | go | func (w *Writer) Open() {
if !w.enabled {
return
}
w.mu.Lock()
defer w.mu.Unlock()
if w.isOpen {
return
}
log.Info("Beginning heartbeat writes")
w.pool.Open(w.dbconfigs.AppWithDB(), w.dbconfigs.DbaWithDB(), w.dbconfigs.AppDebugWithDB())
w.ticks.Start(func() { w.writeHeartbeat() })
w.isOpen = true
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"Open",
"(",
")",
"{",
"if",
"!",
"w",
".",
"enabled",
"{",
"return",
"\n",
"}",
"\n",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"w",
".",
"isOpen",
"{",
"return",
"\n",
"}",
"\n",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"w",
".",
"pool",
".",
"Open",
"(",
"w",
".",
"dbconfigs",
".",
"AppWithDB",
"(",
")",
",",
"w",
".",
"dbconfigs",
".",
"DbaWithDB",
"(",
")",
",",
"w",
".",
"dbconfigs",
".",
"AppDebugWithDB",
"(",
")",
")",
"\n",
"w",
".",
"ticks",
".",
"Start",
"(",
"func",
"(",
")",
"{",
"w",
".",
"writeHeartbeat",
"(",
")",
"}",
")",
"\n",
"w",
".",
"isOpen",
"=",
"true",
"\n",
"}"
] | // Open sets up the Writer's db connection and launches the ticker
// responsible for periodically writing to the heartbeat table.
// Open may be called multiple times, as long as it was closed since
// last invocation. | [
"Open",
"sets",
"up",
"the",
"Writer",
"s",
"db",
"connection",
"and",
"launches",
"the",
"ticker",
"responsible",
"for",
"periodically",
"writing",
"to",
"the",
"heartbeat",
"table",
".",
"Open",
"may",
"be",
"called",
"multiple",
"times",
"as",
"long",
"as",
"it",
"was",
"closed",
"since",
"last",
"invocation",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/heartbeat/writer.go#L121-L134 | train |
vitessio/vitess | go/vt/vttablet/heartbeat/writer.go | Close | func (w *Writer) Close() {
if !w.enabled {
return
}
w.mu.Lock()
defer w.mu.Unlock()
if !w.isOpen {
return
}
w.ticks.Stop()
w.pool.Close()
log.Info("Stopped heartbeat writes.")
w.isOpen = false
} | go | func (w *Writer) Close() {
if !w.enabled {
return
}
w.mu.Lock()
defer w.mu.Unlock()
if !w.isOpen {
return
}
w.ticks.Stop()
w.pool.Close()
log.Info("Stopped heartbeat writes.")
w.isOpen = false
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"Close",
"(",
")",
"{",
"if",
"!",
"w",
".",
"enabled",
"{",
"return",
"\n",
"}",
"\n",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"!",
"w",
".",
"isOpen",
"{",
"return",
"\n",
"}",
"\n",
"w",
".",
"ticks",
".",
"Stop",
"(",
")",
"\n",
"w",
".",
"pool",
".",
"Close",
"(",
")",
"\n",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"w",
".",
"isOpen",
"=",
"false",
"\n",
"}"
] | // Close closes the Writer's db connection and stops the periodic ticker. A writer
// object can be re-opened after closing. | [
"Close",
"closes",
"the",
"Writer",
"s",
"db",
"connection",
"and",
"stops",
"the",
"periodic",
"ticker",
".",
"A",
"writer",
"object",
"can",
"be",
"re",
"-",
"opened",
"after",
"closing",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/heartbeat/writer.go#L138-L151 | train |
vitessio/vitess | go/vt/vttablet/heartbeat/writer.go | writeHeartbeat | func (w *Writer) writeHeartbeat() {
defer tabletenv.LogError()
ctx, cancel := context.WithDeadline(context.Background(), w.now().Add(w.interval))
defer cancel()
update, err := w.bindHeartbeatVars(sqlUpdateHeartbeat)
if err != nil {
w.recordError(err)
return
}
err = w.exec(ctx, update)
if err != nil {
w.recordError(err)
return
}
writes.Add(1)
} | go | func (w *Writer) writeHeartbeat() {
defer tabletenv.LogError()
ctx, cancel := context.WithDeadline(context.Background(), w.now().Add(w.interval))
defer cancel()
update, err := w.bindHeartbeatVars(sqlUpdateHeartbeat)
if err != nil {
w.recordError(err)
return
}
err = w.exec(ctx, update)
if err != nil {
w.recordError(err)
return
}
writes.Add(1)
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"writeHeartbeat",
"(",
")",
"{",
"defer",
"tabletenv",
".",
"LogError",
"(",
")",
"\n",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithDeadline",
"(",
"context",
".",
"Background",
"(",
")",
",",
"w",
".",
"now",
"(",
")",
".",
"Add",
"(",
"w",
".",
"interval",
")",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n",
"update",
",",
"err",
":=",
"w",
".",
"bindHeartbeatVars",
"(",
"sqlUpdateHeartbeat",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"w",
".",
"recordError",
"(",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"err",
"=",
"w",
".",
"exec",
"(",
"ctx",
",",
"update",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"w",
".",
"recordError",
"(",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"writes",
".",
"Add",
"(",
"1",
")",
"\n",
"}"
] | // writeHeartbeat updates the heartbeat row for this tablet with the current time in nanoseconds. | [
"writeHeartbeat",
"updates",
"the",
"heartbeat",
"row",
"for",
"this",
"tablet",
"with",
"the",
"current",
"time",
"in",
"nanoseconds",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/heartbeat/writer.go#L204-L219 | train |
vitessio/vitess | go/vt/workflow/topovalidator/validator.go | Run | func (w *Workflow) Run(ctx context.Context, manager *workflow.Manager, wi *topo.WorkflowInfo) error {
w.uiUpdate()
w.rootUINode.Display = workflow.NodeDisplayDeterminate
w.rootUINode.BroadcastChanges(false /* updateChildren */)
// Run all the validators. They may add fixers.
for name, v := range validators {
w.logger.Infof("Running validator: %v", name)
w.uiUpdate()
w.rootUINode.BroadcastChanges(false /* updateChildren */)
err := v.Audit(ctx, manager.TopoServer(), w)
if err != nil {
w.logger.Errorf("Validator %v failed: %v", name, err)
} else {
w.logger.Infof("Validator %v successfully finished", name)
}
w.runCount++
}
// Now for each Fixer, add a sub node.
if len(w.fixers) == 0 {
w.logger.Infof("No problem found")
}
for i, f := range w.fixers {
w.wg.Add(1)
f.node = workflow.NewNode()
w.rootUINode.Children = append(w.rootUINode.Children, f.node)
f.node.PathName = fmt.Sprintf("%v", i)
f.node.Name = f.name
f.node.Message = f.message
f.node.Display = workflow.NodeDisplayIndeterminate
for _, action := range f.actions {
f.node.Actions = append(f.node.Actions, &workflow.Action{
Name: action,
State: workflow.ActionStateEnabled,
Style: workflow.ActionStyleNormal,
})
}
f.node.Listener = f
}
w.uiUpdate()
w.rootUINode.BroadcastChanges(true /* updateChildren */)
// And wait for the workflow to be done.
fixersChan := make(chan struct{})
go func(wg *sync.WaitGroup) {
wg.Wait()
close(fixersChan)
}(&w.wg)
select {
case <-ctx.Done():
return ctx.Err()
case <-fixersChan:
return nil
}
} | go | func (w *Workflow) Run(ctx context.Context, manager *workflow.Manager, wi *topo.WorkflowInfo) error {
w.uiUpdate()
w.rootUINode.Display = workflow.NodeDisplayDeterminate
w.rootUINode.BroadcastChanges(false /* updateChildren */)
// Run all the validators. They may add fixers.
for name, v := range validators {
w.logger.Infof("Running validator: %v", name)
w.uiUpdate()
w.rootUINode.BroadcastChanges(false /* updateChildren */)
err := v.Audit(ctx, manager.TopoServer(), w)
if err != nil {
w.logger.Errorf("Validator %v failed: %v", name, err)
} else {
w.logger.Infof("Validator %v successfully finished", name)
}
w.runCount++
}
// Now for each Fixer, add a sub node.
if len(w.fixers) == 0 {
w.logger.Infof("No problem found")
}
for i, f := range w.fixers {
w.wg.Add(1)
f.node = workflow.NewNode()
w.rootUINode.Children = append(w.rootUINode.Children, f.node)
f.node.PathName = fmt.Sprintf("%v", i)
f.node.Name = f.name
f.node.Message = f.message
f.node.Display = workflow.NodeDisplayIndeterminate
for _, action := range f.actions {
f.node.Actions = append(f.node.Actions, &workflow.Action{
Name: action,
State: workflow.ActionStateEnabled,
Style: workflow.ActionStyleNormal,
})
}
f.node.Listener = f
}
w.uiUpdate()
w.rootUINode.BroadcastChanges(true /* updateChildren */)
// And wait for the workflow to be done.
fixersChan := make(chan struct{})
go func(wg *sync.WaitGroup) {
wg.Wait()
close(fixersChan)
}(&w.wg)
select {
case <-ctx.Done():
return ctx.Err()
case <-fixersChan:
return nil
}
} | [
"func",
"(",
"w",
"*",
"Workflow",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"manager",
"*",
"workflow",
".",
"Manager",
",",
"wi",
"*",
"topo",
".",
"WorkflowInfo",
")",
"error",
"{",
"w",
".",
"uiUpdate",
"(",
")",
"\n",
"w",
".",
"rootUINode",
".",
"Display",
"=",
"workflow",
".",
"NodeDisplayDeterminate",
"\n",
"w",
".",
"rootUINode",
".",
"BroadcastChanges",
"(",
"false",
"/* updateChildren */",
")",
"\n\n",
"// Run all the validators. They may add fixers.",
"for",
"name",
",",
"v",
":=",
"range",
"validators",
"{",
"w",
".",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"w",
".",
"uiUpdate",
"(",
")",
"\n",
"w",
".",
"rootUINode",
".",
"BroadcastChanges",
"(",
"false",
"/* updateChildren */",
")",
"\n",
"err",
":=",
"v",
".",
"Audit",
"(",
"ctx",
",",
"manager",
".",
"TopoServer",
"(",
")",
",",
"w",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"w",
".",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"w",
".",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"w",
".",
"runCount",
"++",
"\n",
"}",
"\n\n",
"// Now for each Fixer, add a sub node.",
"if",
"len",
"(",
"w",
".",
"fixers",
")",
"==",
"0",
"{",
"w",
".",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"i",
",",
"f",
":=",
"range",
"w",
".",
"fixers",
"{",
"w",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"f",
".",
"node",
"=",
"workflow",
".",
"NewNode",
"(",
")",
"\n",
"w",
".",
"rootUINode",
".",
"Children",
"=",
"append",
"(",
"w",
".",
"rootUINode",
".",
"Children",
",",
"f",
".",
"node",
")",
"\n",
"f",
".",
"node",
".",
"PathName",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"i",
")",
"\n",
"f",
".",
"node",
".",
"Name",
"=",
"f",
".",
"name",
"\n",
"f",
".",
"node",
".",
"Message",
"=",
"f",
".",
"message",
"\n",
"f",
".",
"node",
".",
"Display",
"=",
"workflow",
".",
"NodeDisplayIndeterminate",
"\n",
"for",
"_",
",",
"action",
":=",
"range",
"f",
".",
"actions",
"{",
"f",
".",
"node",
".",
"Actions",
"=",
"append",
"(",
"f",
".",
"node",
".",
"Actions",
",",
"&",
"workflow",
".",
"Action",
"{",
"Name",
":",
"action",
",",
"State",
":",
"workflow",
".",
"ActionStateEnabled",
",",
"Style",
":",
"workflow",
".",
"ActionStyleNormal",
",",
"}",
")",
"\n",
"}",
"\n",
"f",
".",
"node",
".",
"Listener",
"=",
"f",
"\n",
"}",
"\n",
"w",
".",
"uiUpdate",
"(",
")",
"\n",
"w",
".",
"rootUINode",
".",
"BroadcastChanges",
"(",
"true",
"/* updateChildren */",
")",
"\n\n",
"// And wait for the workflow to be done.",
"fixersChan",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"go",
"func",
"(",
"wg",
"*",
"sync",
".",
"WaitGroup",
")",
"{",
"wg",
".",
"Wait",
"(",
")",
"\n",
"close",
"(",
"fixersChan",
")",
"\n",
"}",
"(",
"&",
"w",
".",
"wg",
")",
"\n",
"select",
"{",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"ctx",
".",
"Err",
"(",
")",
"\n",
"case",
"<-",
"fixersChan",
":",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // Run is part of the workflow.Workflow interface. | [
"Run",
"is",
"part",
"of",
"the",
"workflow",
".",
"Workflow",
"interface",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/topovalidator/validator.go#L120-L175 | train |
vitessio/vitess | go/vt/workflow/topovalidator/validator.go | uiUpdate | func (w *Workflow) uiUpdate() {
c := len(validators)
w.rootUINode.Progress = 100 * w.runCount / c
w.rootUINode.ProgressMessage = fmt.Sprintf("%v/%v", w.runCount, c)
w.rootUINode.Log = w.logger.String()
} | go | func (w *Workflow) uiUpdate() {
c := len(validators)
w.rootUINode.Progress = 100 * w.runCount / c
w.rootUINode.ProgressMessage = fmt.Sprintf("%v/%v", w.runCount, c)
w.rootUINode.Log = w.logger.String()
} | [
"func",
"(",
"w",
"*",
"Workflow",
")",
"uiUpdate",
"(",
")",
"{",
"c",
":=",
"len",
"(",
"validators",
")",
"\n",
"w",
".",
"rootUINode",
".",
"Progress",
"=",
"100",
"*",
"w",
".",
"runCount",
"/",
"c",
"\n",
"w",
".",
"rootUINode",
".",
"ProgressMessage",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"w",
".",
"runCount",
",",
"c",
")",
"\n",
"w",
".",
"rootUINode",
".",
"Log",
"=",
"w",
".",
"logger",
".",
"String",
"(",
")",
"\n",
"}"
] | // uiUpdate updates the computed parts of the Node, based on the
// current state. | [
"uiUpdate",
"updates",
"the",
"computed",
"parts",
"of",
"the",
"Node",
"based",
"on",
"the",
"current",
"state",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/topovalidator/validator.go#L179-L184 | train |
vitessio/vitess | go/vt/vtgate/engine/primitive.go | AddStats | func (p *Plan) AddStats(execCount uint64, execTime time.Duration, shardQueries, rows, errors uint64) {
p.mu.Lock()
p.ExecCount += execCount
p.ExecTime += execTime
p.ShardQueries += shardQueries
p.Rows += rows
p.Errors += errors
p.mu.Unlock()
} | go | func (p *Plan) AddStats(execCount uint64, execTime time.Duration, shardQueries, rows, errors uint64) {
p.mu.Lock()
p.ExecCount += execCount
p.ExecTime += execTime
p.ShardQueries += shardQueries
p.Rows += rows
p.Errors += errors
p.mu.Unlock()
} | [
"func",
"(",
"p",
"*",
"Plan",
")",
"AddStats",
"(",
"execCount",
"uint64",
",",
"execTime",
"time",
".",
"Duration",
",",
"shardQueries",
",",
"rows",
",",
"errors",
"uint64",
")",
"{",
"p",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"p",
".",
"ExecCount",
"+=",
"execCount",
"\n",
"p",
".",
"ExecTime",
"+=",
"execTime",
"\n",
"p",
".",
"ShardQueries",
"+=",
"shardQueries",
"\n",
"p",
".",
"Rows",
"+=",
"rows",
"\n",
"p",
".",
"Errors",
"+=",
"errors",
"\n",
"p",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // AddStats updates the plan execution statistics | [
"AddStats",
"updates",
"the",
"plan",
"execution",
"statistics"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/engine/primitive.go#L94-L102 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/select.go | buildSelectPlan | func buildSelectPlan(sel *sqlparser.Select, vschema ContextVSchema) (primitive engine.Primitive, err error) {
pb := newPrimitiveBuilder(vschema, newJointab(sqlparser.GetBindvars(sel)))
if err := pb.processSelect(sel, nil); err != nil {
return nil, err
}
if err := pb.bldr.Wireup(pb.bldr, pb.jt); err != nil {
return nil, err
}
return pb.bldr.Primitive(), nil
} | go | func buildSelectPlan(sel *sqlparser.Select, vschema ContextVSchema) (primitive engine.Primitive, err error) {
pb := newPrimitiveBuilder(vschema, newJointab(sqlparser.GetBindvars(sel)))
if err := pb.processSelect(sel, nil); err != nil {
return nil, err
}
if err := pb.bldr.Wireup(pb.bldr, pb.jt); err != nil {
return nil, err
}
return pb.bldr.Primitive(), nil
} | [
"func",
"buildSelectPlan",
"(",
"sel",
"*",
"sqlparser",
".",
"Select",
",",
"vschema",
"ContextVSchema",
")",
"(",
"primitive",
"engine",
".",
"Primitive",
",",
"err",
"error",
")",
"{",
"pb",
":=",
"newPrimitiveBuilder",
"(",
"vschema",
",",
"newJointab",
"(",
"sqlparser",
".",
"GetBindvars",
"(",
"sel",
")",
")",
")",
"\n",
"if",
"err",
":=",
"pb",
".",
"processSelect",
"(",
"sel",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"pb",
".",
"bldr",
".",
"Wireup",
"(",
"pb",
".",
"bldr",
",",
"pb",
".",
"jt",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"pb",
".",
"bldr",
".",
"Primitive",
"(",
")",
",",
"nil",
"\n",
"}"
] | // buildSelectPlan is the new function to build a Select plan. | [
"buildSelectPlan",
"is",
"the",
"new",
"function",
"to",
"build",
"a",
"Select",
"plan",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/select.go#L28-L37 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/select.go | pushFilter | func (pb *primitiveBuilder) pushFilter(boolExpr sqlparser.Expr, whereType string) error {
filters := splitAndExpression(nil, boolExpr)
reorderBySubquery(filters)
for _, filter := range filters {
pullouts, origin, expr, err := pb.findOrigin(filter)
if err != nil {
return err
}
// The returned expression may be complex. Resplit before pushing.
for _, subexpr := range splitAndExpression(nil, expr) {
if err := pb.bldr.PushFilter(pb, subexpr, whereType, origin); err != nil {
return err
}
}
pb.addPullouts(pullouts)
}
return nil
} | go | func (pb *primitiveBuilder) pushFilter(boolExpr sqlparser.Expr, whereType string) error {
filters := splitAndExpression(nil, boolExpr)
reorderBySubquery(filters)
for _, filter := range filters {
pullouts, origin, expr, err := pb.findOrigin(filter)
if err != nil {
return err
}
// The returned expression may be complex. Resplit before pushing.
for _, subexpr := range splitAndExpression(nil, expr) {
if err := pb.bldr.PushFilter(pb, subexpr, whereType, origin); err != nil {
return err
}
}
pb.addPullouts(pullouts)
}
return nil
} | [
"func",
"(",
"pb",
"*",
"primitiveBuilder",
")",
"pushFilter",
"(",
"boolExpr",
"sqlparser",
".",
"Expr",
",",
"whereType",
"string",
")",
"error",
"{",
"filters",
":=",
"splitAndExpression",
"(",
"nil",
",",
"boolExpr",
")",
"\n",
"reorderBySubquery",
"(",
"filters",
")",
"\n",
"for",
"_",
",",
"filter",
":=",
"range",
"filters",
"{",
"pullouts",
",",
"origin",
",",
"expr",
",",
"err",
":=",
"pb",
".",
"findOrigin",
"(",
"filter",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// The returned expression may be complex. Resplit before pushing.",
"for",
"_",
",",
"subexpr",
":=",
"range",
"splitAndExpression",
"(",
"nil",
",",
"expr",
")",
"{",
"if",
"err",
":=",
"pb",
".",
"bldr",
".",
"PushFilter",
"(",
"pb",
",",
"subexpr",
",",
"whereType",
",",
"origin",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"pb",
".",
"addPullouts",
"(",
"pullouts",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // pushFilter identifies the target route for the specified bool expr,
// pushes it down, and updates the route info if the new constraint improves
// the primitive. This function can push to a WHERE or HAVING clause. | [
"pushFilter",
"identifies",
"the",
"target",
"route",
"for",
"the",
"specified",
"bool",
"expr",
"pushes",
"it",
"down",
"and",
"updates",
"the",
"route",
"info",
"if",
"the",
"new",
"constraint",
"improves",
"the",
"primitive",
".",
"This",
"function",
"can",
"push",
"to",
"a",
"WHERE",
"or",
"HAVING",
"clause",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/select.go#L127-L144 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/select.go | reorderBySubquery | func reorderBySubquery(filters []sqlparser.Expr) {
max := len(filters)
for i := 0; i < max; i++ {
if !hasSubquery(filters[i]) {
continue
}
saved := filters[i]
for j := i; j < len(filters)-1; j++ {
filters[j] = filters[j+1]
}
filters[len(filters)-1] = saved
max--
}
} | go | func reorderBySubquery(filters []sqlparser.Expr) {
max := len(filters)
for i := 0; i < max; i++ {
if !hasSubquery(filters[i]) {
continue
}
saved := filters[i]
for j := i; j < len(filters)-1; j++ {
filters[j] = filters[j+1]
}
filters[len(filters)-1] = saved
max--
}
} | [
"func",
"reorderBySubquery",
"(",
"filters",
"[",
"]",
"sqlparser",
".",
"Expr",
")",
"{",
"max",
":=",
"len",
"(",
"filters",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"max",
";",
"i",
"++",
"{",
"if",
"!",
"hasSubquery",
"(",
"filters",
"[",
"i",
"]",
")",
"{",
"continue",
"\n",
"}",
"\n",
"saved",
":=",
"filters",
"[",
"i",
"]",
"\n",
"for",
"j",
":=",
"i",
";",
"j",
"<",
"len",
"(",
"filters",
")",
"-",
"1",
";",
"j",
"++",
"{",
"filters",
"[",
"j",
"]",
"=",
"filters",
"[",
"j",
"+",
"1",
"]",
"\n",
"}",
"\n",
"filters",
"[",
"len",
"(",
"filters",
")",
"-",
"1",
"]",
"=",
"saved",
"\n",
"max",
"--",
"\n",
"}",
"\n",
"}"
] | // reorderBySubquery reorders the filters by pushing subqueries
// to the end. This allows the non-subquery filters to be
// pushed first because they can potentially improve the routing
// plan, which can later allow a filter containing a subquery
// to successfully merge with the corresponding route. | [
"reorderBySubquery",
"reorders",
"the",
"filters",
"by",
"pushing",
"subqueries",
"to",
"the",
"end",
".",
"This",
"allows",
"the",
"non",
"-",
"subquery",
"filters",
"to",
"be",
"pushed",
"first",
"because",
"they",
"can",
"potentially",
"improve",
"the",
"routing",
"plan",
"which",
"can",
"later",
"allow",
"a",
"filter",
"containing",
"a",
"subquery",
"to",
"successfully",
"merge",
"with",
"the",
"corresponding",
"route",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/select.go#L151-L164 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/select.go | addPullouts | func (pb *primitiveBuilder) addPullouts(pullouts []*pulloutSubquery) {
for _, pullout := range pullouts {
pullout.setUnderlying(pb.bldr)
pb.bldr = pullout
}
} | go | func (pb *primitiveBuilder) addPullouts(pullouts []*pulloutSubquery) {
for _, pullout := range pullouts {
pullout.setUnderlying(pb.bldr)
pb.bldr = pullout
}
} | [
"func",
"(",
"pb",
"*",
"primitiveBuilder",
")",
"addPullouts",
"(",
"pullouts",
"[",
"]",
"*",
"pulloutSubquery",
")",
"{",
"for",
"_",
",",
"pullout",
":=",
"range",
"pullouts",
"{",
"pullout",
".",
"setUnderlying",
"(",
"pb",
".",
"bldr",
")",
"\n",
"pb",
".",
"bldr",
"=",
"pullout",
"\n",
"}",
"\n",
"}"
] | // addPullouts adds the pullout subqueries to the primitiveBuilder. | [
"addPullouts",
"adds",
"the",
"pullout",
"subqueries",
"to",
"the",
"primitiveBuilder",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/select.go#L167-L172 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/select.go | pushSelectExprs | func (pb *primitiveBuilder) pushSelectExprs(sel *sqlparser.Select, grouper groupByHandler) error {
resultColumns, err := pb.pushSelectRoutes(sel.SelectExprs)
if err != nil {
return err
}
pb.st.SetResultColumns(resultColumns)
return pb.pushGroupBy(sel, grouper)
} | go | func (pb *primitiveBuilder) pushSelectExprs(sel *sqlparser.Select, grouper groupByHandler) error {
resultColumns, err := pb.pushSelectRoutes(sel.SelectExprs)
if err != nil {
return err
}
pb.st.SetResultColumns(resultColumns)
return pb.pushGroupBy(sel, grouper)
} | [
"func",
"(",
"pb",
"*",
"primitiveBuilder",
")",
"pushSelectExprs",
"(",
"sel",
"*",
"sqlparser",
".",
"Select",
",",
"grouper",
"groupByHandler",
")",
"error",
"{",
"resultColumns",
",",
"err",
":=",
"pb",
".",
"pushSelectRoutes",
"(",
"sel",
".",
"SelectExprs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"pb",
".",
"st",
".",
"SetResultColumns",
"(",
"resultColumns",
")",
"\n",
"return",
"pb",
".",
"pushGroupBy",
"(",
"sel",
",",
"grouper",
")",
"\n",
"}"
] | // pushSelectExprs identifies the target route for the
// select expressions and pushes them down. | [
"pushSelectExprs",
"identifies",
"the",
"target",
"route",
"for",
"the",
"select",
"expressions",
"and",
"pushes",
"them",
"down",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/select.go#L176-L183 | train |
vitessio/vitess | go/vt/vtgate/planbuilder/select.go | pushSelectRoutes | func (pb *primitiveBuilder) pushSelectRoutes(selectExprs sqlparser.SelectExprs) ([]*resultColumn, error) {
resultColumns := make([]*resultColumn, 0, len(selectExprs))
for _, node := range selectExprs {
switch node := node.(type) {
case *sqlparser.AliasedExpr:
pullouts, origin, expr, err := pb.findOrigin(node.Expr)
if err != nil {
return nil, err
}
node.Expr = expr
rc, _, err := pb.bldr.PushSelect(node, origin)
if err != nil {
return nil, err
}
resultColumns = append(resultColumns, rc)
pb.addPullouts(pullouts)
case *sqlparser.StarExpr:
var expanded bool
var err error
resultColumns, expanded, err = pb.expandStar(resultColumns, node)
if err != nil {
return nil, err
}
if expanded {
continue
}
// We'll allow select * for simple routes.
rb, ok := pb.bldr.(*route)
if !ok {
return nil, errors.New("unsupported: '*' expression in cross-shard query")
}
// Validate keyspace reference if any.
if !node.TableName.IsEmpty() {
if _, err := pb.st.FindTable(node.TableName); err != nil {
return nil, err
}
}
resultColumns = append(resultColumns, rb.PushAnonymous(node))
case sqlparser.Nextval:
rb, ok := pb.bldr.(*route)
if !ok {
// This code is unreachable because the parser doesn't allow joins for next val statements.
return nil, errors.New("unsupported: SELECT NEXT query in cross-shard query")
}
for _, ro := range rb.routeOptions {
if ro.eroute.Opcode != engine.SelectNext {
return nil, errors.New("NEXT used on a non-sequence table")
}
ro.eroute.Opcode = engine.SelectNext
}
resultColumns = append(resultColumns, rb.PushAnonymous(node))
default:
panic(fmt.Sprintf("BUG: unexpceted select expression type: %T", node))
}
}
return resultColumns, nil
} | go | func (pb *primitiveBuilder) pushSelectRoutes(selectExprs sqlparser.SelectExprs) ([]*resultColumn, error) {
resultColumns := make([]*resultColumn, 0, len(selectExprs))
for _, node := range selectExprs {
switch node := node.(type) {
case *sqlparser.AliasedExpr:
pullouts, origin, expr, err := pb.findOrigin(node.Expr)
if err != nil {
return nil, err
}
node.Expr = expr
rc, _, err := pb.bldr.PushSelect(node, origin)
if err != nil {
return nil, err
}
resultColumns = append(resultColumns, rc)
pb.addPullouts(pullouts)
case *sqlparser.StarExpr:
var expanded bool
var err error
resultColumns, expanded, err = pb.expandStar(resultColumns, node)
if err != nil {
return nil, err
}
if expanded {
continue
}
// We'll allow select * for simple routes.
rb, ok := pb.bldr.(*route)
if !ok {
return nil, errors.New("unsupported: '*' expression in cross-shard query")
}
// Validate keyspace reference if any.
if !node.TableName.IsEmpty() {
if _, err := pb.st.FindTable(node.TableName); err != nil {
return nil, err
}
}
resultColumns = append(resultColumns, rb.PushAnonymous(node))
case sqlparser.Nextval:
rb, ok := pb.bldr.(*route)
if !ok {
// This code is unreachable because the parser doesn't allow joins for next val statements.
return nil, errors.New("unsupported: SELECT NEXT query in cross-shard query")
}
for _, ro := range rb.routeOptions {
if ro.eroute.Opcode != engine.SelectNext {
return nil, errors.New("NEXT used on a non-sequence table")
}
ro.eroute.Opcode = engine.SelectNext
}
resultColumns = append(resultColumns, rb.PushAnonymous(node))
default:
panic(fmt.Sprintf("BUG: unexpceted select expression type: %T", node))
}
}
return resultColumns, nil
} | [
"func",
"(",
"pb",
"*",
"primitiveBuilder",
")",
"pushSelectRoutes",
"(",
"selectExprs",
"sqlparser",
".",
"SelectExprs",
")",
"(",
"[",
"]",
"*",
"resultColumn",
",",
"error",
")",
"{",
"resultColumns",
":=",
"make",
"(",
"[",
"]",
"*",
"resultColumn",
",",
"0",
",",
"len",
"(",
"selectExprs",
")",
")",
"\n",
"for",
"_",
",",
"node",
":=",
"range",
"selectExprs",
"{",
"switch",
"node",
":=",
"node",
".",
"(",
"type",
")",
"{",
"case",
"*",
"sqlparser",
".",
"AliasedExpr",
":",
"pullouts",
",",
"origin",
",",
"expr",
",",
"err",
":=",
"pb",
".",
"findOrigin",
"(",
"node",
".",
"Expr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"node",
".",
"Expr",
"=",
"expr",
"\n",
"rc",
",",
"_",
",",
"err",
":=",
"pb",
".",
"bldr",
".",
"PushSelect",
"(",
"node",
",",
"origin",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"resultColumns",
"=",
"append",
"(",
"resultColumns",
",",
"rc",
")",
"\n",
"pb",
".",
"addPullouts",
"(",
"pullouts",
")",
"\n",
"case",
"*",
"sqlparser",
".",
"StarExpr",
":",
"var",
"expanded",
"bool",
"\n",
"var",
"err",
"error",
"\n",
"resultColumns",
",",
"expanded",
",",
"err",
"=",
"pb",
".",
"expandStar",
"(",
"resultColumns",
",",
"node",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"expanded",
"{",
"continue",
"\n",
"}",
"\n",
"// We'll allow select * for simple routes.",
"rb",
",",
"ok",
":=",
"pb",
".",
"bldr",
".",
"(",
"*",
"route",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// Validate keyspace reference if any.",
"if",
"!",
"node",
".",
"TableName",
".",
"IsEmpty",
"(",
")",
"{",
"if",
"_",
",",
"err",
":=",
"pb",
".",
"st",
".",
"FindTable",
"(",
"node",
".",
"TableName",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"resultColumns",
"=",
"append",
"(",
"resultColumns",
",",
"rb",
".",
"PushAnonymous",
"(",
"node",
")",
")",
"\n",
"case",
"sqlparser",
".",
"Nextval",
":",
"rb",
",",
"ok",
":=",
"pb",
".",
"bldr",
".",
"(",
"*",
"route",
")",
"\n",
"if",
"!",
"ok",
"{",
"// This code is unreachable because the parser doesn't allow joins for next val statements.",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"ro",
":=",
"range",
"rb",
".",
"routeOptions",
"{",
"if",
"ro",
".",
"eroute",
".",
"Opcode",
"!=",
"engine",
".",
"SelectNext",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"ro",
".",
"eroute",
".",
"Opcode",
"=",
"engine",
".",
"SelectNext",
"\n",
"}",
"\n",
"resultColumns",
"=",
"append",
"(",
"resultColumns",
",",
"rb",
".",
"PushAnonymous",
"(",
"node",
")",
")",
"\n",
"default",
":",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"node",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"resultColumns",
",",
"nil",
"\n",
"}"
] | // pusheSelectRoutes is a convenience function that pushes all the select
// expressions and returns the list of resultColumns generated for it. | [
"pusheSelectRoutes",
"is",
"a",
"convenience",
"function",
"that",
"pushes",
"all",
"the",
"select",
"expressions",
"and",
"returns",
"the",
"list",
"of",
"resultColumns",
"generated",
"for",
"it",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/planbuilder/select.go#L187-L243 | train |
vitessio/vitess | go/mysql/client.go | Ping | func (c *Conn) Ping() error {
// This is a new command, need to reset the sequence.
c.sequence = 0
if err := c.writePacket([]byte{ComPing}); err != nil {
return NewSQLError(CRServerGone, SSUnknownSQLState, "%v", err)
}
data, err := c.readEphemeralPacket()
if err != nil {
return NewSQLError(CRServerLost, SSUnknownSQLState, "%v", err)
}
defer c.recycleReadPacket()
switch data[0] {
case OKPacket:
return nil
case ErrPacket:
return ParseErrorPacket(data)
}
return vterrors.Errorf(vtrpc.Code_INTERNAL, "unexpected packet type: %d", data[0])
} | go | func (c *Conn) Ping() error {
// This is a new command, need to reset the sequence.
c.sequence = 0
if err := c.writePacket([]byte{ComPing}); err != nil {
return NewSQLError(CRServerGone, SSUnknownSQLState, "%v", err)
}
data, err := c.readEphemeralPacket()
if err != nil {
return NewSQLError(CRServerLost, SSUnknownSQLState, "%v", err)
}
defer c.recycleReadPacket()
switch data[0] {
case OKPacket:
return nil
case ErrPacket:
return ParseErrorPacket(data)
}
return vterrors.Errorf(vtrpc.Code_INTERNAL, "unexpected packet type: %d", data[0])
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"Ping",
"(",
")",
"error",
"{",
"// This is a new command, need to reset the sequence.",
"c",
".",
"sequence",
"=",
"0",
"\n\n",
"if",
"err",
":=",
"c",
".",
"writePacket",
"(",
"[",
"]",
"byte",
"{",
"ComPing",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"NewSQLError",
"(",
"CRServerGone",
",",
"SSUnknownSQLState",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"data",
",",
"err",
":=",
"c",
".",
"readEphemeralPacket",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"NewSQLError",
"(",
"CRServerLost",
",",
"SSUnknownSQLState",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"c",
".",
"recycleReadPacket",
"(",
")",
"\n",
"switch",
"data",
"[",
"0",
"]",
"{",
"case",
"OKPacket",
":",
"return",
"nil",
"\n",
"case",
"ErrPacket",
":",
"return",
"ParseErrorPacket",
"(",
"data",
")",
"\n",
"}",
"\n",
"return",
"vterrors",
".",
"Errorf",
"(",
"vtrpc",
".",
"Code_INTERNAL",
",",
"\"",
"\"",
",",
"data",
"[",
"0",
"]",
")",
"\n",
"}"
] | // Ping implements mysql ping command. | [
"Ping",
"implements",
"mysql",
"ping",
"command",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/client.go#L172-L191 | train |
vitessio/vitess | go/mysql/client.go | writeSSLRequest | func (c *Conn) writeSSLRequest(capabilities uint32, characterSet uint8, params *ConnParams) error {
// Build our flags, with CapabilityClientSSL.
var flags uint32 = CapabilityClientLongPassword |
CapabilityClientLongFlag |
CapabilityClientProtocol41 |
CapabilityClientTransactions |
CapabilityClientSecureConnection |
CapabilityClientMultiStatements |
CapabilityClientMultiResults |
CapabilityClientPluginAuth |
CapabilityClientPluginAuthLenencClientData |
CapabilityClientSSL |
// If the server supported
// CapabilityClientDeprecateEOF, we also support it.
c.Capabilities&CapabilityClientDeprecateEOF |
// Pass-through ClientFoundRows flag.
CapabilityClientFoundRows&uint32(params.Flags)
length :=
4 + // Client capability flags.
4 + // Max-packet size.
1 + // Character set.
23 // Reserved.
// Add the DB name if the server supports it.
if params.DbName != "" && (capabilities&CapabilityClientConnectWithDB != 0) {
flags |= CapabilityClientConnectWithDB
}
data := c.startEphemeralPacket(length)
pos := 0
// Client capability flags.
pos = writeUint32(data, pos, flags)
// Max-packet size, always 0. See doc.go.
pos = writeZeroes(data, pos, 4)
// Character set.
_ = writeByte(data, pos, characterSet)
// And send it as is.
if err := c.writeEphemeralPacket(); err != nil {
return NewSQLError(CRServerLost, SSUnknownSQLState, "cannot send SSLRequest: %v", err)
}
return nil
} | go | func (c *Conn) writeSSLRequest(capabilities uint32, characterSet uint8, params *ConnParams) error {
// Build our flags, with CapabilityClientSSL.
var flags uint32 = CapabilityClientLongPassword |
CapabilityClientLongFlag |
CapabilityClientProtocol41 |
CapabilityClientTransactions |
CapabilityClientSecureConnection |
CapabilityClientMultiStatements |
CapabilityClientMultiResults |
CapabilityClientPluginAuth |
CapabilityClientPluginAuthLenencClientData |
CapabilityClientSSL |
// If the server supported
// CapabilityClientDeprecateEOF, we also support it.
c.Capabilities&CapabilityClientDeprecateEOF |
// Pass-through ClientFoundRows flag.
CapabilityClientFoundRows&uint32(params.Flags)
length :=
4 + // Client capability flags.
4 + // Max-packet size.
1 + // Character set.
23 // Reserved.
// Add the DB name if the server supports it.
if params.DbName != "" && (capabilities&CapabilityClientConnectWithDB != 0) {
flags |= CapabilityClientConnectWithDB
}
data := c.startEphemeralPacket(length)
pos := 0
// Client capability flags.
pos = writeUint32(data, pos, flags)
// Max-packet size, always 0. See doc.go.
pos = writeZeroes(data, pos, 4)
// Character set.
_ = writeByte(data, pos, characterSet)
// And send it as is.
if err := c.writeEphemeralPacket(); err != nil {
return NewSQLError(CRServerLost, SSUnknownSQLState, "cannot send SSLRequest: %v", err)
}
return nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"writeSSLRequest",
"(",
"capabilities",
"uint32",
",",
"characterSet",
"uint8",
",",
"params",
"*",
"ConnParams",
")",
"error",
"{",
"// Build our flags, with CapabilityClientSSL.",
"var",
"flags",
"uint32",
"=",
"CapabilityClientLongPassword",
"|",
"CapabilityClientLongFlag",
"|",
"CapabilityClientProtocol41",
"|",
"CapabilityClientTransactions",
"|",
"CapabilityClientSecureConnection",
"|",
"CapabilityClientMultiStatements",
"|",
"CapabilityClientMultiResults",
"|",
"CapabilityClientPluginAuth",
"|",
"CapabilityClientPluginAuthLenencClientData",
"|",
"CapabilityClientSSL",
"|",
"// If the server supported",
"// CapabilityClientDeprecateEOF, we also support it.",
"c",
".",
"Capabilities",
"&",
"CapabilityClientDeprecateEOF",
"|",
"// Pass-through ClientFoundRows flag.",
"CapabilityClientFoundRows",
"&",
"uint32",
"(",
"params",
".",
"Flags",
")",
"\n\n",
"length",
":=",
"4",
"+",
"// Client capability flags.",
"4",
"+",
"// Max-packet size.",
"1",
"+",
"// Character set.",
"23",
"// Reserved.",
"\n\n",
"// Add the DB name if the server supports it.",
"if",
"params",
".",
"DbName",
"!=",
"\"",
"\"",
"&&",
"(",
"capabilities",
"&",
"CapabilityClientConnectWithDB",
"!=",
"0",
")",
"{",
"flags",
"|=",
"CapabilityClientConnectWithDB",
"\n",
"}",
"\n\n",
"data",
":=",
"c",
".",
"startEphemeralPacket",
"(",
"length",
")",
"\n",
"pos",
":=",
"0",
"\n\n",
"// Client capability flags.",
"pos",
"=",
"writeUint32",
"(",
"data",
",",
"pos",
",",
"flags",
")",
"\n\n",
"// Max-packet size, always 0. See doc.go.",
"pos",
"=",
"writeZeroes",
"(",
"data",
",",
"pos",
",",
"4",
")",
"\n\n",
"// Character set.",
"_",
"=",
"writeByte",
"(",
"data",
",",
"pos",
",",
"characterSet",
")",
"\n\n",
"// And send it as is.",
"if",
"err",
":=",
"c",
".",
"writeEphemeralPacket",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"NewSQLError",
"(",
"CRServerLost",
",",
"SSUnknownSQLState",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // writeSSLRequest writes the SSLRequest packet. It's just a truncated
// HandshakeResponse41. | [
"writeSSLRequest",
"writes",
"the",
"SSLRequest",
"packet",
".",
"It",
"s",
"just",
"a",
"truncated",
"HandshakeResponse41",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/client.go#L495-L541 | train |
vitessio/vitess | go/mysql/client.go | writeHandshakeResponse41 | func (c *Conn) writeHandshakeResponse41(capabilities uint32, scrambledPassword []byte, characterSet uint8, params *ConnParams) error {
// Build our flags.
var flags uint32 = CapabilityClientLongPassword |
CapabilityClientLongFlag |
CapabilityClientProtocol41 |
CapabilityClientTransactions |
CapabilityClientSecureConnection |
CapabilityClientMultiStatements |
CapabilityClientMultiResults |
CapabilityClientPluginAuth |
CapabilityClientPluginAuthLenencClientData |
// If the server supported
// CapabilityClientDeprecateEOF, we also support it.
c.Capabilities&CapabilityClientDeprecateEOF |
// Pass-through ClientFoundRows flag.
CapabilityClientFoundRows&uint32(params.Flags)
// FIXME(alainjobart) add multi statement.
length :=
4 + // Client capability flags.
4 + // Max-packet size.
1 + // Character set.
23 + // Reserved.
lenNullString(params.Uname) +
// length of scrambled passsword is handled below.
len(scrambledPassword) +
21 + // "mysql_native_password" string.
1 // terminating zero.
// Add the DB name if the server supports it.
if params.DbName != "" && (capabilities&CapabilityClientConnectWithDB != 0) {
flags |= CapabilityClientConnectWithDB
length += lenNullString(params.DbName)
}
if capabilities&CapabilityClientPluginAuthLenencClientData != 0 {
length += lenEncIntSize(uint64(len(scrambledPassword)))
} else {
length++
}
data := c.startEphemeralPacket(length)
pos := 0
// Client capability flags.
pos = writeUint32(data, pos, flags)
// Max-packet size, always 0. See doc.go.
pos = writeZeroes(data, pos, 4)
// Character set.
pos = writeByte(data, pos, characterSet)
// 23 reserved bytes, all 0.
pos = writeZeroes(data, pos, 23)
// Username
pos = writeNullString(data, pos, params.Uname)
// Scrambled password. The length is encoded as variable length if
// CapabilityClientPluginAuthLenencClientData is set.
if capabilities&CapabilityClientPluginAuthLenencClientData != 0 {
pos = writeLenEncInt(data, pos, uint64(len(scrambledPassword)))
} else {
data[pos] = byte(len(scrambledPassword))
pos++
}
pos += copy(data[pos:], scrambledPassword)
// DbName, only if server supports it.
if params.DbName != "" && (capabilities&CapabilityClientConnectWithDB != 0) {
pos = writeNullString(data, pos, params.DbName)
c.SchemaName = params.DbName
}
// Assume native client during response
pos = writeNullString(data, pos, MysqlNativePassword)
// Sanity-check the length.
if pos != len(data) {
return NewSQLError(CRMalformedPacket, SSUnknownSQLState, "writeHandshakeResponse41: only packed %v bytes, out of %v allocated", pos, len(data))
}
if err := c.writeEphemeralPacket(); err != nil {
return NewSQLError(CRServerLost, SSUnknownSQLState, "cannot send HandshakeResponse41: %v", err)
}
return nil
} | go | func (c *Conn) writeHandshakeResponse41(capabilities uint32, scrambledPassword []byte, characterSet uint8, params *ConnParams) error {
// Build our flags.
var flags uint32 = CapabilityClientLongPassword |
CapabilityClientLongFlag |
CapabilityClientProtocol41 |
CapabilityClientTransactions |
CapabilityClientSecureConnection |
CapabilityClientMultiStatements |
CapabilityClientMultiResults |
CapabilityClientPluginAuth |
CapabilityClientPluginAuthLenencClientData |
// If the server supported
// CapabilityClientDeprecateEOF, we also support it.
c.Capabilities&CapabilityClientDeprecateEOF |
// Pass-through ClientFoundRows flag.
CapabilityClientFoundRows&uint32(params.Flags)
// FIXME(alainjobart) add multi statement.
length :=
4 + // Client capability flags.
4 + // Max-packet size.
1 + // Character set.
23 + // Reserved.
lenNullString(params.Uname) +
// length of scrambled passsword is handled below.
len(scrambledPassword) +
21 + // "mysql_native_password" string.
1 // terminating zero.
// Add the DB name if the server supports it.
if params.DbName != "" && (capabilities&CapabilityClientConnectWithDB != 0) {
flags |= CapabilityClientConnectWithDB
length += lenNullString(params.DbName)
}
if capabilities&CapabilityClientPluginAuthLenencClientData != 0 {
length += lenEncIntSize(uint64(len(scrambledPassword)))
} else {
length++
}
data := c.startEphemeralPacket(length)
pos := 0
// Client capability flags.
pos = writeUint32(data, pos, flags)
// Max-packet size, always 0. See doc.go.
pos = writeZeroes(data, pos, 4)
// Character set.
pos = writeByte(data, pos, characterSet)
// 23 reserved bytes, all 0.
pos = writeZeroes(data, pos, 23)
// Username
pos = writeNullString(data, pos, params.Uname)
// Scrambled password. The length is encoded as variable length if
// CapabilityClientPluginAuthLenencClientData is set.
if capabilities&CapabilityClientPluginAuthLenencClientData != 0 {
pos = writeLenEncInt(data, pos, uint64(len(scrambledPassword)))
} else {
data[pos] = byte(len(scrambledPassword))
pos++
}
pos += copy(data[pos:], scrambledPassword)
// DbName, only if server supports it.
if params.DbName != "" && (capabilities&CapabilityClientConnectWithDB != 0) {
pos = writeNullString(data, pos, params.DbName)
c.SchemaName = params.DbName
}
// Assume native client during response
pos = writeNullString(data, pos, MysqlNativePassword)
// Sanity-check the length.
if pos != len(data) {
return NewSQLError(CRMalformedPacket, SSUnknownSQLState, "writeHandshakeResponse41: only packed %v bytes, out of %v allocated", pos, len(data))
}
if err := c.writeEphemeralPacket(); err != nil {
return NewSQLError(CRServerLost, SSUnknownSQLState, "cannot send HandshakeResponse41: %v", err)
}
return nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"writeHandshakeResponse41",
"(",
"capabilities",
"uint32",
",",
"scrambledPassword",
"[",
"]",
"byte",
",",
"characterSet",
"uint8",
",",
"params",
"*",
"ConnParams",
")",
"error",
"{",
"// Build our flags.",
"var",
"flags",
"uint32",
"=",
"CapabilityClientLongPassword",
"|",
"CapabilityClientLongFlag",
"|",
"CapabilityClientProtocol41",
"|",
"CapabilityClientTransactions",
"|",
"CapabilityClientSecureConnection",
"|",
"CapabilityClientMultiStatements",
"|",
"CapabilityClientMultiResults",
"|",
"CapabilityClientPluginAuth",
"|",
"CapabilityClientPluginAuthLenencClientData",
"|",
"// If the server supported",
"// CapabilityClientDeprecateEOF, we also support it.",
"c",
".",
"Capabilities",
"&",
"CapabilityClientDeprecateEOF",
"|",
"// Pass-through ClientFoundRows flag.",
"CapabilityClientFoundRows",
"&",
"uint32",
"(",
"params",
".",
"Flags",
")",
"\n\n",
"// FIXME(alainjobart) add multi statement.",
"length",
":=",
"4",
"+",
"// Client capability flags.",
"4",
"+",
"// Max-packet size.",
"1",
"+",
"// Character set.",
"23",
"+",
"// Reserved.",
"lenNullString",
"(",
"params",
".",
"Uname",
")",
"+",
"// length of scrambled passsword is handled below.",
"len",
"(",
"scrambledPassword",
")",
"+",
"21",
"+",
"// \"mysql_native_password\" string.",
"1",
"// terminating zero.",
"\n\n",
"// Add the DB name if the server supports it.",
"if",
"params",
".",
"DbName",
"!=",
"\"",
"\"",
"&&",
"(",
"capabilities",
"&",
"CapabilityClientConnectWithDB",
"!=",
"0",
")",
"{",
"flags",
"|=",
"CapabilityClientConnectWithDB",
"\n",
"length",
"+=",
"lenNullString",
"(",
"params",
".",
"DbName",
")",
"\n",
"}",
"\n\n",
"if",
"capabilities",
"&",
"CapabilityClientPluginAuthLenencClientData",
"!=",
"0",
"{",
"length",
"+=",
"lenEncIntSize",
"(",
"uint64",
"(",
"len",
"(",
"scrambledPassword",
")",
")",
")",
"\n",
"}",
"else",
"{",
"length",
"++",
"\n",
"}",
"\n\n",
"data",
":=",
"c",
".",
"startEphemeralPacket",
"(",
"length",
")",
"\n",
"pos",
":=",
"0",
"\n\n",
"// Client capability flags.",
"pos",
"=",
"writeUint32",
"(",
"data",
",",
"pos",
",",
"flags",
")",
"\n\n",
"// Max-packet size, always 0. See doc.go.",
"pos",
"=",
"writeZeroes",
"(",
"data",
",",
"pos",
",",
"4",
")",
"\n\n",
"// Character set.",
"pos",
"=",
"writeByte",
"(",
"data",
",",
"pos",
",",
"characterSet",
")",
"\n\n",
"// 23 reserved bytes, all 0.",
"pos",
"=",
"writeZeroes",
"(",
"data",
",",
"pos",
",",
"23",
")",
"\n\n",
"// Username",
"pos",
"=",
"writeNullString",
"(",
"data",
",",
"pos",
",",
"params",
".",
"Uname",
")",
"\n\n",
"// Scrambled password. The length is encoded as variable length if",
"// CapabilityClientPluginAuthLenencClientData is set.",
"if",
"capabilities",
"&",
"CapabilityClientPluginAuthLenencClientData",
"!=",
"0",
"{",
"pos",
"=",
"writeLenEncInt",
"(",
"data",
",",
"pos",
",",
"uint64",
"(",
"len",
"(",
"scrambledPassword",
")",
")",
")",
"\n",
"}",
"else",
"{",
"data",
"[",
"pos",
"]",
"=",
"byte",
"(",
"len",
"(",
"scrambledPassword",
")",
")",
"\n",
"pos",
"++",
"\n",
"}",
"\n",
"pos",
"+=",
"copy",
"(",
"data",
"[",
"pos",
":",
"]",
",",
"scrambledPassword",
")",
"\n\n",
"// DbName, only if server supports it.",
"if",
"params",
".",
"DbName",
"!=",
"\"",
"\"",
"&&",
"(",
"capabilities",
"&",
"CapabilityClientConnectWithDB",
"!=",
"0",
")",
"{",
"pos",
"=",
"writeNullString",
"(",
"data",
",",
"pos",
",",
"params",
".",
"DbName",
")",
"\n",
"c",
".",
"SchemaName",
"=",
"params",
".",
"DbName",
"\n",
"}",
"\n\n",
"// Assume native client during response",
"pos",
"=",
"writeNullString",
"(",
"data",
",",
"pos",
",",
"MysqlNativePassword",
")",
"\n\n",
"// Sanity-check the length.",
"if",
"pos",
"!=",
"len",
"(",
"data",
")",
"{",
"return",
"NewSQLError",
"(",
"CRMalformedPacket",
",",
"SSUnknownSQLState",
",",
"\"",
"\"",
",",
"pos",
",",
"len",
"(",
"data",
")",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"c",
".",
"writeEphemeralPacket",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"NewSQLError",
"(",
"CRServerLost",
",",
"SSUnknownSQLState",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // writeHandshakeResponse41 writes the handshake response.
// Returns a SQLError. | [
"writeHandshakeResponse41",
"writes",
"the",
"handshake",
"response",
".",
"Returns",
"a",
"SQLError",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/client.go#L545-L633 | train |
vitessio/vitess | go/mysql/client.go | writeClearTextPassword | func (c *Conn) writeClearTextPassword(params *ConnParams) error {
length := len(params.Pass) + 1
data := c.startEphemeralPacket(length)
pos := 0
pos = writeNullString(data, pos, params.Pass)
// Sanity check.
if pos != len(data) {
return vterrors.Errorf(vtrpc.Code_INTERNAL, "error building ClearTextPassword packet: got %v bytes expected %v", pos, len(data))
}
return c.writeEphemeralPacket()
} | go | func (c *Conn) writeClearTextPassword(params *ConnParams) error {
length := len(params.Pass) + 1
data := c.startEphemeralPacket(length)
pos := 0
pos = writeNullString(data, pos, params.Pass)
// Sanity check.
if pos != len(data) {
return vterrors.Errorf(vtrpc.Code_INTERNAL, "error building ClearTextPassword packet: got %v bytes expected %v", pos, len(data))
}
return c.writeEphemeralPacket()
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"writeClearTextPassword",
"(",
"params",
"*",
"ConnParams",
")",
"error",
"{",
"length",
":=",
"len",
"(",
"params",
".",
"Pass",
")",
"+",
"1",
"\n",
"data",
":=",
"c",
".",
"startEphemeralPacket",
"(",
"length",
")",
"\n",
"pos",
":=",
"0",
"\n",
"pos",
"=",
"writeNullString",
"(",
"data",
",",
"pos",
",",
"params",
".",
"Pass",
")",
"\n",
"// Sanity check.",
"if",
"pos",
"!=",
"len",
"(",
"data",
")",
"{",
"return",
"vterrors",
".",
"Errorf",
"(",
"vtrpc",
".",
"Code_INTERNAL",
",",
"\"",
"\"",
",",
"pos",
",",
"len",
"(",
"data",
")",
")",
"\n",
"}",
"\n",
"return",
"c",
".",
"writeEphemeralPacket",
"(",
")",
"\n",
"}"
] | // writeClearTextPassword writes the clear text password.
// Returns a SQLError. | [
"writeClearTextPassword",
"writes",
"the",
"clear",
"text",
"password",
".",
"Returns",
"a",
"SQLError",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/client.go#L647-L657 | train |
vitessio/vitess | go/vt/callinfo/plugin_grpc.go | GRPCCallInfo | func GRPCCallInfo(ctx context.Context) context.Context {
method, ok := grpc.Method(ctx)
if !ok {
return ctx
}
callinfo := &gRPCCallInfoImpl{
method: method,
}
peer, ok := peer.FromContext(ctx)
if ok {
callinfo.remoteAddr = peer.Addr.String()
}
return NewContext(ctx, callinfo)
} | go | func GRPCCallInfo(ctx context.Context) context.Context {
method, ok := grpc.Method(ctx)
if !ok {
return ctx
}
callinfo := &gRPCCallInfoImpl{
method: method,
}
peer, ok := peer.FromContext(ctx)
if ok {
callinfo.remoteAddr = peer.Addr.String()
}
return NewContext(ctx, callinfo)
} | [
"func",
"GRPCCallInfo",
"(",
"ctx",
"context",
".",
"Context",
")",
"context",
".",
"Context",
"{",
"method",
",",
"ok",
":=",
"grpc",
".",
"Method",
"(",
"ctx",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"ctx",
"\n",
"}",
"\n\n",
"callinfo",
":=",
"&",
"gRPCCallInfoImpl",
"{",
"method",
":",
"method",
",",
"}",
"\n",
"peer",
",",
"ok",
":=",
"peer",
".",
"FromContext",
"(",
"ctx",
")",
"\n",
"if",
"ok",
"{",
"callinfo",
".",
"remoteAddr",
"=",
"peer",
".",
"Addr",
".",
"String",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"NewContext",
"(",
"ctx",
",",
"callinfo",
")",
"\n",
"}"
] | // GRPCCallInfo returns an augmented context with a CallInfo structure,
// only for gRPC contexts. | [
"GRPCCallInfo",
"returns",
"an",
"augmented",
"context",
"with",
"a",
"CallInfo",
"structure",
"only",
"for",
"gRPC",
"contexts",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/callinfo/plugin_grpc.go#L32-L47 | train |
vitessio/vitess | go/vt/mysqlctl/grpcmysqlctlclient/client.go | Start | func (c *client) Start(ctx context.Context, mysqldArgs ...string) error {
return c.withRetry(ctx, func() error {
_, err := c.c.Start(ctx, &mysqlctlpb.StartRequest{
MysqldArgs: mysqldArgs,
})
return err
})
} | go | func (c *client) Start(ctx context.Context, mysqldArgs ...string) error {
return c.withRetry(ctx, func() error {
_, err := c.c.Start(ctx, &mysqlctlpb.StartRequest{
MysqldArgs: mysqldArgs,
})
return err
})
} | [
"func",
"(",
"c",
"*",
"client",
")",
"Start",
"(",
"ctx",
"context",
".",
"Context",
",",
"mysqldArgs",
"...",
"string",
")",
"error",
"{",
"return",
"c",
".",
"withRetry",
"(",
"ctx",
",",
"func",
"(",
")",
"error",
"{",
"_",
",",
"err",
":=",
"c",
".",
"c",
".",
"Start",
"(",
"ctx",
",",
"&",
"mysqlctlpb",
".",
"StartRequest",
"{",
"MysqldArgs",
":",
"mysqldArgs",
",",
"}",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"}"
] | // Start is part of the MysqlctlClient interface. | [
"Start",
"is",
"part",
"of",
"the",
"MysqlctlClient",
"interface",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/grpcmysqlctlclient/client.go#L60-L67 | train |
vitessio/vitess | go/vt/mysqlctl/grpcmysqlctlclient/client.go | Shutdown | func (c *client) Shutdown(ctx context.Context, waitForMysqld bool) error {
return c.withRetry(ctx, func() error {
_, err := c.c.Shutdown(ctx, &mysqlctlpb.ShutdownRequest{
WaitForMysqld: waitForMysqld,
})
return err
})
} | go | func (c *client) Shutdown(ctx context.Context, waitForMysqld bool) error {
return c.withRetry(ctx, func() error {
_, err := c.c.Shutdown(ctx, &mysqlctlpb.ShutdownRequest{
WaitForMysqld: waitForMysqld,
})
return err
})
} | [
"func",
"(",
"c",
"*",
"client",
")",
"Shutdown",
"(",
"ctx",
"context",
".",
"Context",
",",
"waitForMysqld",
"bool",
")",
"error",
"{",
"return",
"c",
".",
"withRetry",
"(",
"ctx",
",",
"func",
"(",
")",
"error",
"{",
"_",
",",
"err",
":=",
"c",
".",
"c",
".",
"Shutdown",
"(",
"ctx",
",",
"&",
"mysqlctlpb",
".",
"ShutdownRequest",
"{",
"WaitForMysqld",
":",
"waitForMysqld",
",",
"}",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"}"
] | // Shutdown is part of the MysqlctlClient interface. | [
"Shutdown",
"is",
"part",
"of",
"the",
"MysqlctlClient",
"interface",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/grpcmysqlctlclient/client.go#L70-L77 | train |
vitessio/vitess | go/vt/mysqlctl/grpcmysqlctlclient/client.go | RunMysqlUpgrade | func (c *client) RunMysqlUpgrade(ctx context.Context) error {
return c.withRetry(ctx, func() error {
_, err := c.c.RunMysqlUpgrade(ctx, &mysqlctlpb.RunMysqlUpgradeRequest{})
return err
})
} | go | func (c *client) RunMysqlUpgrade(ctx context.Context) error {
return c.withRetry(ctx, func() error {
_, err := c.c.RunMysqlUpgrade(ctx, &mysqlctlpb.RunMysqlUpgradeRequest{})
return err
})
} | [
"func",
"(",
"c",
"*",
"client",
")",
"RunMysqlUpgrade",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"return",
"c",
".",
"withRetry",
"(",
"ctx",
",",
"func",
"(",
")",
"error",
"{",
"_",
",",
"err",
":=",
"c",
".",
"c",
".",
"RunMysqlUpgrade",
"(",
"ctx",
",",
"&",
"mysqlctlpb",
".",
"RunMysqlUpgradeRequest",
"{",
"}",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"}"
] | // RunMysqlUpgrade is part of the MysqlctlClient interface. | [
"RunMysqlUpgrade",
"is",
"part",
"of",
"the",
"MysqlctlClient",
"interface",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/grpcmysqlctlclient/client.go#L80-L85 | train |
vitessio/vitess | go/vt/mysqlctl/grpcmysqlctlclient/client.go | ReinitConfig | func (c *client) ReinitConfig(ctx context.Context) error {
return c.withRetry(ctx, func() error {
_, err := c.c.ReinitConfig(ctx, &mysqlctlpb.ReinitConfigRequest{})
return err
})
} | go | func (c *client) ReinitConfig(ctx context.Context) error {
return c.withRetry(ctx, func() error {
_, err := c.c.ReinitConfig(ctx, &mysqlctlpb.ReinitConfigRequest{})
return err
})
} | [
"func",
"(",
"c",
"*",
"client",
")",
"ReinitConfig",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"return",
"c",
".",
"withRetry",
"(",
"ctx",
",",
"func",
"(",
")",
"error",
"{",
"_",
",",
"err",
":=",
"c",
".",
"c",
".",
"ReinitConfig",
"(",
"ctx",
",",
"&",
"mysqlctlpb",
".",
"ReinitConfigRequest",
"{",
"}",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"}"
] | // ReinitConfig is part of the MysqlctlClient interface. | [
"ReinitConfig",
"is",
"part",
"of",
"the",
"MysqlctlClient",
"interface",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/grpcmysqlctlclient/client.go#L88-L93 | train |
vitessio/vitess | go/vt/mysqlctl/grpcmysqlctlclient/client.go | RefreshConfig | func (c *client) RefreshConfig(ctx context.Context) error {
return c.withRetry(ctx, func() error {
_, err := c.c.RefreshConfig(ctx, &mysqlctlpb.RefreshConfigRequest{})
return err
})
} | go | func (c *client) RefreshConfig(ctx context.Context) error {
return c.withRetry(ctx, func() error {
_, err := c.c.RefreshConfig(ctx, &mysqlctlpb.RefreshConfigRequest{})
return err
})
} | [
"func",
"(",
"c",
"*",
"client",
")",
"RefreshConfig",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"return",
"c",
".",
"withRetry",
"(",
"ctx",
",",
"func",
"(",
")",
"error",
"{",
"_",
",",
"err",
":=",
"c",
".",
"c",
".",
"RefreshConfig",
"(",
"ctx",
",",
"&",
"mysqlctlpb",
".",
"RefreshConfigRequest",
"{",
"}",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"}"
] | // RefreshConfig is part of the MysqlctlClient interface. | [
"RefreshConfig",
"is",
"part",
"of",
"the",
"MysqlctlClient",
"interface",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/grpcmysqlctlclient/client.go#L96-L101 | train |
vitessio/vitess | go/vt/topo/helpers/compare.go | CompareKeyspaces | func CompareKeyspaces(ctx context.Context, fromTS, toTS *topo.Server) error {
keyspaces, err := fromTS.GetKeyspaces(ctx)
if err != nil {
return vterrors.Wrapf(err, "GetKeyspace(%v)", keyspaces)
}
for _, keyspace := range keyspaces {
fromKs, err := fromTS.GetKeyspace(ctx, keyspace)
if err != nil {
return vterrors.Wrapf(err, "GetKeyspace(%v)", keyspace)
}
toKs, err := toTS.GetKeyspace(ctx, keyspace)
if err != nil {
return vterrors.Wrapf(err, "GetKeyspace(%v)", keyspace)
}
if !reflect.DeepEqual(fromKs.Keyspace, toKs.Keyspace) {
return vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "Keyspace: %v does not match between from and to topology", keyspace)
}
fromVs, err := fromTS.GetVSchema(ctx, keyspace)
switch {
case err == nil:
// Nothing to do.
case topo.IsErrType(err, topo.NoNode):
// Nothing to do.
default:
return vterrors.Wrapf(err, "GetVSchema(%v)", keyspace)
}
toVs, err := toTS.GetVSchema(ctx, keyspace)
switch {
case err == nil:
// Nothing to do.
case topo.IsErrType(err, topo.NoNode):
// Nothing to do.
default:
return vterrors.Wrapf(err, "GetVSchema(%v)", keyspace)
}
if !reflect.DeepEqual(fromVs, toVs) {
return vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "Vschema for keyspace: %v does not match between from and to topology", keyspace)
}
}
return nil
} | go | func CompareKeyspaces(ctx context.Context, fromTS, toTS *topo.Server) error {
keyspaces, err := fromTS.GetKeyspaces(ctx)
if err != nil {
return vterrors.Wrapf(err, "GetKeyspace(%v)", keyspaces)
}
for _, keyspace := range keyspaces {
fromKs, err := fromTS.GetKeyspace(ctx, keyspace)
if err != nil {
return vterrors.Wrapf(err, "GetKeyspace(%v)", keyspace)
}
toKs, err := toTS.GetKeyspace(ctx, keyspace)
if err != nil {
return vterrors.Wrapf(err, "GetKeyspace(%v)", keyspace)
}
if !reflect.DeepEqual(fromKs.Keyspace, toKs.Keyspace) {
return vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "Keyspace: %v does not match between from and to topology", keyspace)
}
fromVs, err := fromTS.GetVSchema(ctx, keyspace)
switch {
case err == nil:
// Nothing to do.
case topo.IsErrType(err, topo.NoNode):
// Nothing to do.
default:
return vterrors.Wrapf(err, "GetVSchema(%v)", keyspace)
}
toVs, err := toTS.GetVSchema(ctx, keyspace)
switch {
case err == nil:
// Nothing to do.
case topo.IsErrType(err, topo.NoNode):
// Nothing to do.
default:
return vterrors.Wrapf(err, "GetVSchema(%v)", keyspace)
}
if !reflect.DeepEqual(fromVs, toVs) {
return vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "Vschema for keyspace: %v does not match between from and to topology", keyspace)
}
}
return nil
} | [
"func",
"CompareKeyspaces",
"(",
"ctx",
"context",
".",
"Context",
",",
"fromTS",
",",
"toTS",
"*",
"topo",
".",
"Server",
")",
"error",
"{",
"keyspaces",
",",
"err",
":=",
"fromTS",
".",
"GetKeyspaces",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"keyspaces",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"keyspace",
":=",
"range",
"keyspaces",
"{",
"fromKs",
",",
"err",
":=",
"fromTS",
".",
"GetKeyspace",
"(",
"ctx",
",",
"keyspace",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"keyspace",
")",
"\n",
"}",
"\n\n",
"toKs",
",",
"err",
":=",
"toTS",
".",
"GetKeyspace",
"(",
"ctx",
",",
"keyspace",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"keyspace",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"reflect",
".",
"DeepEqual",
"(",
"fromKs",
".",
"Keyspace",
",",
"toKs",
".",
"Keyspace",
")",
"{",
"return",
"vterrors",
".",
"Errorf",
"(",
"vtrpc",
".",
"Code_FAILED_PRECONDITION",
",",
"\"",
"\"",
",",
"keyspace",
")",
"\n",
"}",
"\n\n",
"fromVs",
",",
"err",
":=",
"fromTS",
".",
"GetVSchema",
"(",
"ctx",
",",
"keyspace",
")",
"\n",
"switch",
"{",
"case",
"err",
"==",
"nil",
":",
"// Nothing to do.",
"case",
"topo",
".",
"IsErrType",
"(",
"err",
",",
"topo",
".",
"NoNode",
")",
":",
"// Nothing to do.",
"default",
":",
"return",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"keyspace",
")",
"\n",
"}",
"\n\n",
"toVs",
",",
"err",
":=",
"toTS",
".",
"GetVSchema",
"(",
"ctx",
",",
"keyspace",
")",
"\n",
"switch",
"{",
"case",
"err",
"==",
"nil",
":",
"// Nothing to do.",
"case",
"topo",
".",
"IsErrType",
"(",
"err",
",",
"topo",
".",
"NoNode",
")",
":",
"// Nothing to do.",
"default",
":",
"return",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"keyspace",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"reflect",
".",
"DeepEqual",
"(",
"fromVs",
",",
"toVs",
")",
"{",
"return",
"vterrors",
".",
"Errorf",
"(",
"vtrpc",
".",
"Code_FAILED_PRECONDITION",
",",
"\"",
"\"",
",",
"keyspace",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // CompareKeyspaces will compare the keyspaces in the destination topo. | [
"CompareKeyspaces",
"will",
"compare",
"the",
"keyspaces",
"in",
"the",
"destination",
"topo",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/helpers/compare.go#L32-L79 | train |
vitessio/vitess | go/vt/topo/helpers/compare.go | CompareShards | func CompareShards(ctx context.Context, fromTS, toTS *topo.Server) error {
keyspaces, err := fromTS.GetKeyspaces(ctx)
if err != nil {
return vterrors.Wrapf(err, "fromTS.GetKeyspaces")
}
for _, keyspace := range keyspaces {
shards, err := fromTS.GetShardNames(ctx, keyspace)
if err != nil {
return vterrors.Wrapf(err, "GetShardNames(%v)", keyspace)
}
for _, shard := range shards {
fromSi, err := fromTS.GetShard(ctx, keyspace, shard)
if err != nil {
return vterrors.Wrapf(err, "GetShard(%v, %v)", keyspace, shard)
}
toSi, err := toTS.GetShard(ctx, keyspace, shard)
if err != nil {
return vterrors.Wrapf(err, "GetShard(%v, %v)", keyspace, shard)
}
if !reflect.DeepEqual(fromSi.Shard, toSi.Shard) {
return vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "Shard %v for keyspace: %v does not match between from and to topology", shard, keyspace)
}
}
}
return nil
} | go | func CompareShards(ctx context.Context, fromTS, toTS *topo.Server) error {
keyspaces, err := fromTS.GetKeyspaces(ctx)
if err != nil {
return vterrors.Wrapf(err, "fromTS.GetKeyspaces")
}
for _, keyspace := range keyspaces {
shards, err := fromTS.GetShardNames(ctx, keyspace)
if err != nil {
return vterrors.Wrapf(err, "GetShardNames(%v)", keyspace)
}
for _, shard := range shards {
fromSi, err := fromTS.GetShard(ctx, keyspace, shard)
if err != nil {
return vterrors.Wrapf(err, "GetShard(%v, %v)", keyspace, shard)
}
toSi, err := toTS.GetShard(ctx, keyspace, shard)
if err != nil {
return vterrors.Wrapf(err, "GetShard(%v, %v)", keyspace, shard)
}
if !reflect.DeepEqual(fromSi.Shard, toSi.Shard) {
return vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "Shard %v for keyspace: %v does not match between from and to topology", shard, keyspace)
}
}
}
return nil
} | [
"func",
"CompareShards",
"(",
"ctx",
"context",
".",
"Context",
",",
"fromTS",
",",
"toTS",
"*",
"topo",
".",
"Server",
")",
"error",
"{",
"keyspaces",
",",
"err",
":=",
"fromTS",
".",
"GetKeyspaces",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"keyspace",
":=",
"range",
"keyspaces",
"{",
"shards",
",",
"err",
":=",
"fromTS",
".",
"GetShardNames",
"(",
"ctx",
",",
"keyspace",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"keyspace",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"shard",
":=",
"range",
"shards",
"{",
"fromSi",
",",
"err",
":=",
"fromTS",
".",
"GetShard",
"(",
"ctx",
",",
"keyspace",
",",
"shard",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"keyspace",
",",
"shard",
")",
"\n",
"}",
"\n",
"toSi",
",",
"err",
":=",
"toTS",
".",
"GetShard",
"(",
"ctx",
",",
"keyspace",
",",
"shard",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"keyspace",
",",
"shard",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"reflect",
".",
"DeepEqual",
"(",
"fromSi",
".",
"Shard",
",",
"toSi",
".",
"Shard",
")",
"{",
"return",
"vterrors",
".",
"Errorf",
"(",
"vtrpc",
".",
"Code_FAILED_PRECONDITION",
",",
"\"",
"\"",
",",
"shard",
",",
"keyspace",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // CompareShards will compare the shards in the destination topo. | [
"CompareShards",
"will",
"compare",
"the",
"shards",
"in",
"the",
"destination",
"topo",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/helpers/compare.go#L82-L110 | train |
vitessio/vitess | go/vt/topo/helpers/compare.go | CompareTablets | func CompareTablets(ctx context.Context, fromTS, toTS *topo.Server) error {
cells, err := fromTS.GetKnownCells(ctx)
if err != nil {
return vterrors.Wrapf(err, "fromTS.GetKnownCells")
}
for _, cell := range cells {
tabletAliases, err := fromTS.GetTabletsByCell(ctx, cell)
if err != nil {
return vterrors.Wrapf(err, "GetTabletsByCell(%v)", cell)
}
for _, tabletAlias := range tabletAliases {
// read the source tablet
fromTi, err := fromTS.GetTablet(ctx, tabletAlias)
if err != nil {
return vterrors.Wrapf(err, "GetTablet(%v)", tabletAlias)
}
toTi, err := toTS.GetTablet(ctx, tabletAlias)
if err != nil {
return vterrors.Wrapf(err, "GetTablet(%v)", tabletAlias)
}
if !reflect.DeepEqual(fromTi.Tablet, toTi.Tablet) {
return vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "Tablet %v: does not match between from and to topology", tabletAlias)
}
}
}
return nil
} | go | func CompareTablets(ctx context.Context, fromTS, toTS *topo.Server) error {
cells, err := fromTS.GetKnownCells(ctx)
if err != nil {
return vterrors.Wrapf(err, "fromTS.GetKnownCells")
}
for _, cell := range cells {
tabletAliases, err := fromTS.GetTabletsByCell(ctx, cell)
if err != nil {
return vterrors.Wrapf(err, "GetTabletsByCell(%v)", cell)
}
for _, tabletAlias := range tabletAliases {
// read the source tablet
fromTi, err := fromTS.GetTablet(ctx, tabletAlias)
if err != nil {
return vterrors.Wrapf(err, "GetTablet(%v)", tabletAlias)
}
toTi, err := toTS.GetTablet(ctx, tabletAlias)
if err != nil {
return vterrors.Wrapf(err, "GetTablet(%v)", tabletAlias)
}
if !reflect.DeepEqual(fromTi.Tablet, toTi.Tablet) {
return vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "Tablet %v: does not match between from and to topology", tabletAlias)
}
}
}
return nil
} | [
"func",
"CompareTablets",
"(",
"ctx",
"context",
".",
"Context",
",",
"fromTS",
",",
"toTS",
"*",
"topo",
".",
"Server",
")",
"error",
"{",
"cells",
",",
"err",
":=",
"fromTS",
".",
"GetKnownCells",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"cell",
":=",
"range",
"cells",
"{",
"tabletAliases",
",",
"err",
":=",
"fromTS",
".",
"GetTabletsByCell",
"(",
"ctx",
",",
"cell",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"cell",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"tabletAlias",
":=",
"range",
"tabletAliases",
"{",
"// read the source tablet",
"fromTi",
",",
"err",
":=",
"fromTS",
".",
"GetTablet",
"(",
"ctx",
",",
"tabletAlias",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"tabletAlias",
")",
"\n",
"}",
"\n",
"toTi",
",",
"err",
":=",
"toTS",
".",
"GetTablet",
"(",
"ctx",
",",
"tabletAlias",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"tabletAlias",
")",
"\n",
"}",
"\n",
"if",
"!",
"reflect",
".",
"DeepEqual",
"(",
"fromTi",
".",
"Tablet",
",",
"toTi",
".",
"Tablet",
")",
"{",
"return",
"vterrors",
".",
"Errorf",
"(",
"vtrpc",
".",
"Code_FAILED_PRECONDITION",
",",
"\"",
"\"",
",",
"tabletAlias",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // CompareTablets will compare the tablets in the destination topo. | [
"CompareTablets",
"will",
"compare",
"the",
"tablets",
"in",
"the",
"destination",
"topo",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/helpers/compare.go#L113-L141 | train |
vitessio/vitess | go/vt/topo/helpers/compare.go | CompareShardReplications | func CompareShardReplications(ctx context.Context, fromTS, toTS *topo.Server) error {
keyspaces, err := fromTS.GetKeyspaces(ctx)
if err != nil {
return vterrors.Wrapf(err, "fromTS.GetKeyspaces")
}
cells, err := fromTS.GetCellInfoNames(ctx)
if err != nil {
return vterrors.Wrap(err, "GetCellInfoNames()")
}
for _, keyspace := range keyspaces {
shards, err := fromTS.GetShardNames(ctx, keyspace)
if err != nil {
return vterrors.Wrapf(err, "GetShardNames(%v)", keyspace)
}
for _, shard := range shards {
for _, cell := range cells {
fromSRi, err := fromTS.GetShardReplication(ctx, cell, keyspace, shard)
if err != nil {
return vterrors.Wrapf(err, "GetShardReplication(%v, %v, %v)", cell, keyspace, shard)
}
toSRi, err := toTS.GetShardReplication(ctx, cell, keyspace, shard)
if err != nil {
return vterrors.Wrapf(err, "GetShardReplication(%v, %v, %v)", cell, keyspace, shard)
}
if !reflect.DeepEqual(fromSRi.ShardReplication, toSRi.ShardReplication) {
return vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION,
"Shard Replication in cell %v, keyspace %v, shard %v: does not match between from and to topology",
cell,
keyspace,
shard)
}
}
}
}
return nil
} | go | func CompareShardReplications(ctx context.Context, fromTS, toTS *topo.Server) error {
keyspaces, err := fromTS.GetKeyspaces(ctx)
if err != nil {
return vterrors.Wrapf(err, "fromTS.GetKeyspaces")
}
cells, err := fromTS.GetCellInfoNames(ctx)
if err != nil {
return vterrors.Wrap(err, "GetCellInfoNames()")
}
for _, keyspace := range keyspaces {
shards, err := fromTS.GetShardNames(ctx, keyspace)
if err != nil {
return vterrors.Wrapf(err, "GetShardNames(%v)", keyspace)
}
for _, shard := range shards {
for _, cell := range cells {
fromSRi, err := fromTS.GetShardReplication(ctx, cell, keyspace, shard)
if err != nil {
return vterrors.Wrapf(err, "GetShardReplication(%v, %v, %v)", cell, keyspace, shard)
}
toSRi, err := toTS.GetShardReplication(ctx, cell, keyspace, shard)
if err != nil {
return vterrors.Wrapf(err, "GetShardReplication(%v, %v, %v)", cell, keyspace, shard)
}
if !reflect.DeepEqual(fromSRi.ShardReplication, toSRi.ShardReplication) {
return vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION,
"Shard Replication in cell %v, keyspace %v, shard %v: does not match between from and to topology",
cell,
keyspace,
shard)
}
}
}
}
return nil
} | [
"func",
"CompareShardReplications",
"(",
"ctx",
"context",
".",
"Context",
",",
"fromTS",
",",
"toTS",
"*",
"topo",
".",
"Server",
")",
"error",
"{",
"keyspaces",
",",
"err",
":=",
"fromTS",
".",
"GetKeyspaces",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"cells",
",",
"err",
":=",
"fromTS",
".",
"GetCellInfoNames",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"vterrors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"keyspace",
":=",
"range",
"keyspaces",
"{",
"shards",
",",
"err",
":=",
"fromTS",
".",
"GetShardNames",
"(",
"ctx",
",",
"keyspace",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"keyspace",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"shard",
":=",
"range",
"shards",
"{",
"for",
"_",
",",
"cell",
":=",
"range",
"cells",
"{",
"fromSRi",
",",
"err",
":=",
"fromTS",
".",
"GetShardReplication",
"(",
"ctx",
",",
"cell",
",",
"keyspace",
",",
"shard",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"cell",
",",
"keyspace",
",",
"shard",
")",
"\n",
"}",
"\n",
"toSRi",
",",
"err",
":=",
"toTS",
".",
"GetShardReplication",
"(",
"ctx",
",",
"cell",
",",
"keyspace",
",",
"shard",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"cell",
",",
"keyspace",
",",
"shard",
")",
"\n",
"}",
"\n",
"if",
"!",
"reflect",
".",
"DeepEqual",
"(",
"fromSRi",
".",
"ShardReplication",
",",
"toSRi",
".",
"ShardReplication",
")",
"{",
"return",
"vterrors",
".",
"Errorf",
"(",
"vtrpc",
".",
"Code_FAILED_PRECONDITION",
",",
"\"",
"\"",
",",
"cell",
",",
"keyspace",
",",
"shard",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // CompareShardReplications will compare the ShardReplication objects in
// the destination topo. | [
"CompareShardReplications",
"will",
"compare",
"the",
"ShardReplication",
"objects",
"in",
"the",
"destination",
"topo",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/helpers/compare.go#L145-L182 | train |
vitessio/vitess | go/vt/topo/helpers/compare.go | CompareRoutingRules | func CompareRoutingRules(ctx context.Context, fromTS, toTS *topo.Server) error {
rrFrom, err := fromTS.GetRoutingRules(ctx)
if err != nil {
return vterrors.Wrapf(err, "GetKeyspace(from)")
}
rrTo, err := toTS.GetRoutingRules(ctx)
if err != nil {
return vterrors.Wrapf(err, "GetKeyspace(to)")
}
if !proto.Equal(rrFrom, rrTo) {
return vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "routing rules: %v does not match %v", rrFrom, rrTo)
}
return nil
} | go | func CompareRoutingRules(ctx context.Context, fromTS, toTS *topo.Server) error {
rrFrom, err := fromTS.GetRoutingRules(ctx)
if err != nil {
return vterrors.Wrapf(err, "GetKeyspace(from)")
}
rrTo, err := toTS.GetRoutingRules(ctx)
if err != nil {
return vterrors.Wrapf(err, "GetKeyspace(to)")
}
if !proto.Equal(rrFrom, rrTo) {
return vterrors.Errorf(vtrpc.Code_FAILED_PRECONDITION, "routing rules: %v does not match %v", rrFrom, rrTo)
}
return nil
} | [
"func",
"CompareRoutingRules",
"(",
"ctx",
"context",
".",
"Context",
",",
"fromTS",
",",
"toTS",
"*",
"topo",
".",
"Server",
")",
"error",
"{",
"rrFrom",
",",
"err",
":=",
"fromTS",
".",
"GetRoutingRules",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"rrTo",
",",
"err",
":=",
"toTS",
".",
"GetRoutingRules",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"!",
"proto",
".",
"Equal",
"(",
"rrFrom",
",",
"rrTo",
")",
"{",
"return",
"vterrors",
".",
"Errorf",
"(",
"vtrpc",
".",
"Code_FAILED_PRECONDITION",
",",
"\"",
"\"",
",",
"rrFrom",
",",
"rrTo",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // CompareRoutingRules will compare the routing rules in the destination topo. | [
"CompareRoutingRules",
"will",
"compare",
"the",
"routing",
"rules",
"in",
"the",
"destination",
"topo",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/helpers/compare.go#L185-L198 | train |
vitessio/vitess | go/vt/vtctl/grpcvtctlserver/server.go | ExecuteVtctlCommand | func (s *VtctlServer) ExecuteVtctlCommand(args *vtctldatapb.ExecuteVtctlCommandRequest, stream vtctlservicepb.Vtctl_ExecuteVtctlCommandServer) (err error) {
defer servenv.HandlePanic("vtctl", &err)
// Create a logger, send the result back to the caller.
// We may execute this in parallel (inside multiple go routines),
// but the stream.Send() method is not thread safe in gRPC.
// So use a mutex to protect it.
mu := sync.Mutex{}
logstream := logutil.NewCallbackLogger(func(e *logutilpb.Event) {
// If the client disconnects, we will just fail
// to send the log events, but won't interrupt
// the command.
mu.Lock()
stream.Send(&vtctldatapb.ExecuteVtctlCommandResponse{
Event: e,
})
mu.Unlock()
})
logger := logutil.NewTeeLogger(logstream, logutil.NewConsoleLogger())
// create the wrangler
tmc := tmclient.NewTabletManagerClient()
defer tmc.Close()
wr := wrangler.New(logger, s.ts, tmc)
// execute the command
return vtctl.RunCommand(stream.Context(), wr, args.Args)
} | go | func (s *VtctlServer) ExecuteVtctlCommand(args *vtctldatapb.ExecuteVtctlCommandRequest, stream vtctlservicepb.Vtctl_ExecuteVtctlCommandServer) (err error) {
defer servenv.HandlePanic("vtctl", &err)
// Create a logger, send the result back to the caller.
// We may execute this in parallel (inside multiple go routines),
// but the stream.Send() method is not thread safe in gRPC.
// So use a mutex to protect it.
mu := sync.Mutex{}
logstream := logutil.NewCallbackLogger(func(e *logutilpb.Event) {
// If the client disconnects, we will just fail
// to send the log events, but won't interrupt
// the command.
mu.Lock()
stream.Send(&vtctldatapb.ExecuteVtctlCommandResponse{
Event: e,
})
mu.Unlock()
})
logger := logutil.NewTeeLogger(logstream, logutil.NewConsoleLogger())
// create the wrangler
tmc := tmclient.NewTabletManagerClient()
defer tmc.Close()
wr := wrangler.New(logger, s.ts, tmc)
// execute the command
return vtctl.RunCommand(stream.Context(), wr, args.Args)
} | [
"func",
"(",
"s",
"*",
"VtctlServer",
")",
"ExecuteVtctlCommand",
"(",
"args",
"*",
"vtctldatapb",
".",
"ExecuteVtctlCommandRequest",
",",
"stream",
"vtctlservicepb",
".",
"Vtctl_ExecuteVtctlCommandServer",
")",
"(",
"err",
"error",
")",
"{",
"defer",
"servenv",
".",
"HandlePanic",
"(",
"\"",
"\"",
",",
"&",
"err",
")",
"\n\n",
"// Create a logger, send the result back to the caller.",
"// We may execute this in parallel (inside multiple go routines),",
"// but the stream.Send() method is not thread safe in gRPC.",
"// So use a mutex to protect it.",
"mu",
":=",
"sync",
".",
"Mutex",
"{",
"}",
"\n",
"logstream",
":=",
"logutil",
".",
"NewCallbackLogger",
"(",
"func",
"(",
"e",
"*",
"logutilpb",
".",
"Event",
")",
"{",
"// If the client disconnects, we will just fail",
"// to send the log events, but won't interrupt",
"// the command.",
"mu",
".",
"Lock",
"(",
")",
"\n",
"stream",
".",
"Send",
"(",
"&",
"vtctldatapb",
".",
"ExecuteVtctlCommandResponse",
"{",
"Event",
":",
"e",
",",
"}",
")",
"\n",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}",
")",
"\n",
"logger",
":=",
"logutil",
".",
"NewTeeLogger",
"(",
"logstream",
",",
"logutil",
".",
"NewConsoleLogger",
"(",
")",
")",
"\n\n",
"// create the wrangler",
"tmc",
":=",
"tmclient",
".",
"NewTabletManagerClient",
"(",
")",
"\n",
"defer",
"tmc",
".",
"Close",
"(",
")",
"\n",
"wr",
":=",
"wrangler",
".",
"New",
"(",
"logger",
",",
"s",
".",
"ts",
",",
"tmc",
")",
"\n\n",
"// execute the command",
"return",
"vtctl",
".",
"RunCommand",
"(",
"stream",
".",
"Context",
"(",
")",
",",
"wr",
",",
"args",
".",
"Args",
")",
"\n",
"}"
] | // ExecuteVtctlCommand is part of the vtctldatapb.VtctlServer interface | [
"ExecuteVtctlCommand",
"is",
"part",
"of",
"the",
"vtctldatapb",
".",
"VtctlServer",
"interface"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtctl/grpcvtctlserver/server.go#L51-L78 | train |
vitessio/vitess | go/vt/vtctl/grpcvtctlserver/server.go | StartServer | func StartServer(s *grpc.Server, ts *topo.Server) {
vtctlservicepb.RegisterVtctlServer(s, NewVtctlServer(ts))
} | go | func StartServer(s *grpc.Server, ts *topo.Server) {
vtctlservicepb.RegisterVtctlServer(s, NewVtctlServer(ts))
} | [
"func",
"StartServer",
"(",
"s",
"*",
"grpc",
".",
"Server",
",",
"ts",
"*",
"topo",
".",
"Server",
")",
"{",
"vtctlservicepb",
".",
"RegisterVtctlServer",
"(",
"s",
",",
"NewVtctlServer",
"(",
"ts",
")",
")",
"\n",
"}"
] | // StartServer registers the VtctlServer for RPCs | [
"StartServer",
"registers",
"the",
"VtctlServer",
"for",
"RPCs"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtctl/grpcvtctlserver/server.go#L81-L83 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/querylogz.go | querylogzHandler | func querylogzHandler(ch chan interface{}, w http.ResponseWriter, r *http.Request) {
if err := acl.CheckAccessHTTP(r, acl.DEBUGGING); err != nil {
acl.SendError(w, err)
return
}
timeout, limit := parseTimeoutLimitParams(r)
logz.StartHTMLTable(w)
defer logz.EndHTMLTable(w)
w.Write(querylogzHeader)
tmr := time.NewTimer(timeout)
defer tmr.Stop()
for i := 0; i < limit; i++ {
select {
case out := <-ch:
select {
case <-tmr.C:
return
default:
}
stats, ok := out.(*tabletenv.LogStats)
if !ok {
err := fmt.Errorf("unexpected value in %s: %#v (expecting value of type %T)", tabletenv.TxLogger.Name(), out, &tabletenv.LogStats{})
io.WriteString(w, `<tr class="error">`)
io.WriteString(w, err.Error())
io.WriteString(w, "</tr>")
log.Error(err)
continue
}
var level string
if stats.TotalTime().Seconds() < 0.01 {
level = "low"
} else if stats.TotalTime().Seconds() < 0.1 {
level = "medium"
} else {
level = "high"
}
tmplData := struct {
*tabletenv.LogStats
ColorLevel string
}{stats, level}
if err := querylogzTmpl.Execute(w, tmplData); err != nil {
log.Errorf("querylogz: couldn't execute template: %v", err)
}
case <-tmr.C:
return
}
}
} | go | func querylogzHandler(ch chan interface{}, w http.ResponseWriter, r *http.Request) {
if err := acl.CheckAccessHTTP(r, acl.DEBUGGING); err != nil {
acl.SendError(w, err)
return
}
timeout, limit := parseTimeoutLimitParams(r)
logz.StartHTMLTable(w)
defer logz.EndHTMLTable(w)
w.Write(querylogzHeader)
tmr := time.NewTimer(timeout)
defer tmr.Stop()
for i := 0; i < limit; i++ {
select {
case out := <-ch:
select {
case <-tmr.C:
return
default:
}
stats, ok := out.(*tabletenv.LogStats)
if !ok {
err := fmt.Errorf("unexpected value in %s: %#v (expecting value of type %T)", tabletenv.TxLogger.Name(), out, &tabletenv.LogStats{})
io.WriteString(w, `<tr class="error">`)
io.WriteString(w, err.Error())
io.WriteString(w, "</tr>")
log.Error(err)
continue
}
var level string
if stats.TotalTime().Seconds() < 0.01 {
level = "low"
} else if stats.TotalTime().Seconds() < 0.1 {
level = "medium"
} else {
level = "high"
}
tmplData := struct {
*tabletenv.LogStats
ColorLevel string
}{stats, level}
if err := querylogzTmpl.Execute(w, tmplData); err != nil {
log.Errorf("querylogz: couldn't execute template: %v", err)
}
case <-tmr.C:
return
}
}
} | [
"func",
"querylogzHandler",
"(",
"ch",
"chan",
"interface",
"{",
"}",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"err",
":=",
"acl",
".",
"CheckAccessHTTP",
"(",
"r",
",",
"acl",
".",
"DEBUGGING",
")",
";",
"err",
"!=",
"nil",
"{",
"acl",
".",
"SendError",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"timeout",
",",
"limit",
":=",
"parseTimeoutLimitParams",
"(",
"r",
")",
"\n",
"logz",
".",
"StartHTMLTable",
"(",
"w",
")",
"\n",
"defer",
"logz",
".",
"EndHTMLTable",
"(",
"w",
")",
"\n",
"w",
".",
"Write",
"(",
"querylogzHeader",
")",
"\n\n",
"tmr",
":=",
"time",
".",
"NewTimer",
"(",
"timeout",
")",
"\n",
"defer",
"tmr",
".",
"Stop",
"(",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"limit",
";",
"i",
"++",
"{",
"select",
"{",
"case",
"out",
":=",
"<-",
"ch",
":",
"select",
"{",
"case",
"<-",
"tmr",
".",
"C",
":",
"return",
"\n",
"default",
":",
"}",
"\n",
"stats",
",",
"ok",
":=",
"out",
".",
"(",
"*",
"tabletenv",
".",
"LogStats",
")",
"\n",
"if",
"!",
"ok",
"{",
"err",
":=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"tabletenv",
".",
"TxLogger",
".",
"Name",
"(",
")",
",",
"out",
",",
"&",
"tabletenv",
".",
"LogStats",
"{",
"}",
")",
"\n",
"io",
".",
"WriteString",
"(",
"w",
",",
"`<tr class=\"error\">`",
")",
"\n",
"io",
".",
"WriteString",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"io",
".",
"WriteString",
"(",
"w",
",",
"\"",
"\"",
")",
"\n",
"log",
".",
"Error",
"(",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"var",
"level",
"string",
"\n",
"if",
"stats",
".",
"TotalTime",
"(",
")",
".",
"Seconds",
"(",
")",
"<",
"0.01",
"{",
"level",
"=",
"\"",
"\"",
"\n",
"}",
"else",
"if",
"stats",
".",
"TotalTime",
"(",
")",
".",
"Seconds",
"(",
")",
"<",
"0.1",
"{",
"level",
"=",
"\"",
"\"",
"\n",
"}",
"else",
"{",
"level",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"tmplData",
":=",
"struct",
"{",
"*",
"tabletenv",
".",
"LogStats",
"\n",
"ColorLevel",
"string",
"\n",
"}",
"{",
"stats",
",",
"level",
"}",
"\n",
"if",
"err",
":=",
"querylogzTmpl",
".",
"Execute",
"(",
"w",
",",
"tmplData",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"case",
"<-",
"tmr",
".",
"C",
":",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // querylogzHandler serves a human readable snapshot of the
// current query log. | [
"querylogzHandler",
"serves",
"a",
"human",
"readable",
"snapshot",
"of",
"the",
"current",
"query",
"log",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/querylogz.go#L98-L146 | train |
vitessio/vitess | go/vt/mysqlctl/backupengine.go | GetBackupEngine | func GetBackupEngine() (BackupEngine, error) {
be, ok := BackupEngineMap[*backupEngineImplementation]
if !ok {
return nil, vterrors.New(vtrpc.Code_NOT_FOUND, "no registered implementation of BackupEngine")
}
return be, nil
} | go | func GetBackupEngine() (BackupEngine, error) {
be, ok := BackupEngineMap[*backupEngineImplementation]
if !ok {
return nil, vterrors.New(vtrpc.Code_NOT_FOUND, "no registered implementation of BackupEngine")
}
return be, nil
} | [
"func",
"GetBackupEngine",
"(",
")",
"(",
"BackupEngine",
",",
"error",
")",
"{",
"be",
",",
"ok",
":=",
"BackupEngineMap",
"[",
"*",
"backupEngineImplementation",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"vterrors",
".",
"New",
"(",
"vtrpc",
".",
"Code_NOT_FOUND",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"be",
",",
"nil",
"\n",
"}"
] | // GetBackupEngine returns the current BackupEngine implementation.
// Should be called after flags have been initialized. | [
"GetBackupEngine",
"returns",
"the",
"current",
"BackupEngine",
"implementation",
".",
"Should",
"be",
"called",
"after",
"flags",
"have",
"been",
"initialized",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/backupengine.go#L46-L52 | train |
vitessio/vitess | go/mysql/slave_status.go | SlaveStatusToProto | func SlaveStatusToProto(s SlaveStatus) *replicationdatapb.Status {
return &replicationdatapb.Status{
Position: EncodePosition(s.Position),
SlaveIoRunning: s.SlaveIORunning,
SlaveSqlRunning: s.SlaveSQLRunning,
SecondsBehindMaster: uint32(s.SecondsBehindMaster),
MasterHost: s.MasterHost,
MasterPort: int32(s.MasterPort),
MasterConnectRetry: int32(s.MasterConnectRetry),
}
} | go | func SlaveStatusToProto(s SlaveStatus) *replicationdatapb.Status {
return &replicationdatapb.Status{
Position: EncodePosition(s.Position),
SlaveIoRunning: s.SlaveIORunning,
SlaveSqlRunning: s.SlaveSQLRunning,
SecondsBehindMaster: uint32(s.SecondsBehindMaster),
MasterHost: s.MasterHost,
MasterPort: int32(s.MasterPort),
MasterConnectRetry: int32(s.MasterConnectRetry),
}
} | [
"func",
"SlaveStatusToProto",
"(",
"s",
"SlaveStatus",
")",
"*",
"replicationdatapb",
".",
"Status",
"{",
"return",
"&",
"replicationdatapb",
".",
"Status",
"{",
"Position",
":",
"EncodePosition",
"(",
"s",
".",
"Position",
")",
",",
"SlaveIoRunning",
":",
"s",
".",
"SlaveIORunning",
",",
"SlaveSqlRunning",
":",
"s",
".",
"SlaveSQLRunning",
",",
"SecondsBehindMaster",
":",
"uint32",
"(",
"s",
".",
"SecondsBehindMaster",
")",
",",
"MasterHost",
":",
"s",
".",
"MasterHost",
",",
"MasterPort",
":",
"int32",
"(",
"s",
".",
"MasterPort",
")",
",",
"MasterConnectRetry",
":",
"int32",
"(",
"s",
".",
"MasterConnectRetry",
")",
",",
"}",
"\n",
"}"
] | // SlaveStatusToProto translates a Status to proto3. | [
"SlaveStatusToProto",
"translates",
"a",
"Status",
"to",
"proto3",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/slave_status.go#L42-L52 | train |
vitessio/vitess | go/mysql/slave_status.go | ProtoToSlaveStatus | func ProtoToSlaveStatus(s *replicationdatapb.Status) SlaveStatus {
pos, err := DecodePosition(s.Position)
if err != nil {
panic(vterrors.Wrapf(err, "cannot decode Position"))
}
return SlaveStatus{
Position: pos,
SlaveIORunning: s.SlaveIoRunning,
SlaveSQLRunning: s.SlaveSqlRunning,
SecondsBehindMaster: uint(s.SecondsBehindMaster),
MasterHost: s.MasterHost,
MasterPort: int(s.MasterPort),
MasterConnectRetry: int(s.MasterConnectRetry),
}
} | go | func ProtoToSlaveStatus(s *replicationdatapb.Status) SlaveStatus {
pos, err := DecodePosition(s.Position)
if err != nil {
panic(vterrors.Wrapf(err, "cannot decode Position"))
}
return SlaveStatus{
Position: pos,
SlaveIORunning: s.SlaveIoRunning,
SlaveSQLRunning: s.SlaveSqlRunning,
SecondsBehindMaster: uint(s.SecondsBehindMaster),
MasterHost: s.MasterHost,
MasterPort: int(s.MasterPort),
MasterConnectRetry: int(s.MasterConnectRetry),
}
} | [
"func",
"ProtoToSlaveStatus",
"(",
"s",
"*",
"replicationdatapb",
".",
"Status",
")",
"SlaveStatus",
"{",
"pos",
",",
"err",
":=",
"DecodePosition",
"(",
"s",
".",
"Position",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"return",
"SlaveStatus",
"{",
"Position",
":",
"pos",
",",
"SlaveIORunning",
":",
"s",
".",
"SlaveIoRunning",
",",
"SlaveSQLRunning",
":",
"s",
".",
"SlaveSqlRunning",
",",
"SecondsBehindMaster",
":",
"uint",
"(",
"s",
".",
"SecondsBehindMaster",
")",
",",
"MasterHost",
":",
"s",
".",
"MasterHost",
",",
"MasterPort",
":",
"int",
"(",
"s",
".",
"MasterPort",
")",
",",
"MasterConnectRetry",
":",
"int",
"(",
"s",
".",
"MasterConnectRetry",
")",
",",
"}",
"\n",
"}"
] | // ProtoToSlaveStatus translates a proto Status, or panics. | [
"ProtoToSlaveStatus",
"translates",
"a",
"proto",
"Status",
"or",
"panics",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/slave_status.go#L55-L69 | train |
vitessio/vitess | go/vt/topotools/split.go | ContainsShard | func (os *OverlappingShards) ContainsShard(shardName string) bool {
for _, l := range os.Left {
if l.ShardName() == shardName {
return true
}
}
for _, r := range os.Right {
if r.ShardName() == shardName {
return true
}
}
return false
} | go | func (os *OverlappingShards) ContainsShard(shardName string) bool {
for _, l := range os.Left {
if l.ShardName() == shardName {
return true
}
}
for _, r := range os.Right {
if r.ShardName() == shardName {
return true
}
}
return false
} | [
"func",
"(",
"os",
"*",
"OverlappingShards",
")",
"ContainsShard",
"(",
"shardName",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"l",
":=",
"range",
"os",
".",
"Left",
"{",
"if",
"l",
".",
"ShardName",
"(",
")",
"==",
"shardName",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"os",
".",
"Right",
"{",
"if",
"r",
".",
"ShardName",
"(",
")",
"==",
"shardName",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // ContainsShard returns true if either Left or Right lists contain
// the provided Shard. | [
"ContainsShard",
"returns",
"true",
"if",
"either",
"Left",
"or",
"Right",
"lists",
"contain",
"the",
"provided",
"Shard",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topotools/split.go#L37-L49 | train |
vitessio/vitess | go/vt/topotools/split.go | OverlappingShardsForShard | func OverlappingShardsForShard(os []*OverlappingShards, shardName string) *OverlappingShards {
for _, o := range os {
if o.ContainsShard(shardName) {
return o
}
}
return nil
} | go | func OverlappingShardsForShard(os []*OverlappingShards, shardName string) *OverlappingShards {
for _, o := range os {
if o.ContainsShard(shardName) {
return o
}
}
return nil
} | [
"func",
"OverlappingShardsForShard",
"(",
"os",
"[",
"]",
"*",
"OverlappingShards",
",",
"shardName",
"string",
")",
"*",
"OverlappingShards",
"{",
"for",
"_",
",",
"o",
":=",
"range",
"os",
"{",
"if",
"o",
".",
"ContainsShard",
"(",
"shardName",
")",
"{",
"return",
"o",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // OverlappingShardsForShard returns the OverlappingShards object
// from the list that has he provided shard, or nil | [
"OverlappingShardsForShard",
"returns",
"the",
"OverlappingShards",
"object",
"from",
"the",
"list",
"that",
"has",
"he",
"provided",
"shard",
"or",
"nil"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topotools/split.go#L53-L60 | train |
vitessio/vitess | go/vt/topotools/split.go | findOverlappingShards | func findOverlappingShards(shardMap map[string]*topo.ShardInfo) ([]*OverlappingShards, error) {
var result []*OverlappingShards
for len(shardMap) > 0 {
var left []*topo.ShardInfo
var right []*topo.ShardInfo
// get the first value from the map, seed our left array with it
var name string
var si *topo.ShardInfo
for name, si = range shardMap {
break
}
left = append(left, si)
delete(shardMap, name)
// keep adding entries until we have no more to add
for {
foundOne := false
// try left to right
si := findIntersectingShard(shardMap, left)
if si != nil {
if intersect(si, right) {
return nil, fmt.Errorf("shard %v intersects with more than one shard, this is not supported", si.ShardName())
}
foundOne = true
right = append(right, si)
}
// try right to left
si = findIntersectingShard(shardMap, right)
if si != nil {
if intersect(si, left) {
return nil, fmt.Errorf("shard %v intersects with more than one shard, this is not supported", si.ShardName())
}
foundOne = true
left = append(left, si)
}
// we haven't found anything new, we're done
if !foundOne {
break
}
}
// save what we found if it's good
if len(right) > 0 {
// sort both lists
sort.Sort(shardInfoList(left))
sort.Sort(shardInfoList(right))
// we should not have holes on either side
hasHoles := false
for i := 0; i < len(left)-1; i++ {
if string(left[i].KeyRange.End) != string(left[i+1].KeyRange.Start) {
hasHoles = true
}
}
for i := 0; i < len(right)-1; i++ {
if string(right[i].KeyRange.End) != string(right[i+1].KeyRange.Start) {
hasHoles = true
}
}
if hasHoles {
continue
}
// the two sides should match
if !key.KeyRangeStartEqual(left[0].KeyRange, right[0].KeyRange) {
continue
}
if !key.KeyRangeEndEqual(left[len(left)-1].KeyRange, right[len(right)-1].KeyRange) {
continue
}
// all good, we have a valid overlap
result = append(result, &OverlappingShards{
Left: left,
Right: right,
})
}
}
return result, nil
} | go | func findOverlappingShards(shardMap map[string]*topo.ShardInfo) ([]*OverlappingShards, error) {
var result []*OverlappingShards
for len(shardMap) > 0 {
var left []*topo.ShardInfo
var right []*topo.ShardInfo
// get the first value from the map, seed our left array with it
var name string
var si *topo.ShardInfo
for name, si = range shardMap {
break
}
left = append(left, si)
delete(shardMap, name)
// keep adding entries until we have no more to add
for {
foundOne := false
// try left to right
si := findIntersectingShard(shardMap, left)
if si != nil {
if intersect(si, right) {
return nil, fmt.Errorf("shard %v intersects with more than one shard, this is not supported", si.ShardName())
}
foundOne = true
right = append(right, si)
}
// try right to left
si = findIntersectingShard(shardMap, right)
if si != nil {
if intersect(si, left) {
return nil, fmt.Errorf("shard %v intersects with more than one shard, this is not supported", si.ShardName())
}
foundOne = true
left = append(left, si)
}
// we haven't found anything new, we're done
if !foundOne {
break
}
}
// save what we found if it's good
if len(right) > 0 {
// sort both lists
sort.Sort(shardInfoList(left))
sort.Sort(shardInfoList(right))
// we should not have holes on either side
hasHoles := false
for i := 0; i < len(left)-1; i++ {
if string(left[i].KeyRange.End) != string(left[i+1].KeyRange.Start) {
hasHoles = true
}
}
for i := 0; i < len(right)-1; i++ {
if string(right[i].KeyRange.End) != string(right[i+1].KeyRange.Start) {
hasHoles = true
}
}
if hasHoles {
continue
}
// the two sides should match
if !key.KeyRangeStartEqual(left[0].KeyRange, right[0].KeyRange) {
continue
}
if !key.KeyRangeEndEqual(left[len(left)-1].KeyRange, right[len(right)-1].KeyRange) {
continue
}
// all good, we have a valid overlap
result = append(result, &OverlappingShards{
Left: left,
Right: right,
})
}
}
return result, nil
} | [
"func",
"findOverlappingShards",
"(",
"shardMap",
"map",
"[",
"string",
"]",
"*",
"topo",
".",
"ShardInfo",
")",
"(",
"[",
"]",
"*",
"OverlappingShards",
",",
"error",
")",
"{",
"var",
"result",
"[",
"]",
"*",
"OverlappingShards",
"\n\n",
"for",
"len",
"(",
"shardMap",
")",
">",
"0",
"{",
"var",
"left",
"[",
"]",
"*",
"topo",
".",
"ShardInfo",
"\n",
"var",
"right",
"[",
"]",
"*",
"topo",
".",
"ShardInfo",
"\n\n",
"// get the first value from the map, seed our left array with it",
"var",
"name",
"string",
"\n",
"var",
"si",
"*",
"topo",
".",
"ShardInfo",
"\n",
"for",
"name",
",",
"si",
"=",
"range",
"shardMap",
"{",
"break",
"\n",
"}",
"\n",
"left",
"=",
"append",
"(",
"left",
",",
"si",
")",
"\n",
"delete",
"(",
"shardMap",
",",
"name",
")",
"\n\n",
"// keep adding entries until we have no more to add",
"for",
"{",
"foundOne",
":=",
"false",
"\n\n",
"// try left to right",
"si",
":=",
"findIntersectingShard",
"(",
"shardMap",
",",
"left",
")",
"\n",
"if",
"si",
"!=",
"nil",
"{",
"if",
"intersect",
"(",
"si",
",",
"right",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"si",
".",
"ShardName",
"(",
")",
")",
"\n",
"}",
"\n",
"foundOne",
"=",
"true",
"\n",
"right",
"=",
"append",
"(",
"right",
",",
"si",
")",
"\n",
"}",
"\n\n",
"// try right to left",
"si",
"=",
"findIntersectingShard",
"(",
"shardMap",
",",
"right",
")",
"\n",
"if",
"si",
"!=",
"nil",
"{",
"if",
"intersect",
"(",
"si",
",",
"left",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"si",
".",
"ShardName",
"(",
")",
")",
"\n",
"}",
"\n",
"foundOne",
"=",
"true",
"\n",
"left",
"=",
"append",
"(",
"left",
",",
"si",
")",
"\n",
"}",
"\n\n",
"// we haven't found anything new, we're done",
"if",
"!",
"foundOne",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"// save what we found if it's good",
"if",
"len",
"(",
"right",
")",
">",
"0",
"{",
"// sort both lists",
"sort",
".",
"Sort",
"(",
"shardInfoList",
"(",
"left",
")",
")",
"\n",
"sort",
".",
"Sort",
"(",
"shardInfoList",
"(",
"right",
")",
")",
"\n\n",
"// we should not have holes on either side",
"hasHoles",
":=",
"false",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"left",
")",
"-",
"1",
";",
"i",
"++",
"{",
"if",
"string",
"(",
"left",
"[",
"i",
"]",
".",
"KeyRange",
".",
"End",
")",
"!=",
"string",
"(",
"left",
"[",
"i",
"+",
"1",
"]",
".",
"KeyRange",
".",
"Start",
")",
"{",
"hasHoles",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"right",
")",
"-",
"1",
";",
"i",
"++",
"{",
"if",
"string",
"(",
"right",
"[",
"i",
"]",
".",
"KeyRange",
".",
"End",
")",
"!=",
"string",
"(",
"right",
"[",
"i",
"+",
"1",
"]",
".",
"KeyRange",
".",
"Start",
")",
"{",
"hasHoles",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"hasHoles",
"{",
"continue",
"\n",
"}",
"\n\n",
"// the two sides should match",
"if",
"!",
"key",
".",
"KeyRangeStartEqual",
"(",
"left",
"[",
"0",
"]",
".",
"KeyRange",
",",
"right",
"[",
"0",
"]",
".",
"KeyRange",
")",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"!",
"key",
".",
"KeyRangeEndEqual",
"(",
"left",
"[",
"len",
"(",
"left",
")",
"-",
"1",
"]",
".",
"KeyRange",
",",
"right",
"[",
"len",
"(",
"right",
")",
"-",
"1",
"]",
".",
"KeyRange",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"// all good, we have a valid overlap",
"result",
"=",
"append",
"(",
"result",
",",
"&",
"OverlappingShards",
"{",
"Left",
":",
"left",
",",
"Right",
":",
"right",
",",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // findOverlappingShards does the work for FindOverlappingShards but
// can be called on test data too. | [
"findOverlappingShards",
"does",
"the",
"work",
"for",
"FindOverlappingShards",
"but",
"can",
"be",
"called",
"on",
"test",
"data",
"too",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topotools/split.go#L79-L164 | train |
vitessio/vitess | go/vt/topotools/split.go | findIntersectingShard | func findIntersectingShard(shardMap map[string]*topo.ShardInfo, sourceArray []*topo.ShardInfo) *topo.ShardInfo {
for name, si := range shardMap {
for _, sourceShardInfo := range sourceArray {
if si.KeyRange == nil || sourceShardInfo.KeyRange == nil || key.KeyRangesIntersect(si.KeyRange, sourceShardInfo.KeyRange) {
delete(shardMap, name)
return si
}
}
}
return nil
} | go | func findIntersectingShard(shardMap map[string]*topo.ShardInfo, sourceArray []*topo.ShardInfo) *topo.ShardInfo {
for name, si := range shardMap {
for _, sourceShardInfo := range sourceArray {
if si.KeyRange == nil || sourceShardInfo.KeyRange == nil || key.KeyRangesIntersect(si.KeyRange, sourceShardInfo.KeyRange) {
delete(shardMap, name)
return si
}
}
}
return nil
} | [
"func",
"findIntersectingShard",
"(",
"shardMap",
"map",
"[",
"string",
"]",
"*",
"topo",
".",
"ShardInfo",
",",
"sourceArray",
"[",
"]",
"*",
"topo",
".",
"ShardInfo",
")",
"*",
"topo",
".",
"ShardInfo",
"{",
"for",
"name",
",",
"si",
":=",
"range",
"shardMap",
"{",
"for",
"_",
",",
"sourceShardInfo",
":=",
"range",
"sourceArray",
"{",
"if",
"si",
".",
"KeyRange",
"==",
"nil",
"||",
"sourceShardInfo",
".",
"KeyRange",
"==",
"nil",
"||",
"key",
".",
"KeyRangesIntersect",
"(",
"si",
".",
"KeyRange",
",",
"sourceShardInfo",
".",
"KeyRange",
")",
"{",
"delete",
"(",
"shardMap",
",",
"name",
")",
"\n",
"return",
"si",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // findIntersectingShard will go through the map and take the first
// entry in there that intersect with the source array, remove it from
// the map, and return it | [
"findIntersectingShard",
"will",
"go",
"through",
"the",
"map",
"and",
"take",
"the",
"first",
"entry",
"in",
"there",
"that",
"intersect",
"with",
"the",
"source",
"array",
"remove",
"it",
"from",
"the",
"map",
"and",
"return",
"it"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topotools/split.go#L169-L179 | train |
vitessio/vitess | go/vt/topotools/split.go | intersect | func intersect(si *topo.ShardInfo, allShards []*topo.ShardInfo) bool {
for _, shard := range allShards {
if key.KeyRangesIntersect(si.KeyRange, shard.KeyRange) {
return true
}
}
return false
} | go | func intersect(si *topo.ShardInfo, allShards []*topo.ShardInfo) bool {
for _, shard := range allShards {
if key.KeyRangesIntersect(si.KeyRange, shard.KeyRange) {
return true
}
}
return false
} | [
"func",
"intersect",
"(",
"si",
"*",
"topo",
".",
"ShardInfo",
",",
"allShards",
"[",
"]",
"*",
"topo",
".",
"ShardInfo",
")",
"bool",
"{",
"for",
"_",
",",
"shard",
":=",
"range",
"allShards",
"{",
"if",
"key",
".",
"KeyRangesIntersect",
"(",
"si",
".",
"KeyRange",
",",
"shard",
".",
"KeyRange",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // intersect returns true if the provided shard intersect with any shard
// in the destination array | [
"intersect",
"returns",
"true",
"if",
"the",
"provided",
"shard",
"intersect",
"with",
"any",
"shard",
"in",
"the",
"destination",
"array"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topotools/split.go#L183-L190 | train |
vitessio/vitess | go/vt/automation/scheduler.go | NewScheduler | func NewScheduler() (*Scheduler, error) {
defaultClusterOperations := map[string]bool{
"HorizontalReshardingTask": true,
"VerticalSplitTask": true,
}
s := &Scheduler{
registeredClusterOperations: defaultClusterOperations,
idGenerator: IDGenerator{},
toBeScheduledClusterOperations: make(chan ClusterOperationInstance, 10),
state: stateNotRunning,
taskCreator: defaultTaskCreator,
pendingOpsWg: &sync.WaitGroup{},
activeClusterOperations: make(map[string]ClusterOperationInstance),
finishedClusterOperations: make(map[string]ClusterOperationInstance),
}
return s, nil
} | go | func NewScheduler() (*Scheduler, error) {
defaultClusterOperations := map[string]bool{
"HorizontalReshardingTask": true,
"VerticalSplitTask": true,
}
s := &Scheduler{
registeredClusterOperations: defaultClusterOperations,
idGenerator: IDGenerator{},
toBeScheduledClusterOperations: make(chan ClusterOperationInstance, 10),
state: stateNotRunning,
taskCreator: defaultTaskCreator,
pendingOpsWg: &sync.WaitGroup{},
activeClusterOperations: make(map[string]ClusterOperationInstance),
finishedClusterOperations: make(map[string]ClusterOperationInstance),
}
return s, nil
} | [
"func",
"NewScheduler",
"(",
")",
"(",
"*",
"Scheduler",
",",
"error",
")",
"{",
"defaultClusterOperations",
":=",
"map",
"[",
"string",
"]",
"bool",
"{",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"}",
"\n\n",
"s",
":=",
"&",
"Scheduler",
"{",
"registeredClusterOperations",
":",
"defaultClusterOperations",
",",
"idGenerator",
":",
"IDGenerator",
"{",
"}",
",",
"toBeScheduledClusterOperations",
":",
"make",
"(",
"chan",
"ClusterOperationInstance",
",",
"10",
")",
",",
"state",
":",
"stateNotRunning",
",",
"taskCreator",
":",
"defaultTaskCreator",
",",
"pendingOpsWg",
":",
"&",
"sync",
".",
"WaitGroup",
"{",
"}",
",",
"activeClusterOperations",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"ClusterOperationInstance",
")",
",",
"finishedClusterOperations",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"ClusterOperationInstance",
")",
",",
"}",
"\n\n",
"return",
"s",
",",
"nil",
"\n",
"}"
] | // NewScheduler creates a new instance. | [
"NewScheduler",
"creates",
"a",
"new",
"instance",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/automation/scheduler.go#L76-L94 | train |
vitessio/vitess | go/vt/automation/scheduler.go | Run | func (s *Scheduler) Run() {
s.mu.Lock()
s.state = stateRunning
s.mu.Unlock()
s.startProcessRequestsLoop()
} | go | func (s *Scheduler) Run() {
s.mu.Lock()
s.state = stateRunning
s.mu.Unlock()
s.startProcessRequestsLoop()
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"Run",
"(",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"state",
"=",
"stateRunning",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"s",
".",
"startProcessRequestsLoop",
"(",
")",
"\n",
"}"
] | // Run processes queued cluster operations. | [
"Run",
"processes",
"queued",
"cluster",
"operations",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/automation/scheduler.go#L104-L110 | train |
vitessio/vitess | go/vt/automation/scheduler.go | EnqueueClusterOperation | func (s *Scheduler) EnqueueClusterOperation(ctx context.Context, req *automationpb.EnqueueClusterOperationRequest) (*automationpb.EnqueueClusterOperationResponse, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.state != stateRunning {
return nil, fmt.Errorf("scheduler is not running. State: %v", s.state)
}
if !s.registeredClusterOperations[req.Name] {
return nil, fmt.Errorf("no ClusterOperation with name: %v is registered", req.Name)
}
err := s.validateTaskSpecification(req.Name, req.Parameters)
if err != nil {
return nil, err
}
clusterOpID := s.idGenerator.GetNextID()
taskIDGenerator := IDGenerator{}
initialTask := NewTaskContainerWithSingleTask(req.Name, req.Parameters)
clusterOp := NewClusterOperationInstance(clusterOpID, initialTask, &taskIDGenerator)
s.muOpList.Lock()
s.activeClusterOperations[clusterOpID] = clusterOp.Clone()
s.muOpList.Unlock()
s.toBeScheduledClusterOperations <- clusterOp
return &automationpb.EnqueueClusterOperationResponse{
Id: clusterOp.Id,
}, nil
} | go | func (s *Scheduler) EnqueueClusterOperation(ctx context.Context, req *automationpb.EnqueueClusterOperationRequest) (*automationpb.EnqueueClusterOperationResponse, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.state != stateRunning {
return nil, fmt.Errorf("scheduler is not running. State: %v", s.state)
}
if !s.registeredClusterOperations[req.Name] {
return nil, fmt.Errorf("no ClusterOperation with name: %v is registered", req.Name)
}
err := s.validateTaskSpecification(req.Name, req.Parameters)
if err != nil {
return nil, err
}
clusterOpID := s.idGenerator.GetNextID()
taskIDGenerator := IDGenerator{}
initialTask := NewTaskContainerWithSingleTask(req.Name, req.Parameters)
clusterOp := NewClusterOperationInstance(clusterOpID, initialTask, &taskIDGenerator)
s.muOpList.Lock()
s.activeClusterOperations[clusterOpID] = clusterOp.Clone()
s.muOpList.Unlock()
s.toBeScheduledClusterOperations <- clusterOp
return &automationpb.EnqueueClusterOperationResponse{
Id: clusterOp.Id,
}, nil
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"EnqueueClusterOperation",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"automationpb",
".",
"EnqueueClusterOperationRequest",
")",
"(",
"*",
"automationpb",
".",
"EnqueueClusterOperationResponse",
",",
"error",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"s",
".",
"state",
"!=",
"stateRunning",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"s",
".",
"state",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"s",
".",
"registeredClusterOperations",
"[",
"req",
".",
"Name",
"]",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"req",
".",
"Name",
")",
"\n",
"}",
"\n\n",
"err",
":=",
"s",
".",
"validateTaskSpecification",
"(",
"req",
".",
"Name",
",",
"req",
".",
"Parameters",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"clusterOpID",
":=",
"s",
".",
"idGenerator",
".",
"GetNextID",
"(",
")",
"\n",
"taskIDGenerator",
":=",
"IDGenerator",
"{",
"}",
"\n",
"initialTask",
":=",
"NewTaskContainerWithSingleTask",
"(",
"req",
".",
"Name",
",",
"req",
".",
"Parameters",
")",
"\n",
"clusterOp",
":=",
"NewClusterOperationInstance",
"(",
"clusterOpID",
",",
"initialTask",
",",
"&",
"taskIDGenerator",
")",
"\n\n",
"s",
".",
"muOpList",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"activeClusterOperations",
"[",
"clusterOpID",
"]",
"=",
"clusterOp",
".",
"Clone",
"(",
")",
"\n",
"s",
".",
"muOpList",
".",
"Unlock",
"(",
")",
"\n",
"s",
".",
"toBeScheduledClusterOperations",
"<-",
"clusterOp",
"\n\n",
"return",
"&",
"automationpb",
".",
"EnqueueClusterOperationResponse",
"{",
"Id",
":",
"clusterOp",
".",
"Id",
",",
"}",
",",
"nil",
"\n",
"}"
] | // EnqueueClusterOperation can be used to start a new cluster operation. | [
"EnqueueClusterOperation",
"can",
"be",
"used",
"to",
"start",
"a",
"new",
"cluster",
"operation",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/automation/scheduler.go#L307-L337 | train |
vitessio/vitess | go/vt/automation/scheduler.go | findClusterOp | func (s *Scheduler) findClusterOp(id string) (ClusterOperationInstance, error) {
var ok bool
var clusterOp ClusterOperationInstance
s.muOpList.Lock()
defer s.muOpList.Unlock()
clusterOp, ok = s.activeClusterOperations[id]
if !ok {
clusterOp, ok = s.finishedClusterOperations[id]
}
if !ok {
return clusterOp, fmt.Errorf("ClusterOperation with id: %v not found", id)
}
return clusterOp.Clone(), nil
} | go | func (s *Scheduler) findClusterOp(id string) (ClusterOperationInstance, error) {
var ok bool
var clusterOp ClusterOperationInstance
s.muOpList.Lock()
defer s.muOpList.Unlock()
clusterOp, ok = s.activeClusterOperations[id]
if !ok {
clusterOp, ok = s.finishedClusterOperations[id]
}
if !ok {
return clusterOp, fmt.Errorf("ClusterOperation with id: %v not found", id)
}
return clusterOp.Clone(), nil
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"findClusterOp",
"(",
"id",
"string",
")",
"(",
"ClusterOperationInstance",
",",
"error",
")",
"{",
"var",
"ok",
"bool",
"\n",
"var",
"clusterOp",
"ClusterOperationInstance",
"\n\n",
"s",
".",
"muOpList",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"muOpList",
".",
"Unlock",
"(",
")",
"\n",
"clusterOp",
",",
"ok",
"=",
"s",
".",
"activeClusterOperations",
"[",
"id",
"]",
"\n",
"if",
"!",
"ok",
"{",
"clusterOp",
",",
"ok",
"=",
"s",
".",
"finishedClusterOperations",
"[",
"id",
"]",
"\n",
"}",
"\n",
"if",
"!",
"ok",
"{",
"return",
"clusterOp",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"id",
")",
"\n",
"}",
"\n",
"return",
"clusterOp",
".",
"Clone",
"(",
")",
",",
"nil",
"\n",
"}"
] | // findClusterOp checks for a given ClusterOperation ID if it's in the list of active or finished operations. | [
"findClusterOp",
"checks",
"for",
"a",
"given",
"ClusterOperation",
"ID",
"if",
"it",
"s",
"in",
"the",
"list",
"of",
"active",
"or",
"finished",
"operations",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/automation/scheduler.go#L340-L354 | train |
vitessio/vitess | go/vt/automation/scheduler.go | Checkpoint | func (s *Scheduler) Checkpoint(clusterOp ClusterOperationInstance) {
// TODO(mberlin): Add here support for persistent checkpoints.
s.muOpList.Lock()
defer s.muOpList.Unlock()
s.activeClusterOperations[clusterOp.Id] = clusterOp.Clone()
} | go | func (s *Scheduler) Checkpoint(clusterOp ClusterOperationInstance) {
// TODO(mberlin): Add here support for persistent checkpoints.
s.muOpList.Lock()
defer s.muOpList.Unlock()
s.activeClusterOperations[clusterOp.Id] = clusterOp.Clone()
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"Checkpoint",
"(",
"clusterOp",
"ClusterOperationInstance",
")",
"{",
"// TODO(mberlin): Add here support for persistent checkpoints.",
"s",
".",
"muOpList",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"muOpList",
".",
"Unlock",
"(",
")",
"\n",
"s",
".",
"activeClusterOperations",
"[",
"clusterOp",
".",
"Id",
"]",
"=",
"clusterOp",
".",
"Clone",
"(",
")",
"\n",
"}"
] | // Checkpoint should be called every time the state of the cluster op changes.
// It is used to update the copy of the state in activeClusterOperations. | [
"Checkpoint",
"should",
"be",
"called",
"every",
"time",
"the",
"state",
"of",
"the",
"cluster",
"op",
"changes",
".",
"It",
"is",
"used",
"to",
"update",
"the",
"copy",
"of",
"the",
"state",
"in",
"activeClusterOperations",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/automation/scheduler.go#L358-L363 | train |
vitessio/vitess | go/vt/automation/scheduler.go | GetClusterOperationDetails | func (s *Scheduler) GetClusterOperationDetails(ctx context.Context, req *automationpb.GetClusterOperationDetailsRequest) (*automationpb.GetClusterOperationDetailsResponse, error) {
clusterOp, err := s.findClusterOp(req.Id)
if err != nil {
return nil, err
}
return &automationpb.GetClusterOperationDetailsResponse{
ClusterOp: &clusterOp.ClusterOperation,
}, nil
} | go | func (s *Scheduler) GetClusterOperationDetails(ctx context.Context, req *automationpb.GetClusterOperationDetailsRequest) (*automationpb.GetClusterOperationDetailsResponse, error) {
clusterOp, err := s.findClusterOp(req.Id)
if err != nil {
return nil, err
}
return &automationpb.GetClusterOperationDetailsResponse{
ClusterOp: &clusterOp.ClusterOperation,
}, nil
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"GetClusterOperationDetails",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"automationpb",
".",
"GetClusterOperationDetailsRequest",
")",
"(",
"*",
"automationpb",
".",
"GetClusterOperationDetailsResponse",
",",
"error",
")",
"{",
"clusterOp",
",",
"err",
":=",
"s",
".",
"findClusterOp",
"(",
"req",
".",
"Id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"automationpb",
".",
"GetClusterOperationDetailsResponse",
"{",
"ClusterOp",
":",
"&",
"clusterOp",
".",
"ClusterOperation",
",",
"}",
",",
"nil",
"\n",
"}"
] | // GetClusterOperationDetails can be used to query the full details of active or finished operations. | [
"GetClusterOperationDetails",
"can",
"be",
"used",
"to",
"query",
"the",
"full",
"details",
"of",
"active",
"or",
"finished",
"operations",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/automation/scheduler.go#L366-L374 | train |
vitessio/vitess | go/vt/automation/scheduler.go | ShutdownAndWait | func (s *Scheduler) ShutdownAndWait() {
s.mu.Lock()
if s.state != stateShuttingDown {
s.state = stateShuttingDown
close(s.toBeScheduledClusterOperations)
}
s.mu.Unlock()
log.Infof("Scheduler was shut down. Waiting for pending ClusterOperations to finish.")
s.pendingOpsWg.Wait()
s.mu.Lock()
s.state = stateShutdown
s.mu.Unlock()
log.Infof("All pending ClusterOperations finished.")
} | go | func (s *Scheduler) ShutdownAndWait() {
s.mu.Lock()
if s.state != stateShuttingDown {
s.state = stateShuttingDown
close(s.toBeScheduledClusterOperations)
}
s.mu.Unlock()
log.Infof("Scheduler was shut down. Waiting for pending ClusterOperations to finish.")
s.pendingOpsWg.Wait()
s.mu.Lock()
s.state = stateShutdown
s.mu.Unlock()
log.Infof("All pending ClusterOperations finished.")
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"ShutdownAndWait",
"(",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"s",
".",
"state",
"!=",
"stateShuttingDown",
"{",
"s",
".",
"state",
"=",
"stateShuttingDown",
"\n",
"close",
"(",
"s",
".",
"toBeScheduledClusterOperations",
")",
"\n",
"}",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n",
"s",
".",
"pendingOpsWg",
".",
"Wait",
"(",
")",
"\n\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"state",
"=",
"stateShutdown",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // ShutdownAndWait shuts down the scheduler and waits infinitely until all pending cluster operations have finished. | [
"ShutdownAndWait",
"shuts",
"down",
"the",
"scheduler",
"and",
"waits",
"infinitely",
"until",
"all",
"pending",
"cluster",
"operations",
"have",
"finished",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/automation/scheduler.go#L377-L392 | train |
vitessio/vitess | go/vt/topo/memorytopo/memorytopo.go | SetError | func (f *Factory) SetError(err error) {
f.mu.Lock()
defer f.mu.Unlock()
f.err = err
if err != nil {
for _, node := range f.cells {
node.PropagateWatchError(err)
}
}
} | go | func (f *Factory) SetError(err error) {
f.mu.Lock()
defer f.mu.Unlock()
f.err = err
if err != nil {
for _, node := range f.cells {
node.PropagateWatchError(err)
}
}
} | [
"func",
"(",
"f",
"*",
"Factory",
")",
"SetError",
"(",
"err",
"error",
")",
"{",
"f",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"f",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"f",
".",
"err",
"=",
"err",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"for",
"_",
",",
"node",
":=",
"range",
"f",
".",
"cells",
"{",
"node",
".",
"PropagateWatchError",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // SetError forces the given error to be returned from all calls and propagates
// the error to all active watches. | [
"SetError",
"forces",
"the",
"given",
"error",
"to",
"be",
"returned",
"from",
"all",
"calls",
"and",
"propagates",
"the",
"error",
"to",
"all",
"active",
"watches",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/memorytopo/memorytopo.go#L89-L99 | train |
vitessio/vitess | go/vt/topo/memorytopo/memorytopo.go | PropagateWatchError | func (n *node) PropagateWatchError(err error) {
for _, ch := range n.watches {
ch <- &topo.WatchData{
Err: err,
}
}
for _, c := range n.children {
c.PropagateWatchError(err)
}
} | go | func (n *node) PropagateWatchError(err error) {
for _, ch := range n.watches {
ch <- &topo.WatchData{
Err: err,
}
}
for _, c := range n.children {
c.PropagateWatchError(err)
}
} | [
"func",
"(",
"n",
"*",
"node",
")",
"PropagateWatchError",
"(",
"err",
"error",
")",
"{",
"for",
"_",
",",
"ch",
":=",
"range",
"n",
".",
"watches",
"{",
"ch",
"<-",
"&",
"topo",
".",
"WatchData",
"{",
"Err",
":",
"err",
",",
"}",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"c",
":=",
"range",
"n",
".",
"children",
"{",
"c",
".",
"PropagateWatchError",
"(",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // PropagateWatchError propagates the given error to all watches on this node
// and recursively applies to all children | [
"PropagateWatchError",
"propagates",
"the",
"given",
"error",
"to",
"all",
"watches",
"on",
"this",
"node",
"and",
"recursively",
"applies",
"to",
"all",
"children"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/memorytopo/memorytopo.go#L157-L167 | train |
vitessio/vitess | go/vt/topo/memorytopo/memorytopo.go | NewServerAndFactory | func NewServerAndFactory(cells ...string) (*topo.Server, *Factory) {
f := &Factory{
cells: make(map[string]*node),
generation: uint64(rand.Int63n(2 ^ 60)),
}
f.cells[topo.GlobalCell] = f.newDirectory(topo.GlobalCell, nil)
ctx := context.Background()
ts, err := topo.NewWithFactory(f, "" /*serverAddress*/, "" /*root*/)
if err != nil {
log.Exitf("topo.NewWithFactory() failed: %v", err)
}
for _, cell := range cells {
f.cells[cell] = f.newDirectory(cell, nil)
if err := ts.CreateCellInfo(ctx, cell, &topodatapb.CellInfo{}); err != nil {
log.Exitf("ts.CreateCellInfo(%v) failed: %v", cell, err)
}
}
return ts, f
} | go | func NewServerAndFactory(cells ...string) (*topo.Server, *Factory) {
f := &Factory{
cells: make(map[string]*node),
generation: uint64(rand.Int63n(2 ^ 60)),
}
f.cells[topo.GlobalCell] = f.newDirectory(topo.GlobalCell, nil)
ctx := context.Background()
ts, err := topo.NewWithFactory(f, "" /*serverAddress*/, "" /*root*/)
if err != nil {
log.Exitf("topo.NewWithFactory() failed: %v", err)
}
for _, cell := range cells {
f.cells[cell] = f.newDirectory(cell, nil)
if err := ts.CreateCellInfo(ctx, cell, &topodatapb.CellInfo{}); err != nil {
log.Exitf("ts.CreateCellInfo(%v) failed: %v", cell, err)
}
}
return ts, f
} | [
"func",
"NewServerAndFactory",
"(",
"cells",
"...",
"string",
")",
"(",
"*",
"topo",
".",
"Server",
",",
"*",
"Factory",
")",
"{",
"f",
":=",
"&",
"Factory",
"{",
"cells",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"node",
")",
",",
"generation",
":",
"uint64",
"(",
"rand",
".",
"Int63n",
"(",
"2",
"^",
"60",
")",
")",
",",
"}",
"\n",
"f",
".",
"cells",
"[",
"topo",
".",
"GlobalCell",
"]",
"=",
"f",
".",
"newDirectory",
"(",
"topo",
".",
"GlobalCell",
",",
"nil",
")",
"\n\n",
"ctx",
":=",
"context",
".",
"Background",
"(",
")",
"\n",
"ts",
",",
"err",
":=",
"topo",
".",
"NewWithFactory",
"(",
"f",
",",
"\"",
"\"",
"/*serverAddress*/",
",",
"\"",
"\"",
"/*root*/",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Exitf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"cell",
":=",
"range",
"cells",
"{",
"f",
".",
"cells",
"[",
"cell",
"]",
"=",
"f",
".",
"newDirectory",
"(",
"cell",
",",
"nil",
")",
"\n",
"if",
"err",
":=",
"ts",
".",
"CreateCellInfo",
"(",
"ctx",
",",
"cell",
",",
"&",
"topodatapb",
".",
"CellInfo",
"{",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Exitf",
"(",
"\"",
"\"",
",",
"cell",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"ts",
",",
"f",
"\n",
"}"
] | // NewServerAndFactory returns a new MemoryTopo and the backing factory for all
// the cells. It will create one cell for each parameter passed in. It will log.Exit out
// in case of a problem. | [
"NewServerAndFactory",
"returns",
"a",
"new",
"MemoryTopo",
"and",
"the",
"backing",
"factory",
"for",
"all",
"the",
"cells",
".",
"It",
"will",
"create",
"one",
"cell",
"for",
"each",
"parameter",
"passed",
"in",
".",
"It",
"will",
"log",
".",
"Exit",
"out",
"in",
"case",
"of",
"a",
"problem",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/memorytopo/memorytopo.go#L172-L191 | train |
vitessio/vitess | go/vt/topo/memorytopo/memorytopo.go | NewServer | func NewServer(cells ...string) *topo.Server {
server, _ := NewServerAndFactory(cells...)
return server
} | go | func NewServer(cells ...string) *topo.Server {
server, _ := NewServerAndFactory(cells...)
return server
} | [
"func",
"NewServer",
"(",
"cells",
"...",
"string",
")",
"*",
"topo",
".",
"Server",
"{",
"server",
",",
"_",
":=",
"NewServerAndFactory",
"(",
"cells",
"...",
")",
"\n",
"return",
"server",
"\n",
"}"
] | // NewServer returns the new server | [
"NewServer",
"returns",
"the",
"new",
"server"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/memorytopo/memorytopo.go#L194-L197 | train |
vitessio/vitess | go/vt/topo/memorytopo/memorytopo.go | recursiveDelete | func (f *Factory) recursiveDelete(n *node) {
parent := n.parent
if parent == nil {
return
}
delete(parent.children, n.name)
if len(parent.children) == 0 {
f.recursiveDelete(parent)
}
} | go | func (f *Factory) recursiveDelete(n *node) {
parent := n.parent
if parent == nil {
return
}
delete(parent.children, n.name)
if len(parent.children) == 0 {
f.recursiveDelete(parent)
}
} | [
"func",
"(",
"f",
"*",
"Factory",
")",
"recursiveDelete",
"(",
"n",
"*",
"node",
")",
"{",
"parent",
":=",
"n",
".",
"parent",
"\n",
"if",
"parent",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"delete",
"(",
"parent",
".",
"children",
",",
"n",
".",
"name",
")",
"\n",
"if",
"len",
"(",
"parent",
".",
"children",
")",
"==",
"0",
"{",
"f",
".",
"recursiveDelete",
"(",
"parent",
")",
"\n",
"}",
"\n",
"}"
] | // recursiveDelete deletes a node and its parent directory if empty. | [
"recursiveDelete",
"deletes",
"a",
"node",
"and",
"its",
"parent",
"directory",
"if",
"empty",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/memorytopo/memorytopo.go#L277-L286 | train |
vitessio/vitess | go/vt/mysqlctl/grpcmysqlctlserver/server.go | Start | func (s *server) Start(ctx context.Context, request *mysqlctlpb.StartRequest) (*mysqlctlpb.StartResponse, error) {
return &mysqlctlpb.StartResponse{}, s.mysqld.Start(ctx, s.cnf, request.MysqldArgs...)
} | go | func (s *server) Start(ctx context.Context, request *mysqlctlpb.StartRequest) (*mysqlctlpb.StartResponse, error) {
return &mysqlctlpb.StartResponse{}, s.mysqld.Start(ctx, s.cnf, request.MysqldArgs...)
} | [
"func",
"(",
"s",
"*",
"server",
")",
"Start",
"(",
"ctx",
"context",
".",
"Context",
",",
"request",
"*",
"mysqlctlpb",
".",
"StartRequest",
")",
"(",
"*",
"mysqlctlpb",
".",
"StartResponse",
",",
"error",
")",
"{",
"return",
"&",
"mysqlctlpb",
".",
"StartResponse",
"{",
"}",
",",
"s",
".",
"mysqld",
".",
"Start",
"(",
"ctx",
",",
"s",
".",
"cnf",
",",
"request",
".",
"MysqldArgs",
"...",
")",
"\n",
"}"
] | // Start implements the server side of the MysqlctlClient interface. | [
"Start",
"implements",
"the",
"server",
"side",
"of",
"the",
"MysqlctlClient",
"interface",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/grpcmysqlctlserver/server.go#L39-L41 | train |
vitessio/vitess | go/vt/mysqlctl/grpcmysqlctlserver/server.go | Shutdown | func (s *server) Shutdown(ctx context.Context, request *mysqlctlpb.ShutdownRequest) (*mysqlctlpb.ShutdownResponse, error) {
return &mysqlctlpb.ShutdownResponse{}, s.mysqld.Shutdown(ctx, s.cnf, request.WaitForMysqld)
} | go | func (s *server) Shutdown(ctx context.Context, request *mysqlctlpb.ShutdownRequest) (*mysqlctlpb.ShutdownResponse, error) {
return &mysqlctlpb.ShutdownResponse{}, s.mysqld.Shutdown(ctx, s.cnf, request.WaitForMysqld)
} | [
"func",
"(",
"s",
"*",
"server",
")",
"Shutdown",
"(",
"ctx",
"context",
".",
"Context",
",",
"request",
"*",
"mysqlctlpb",
".",
"ShutdownRequest",
")",
"(",
"*",
"mysqlctlpb",
".",
"ShutdownResponse",
",",
"error",
")",
"{",
"return",
"&",
"mysqlctlpb",
".",
"ShutdownResponse",
"{",
"}",
",",
"s",
".",
"mysqld",
".",
"Shutdown",
"(",
"ctx",
",",
"s",
".",
"cnf",
",",
"request",
".",
"WaitForMysqld",
")",
"\n",
"}"
] | // Shutdown implements the server side of the MysqlctlClient interface. | [
"Shutdown",
"implements",
"the",
"server",
"side",
"of",
"the",
"MysqlctlClient",
"interface",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/grpcmysqlctlserver/server.go#L44-L46 | train |
vitessio/vitess | go/vt/mysqlctl/grpcmysqlctlserver/server.go | RunMysqlUpgrade | func (s *server) RunMysqlUpgrade(ctx context.Context, request *mysqlctlpb.RunMysqlUpgradeRequest) (*mysqlctlpb.RunMysqlUpgradeResponse, error) {
return &mysqlctlpb.RunMysqlUpgradeResponse{}, s.mysqld.RunMysqlUpgrade()
} | go | func (s *server) RunMysqlUpgrade(ctx context.Context, request *mysqlctlpb.RunMysqlUpgradeRequest) (*mysqlctlpb.RunMysqlUpgradeResponse, error) {
return &mysqlctlpb.RunMysqlUpgradeResponse{}, s.mysqld.RunMysqlUpgrade()
} | [
"func",
"(",
"s",
"*",
"server",
")",
"RunMysqlUpgrade",
"(",
"ctx",
"context",
".",
"Context",
",",
"request",
"*",
"mysqlctlpb",
".",
"RunMysqlUpgradeRequest",
")",
"(",
"*",
"mysqlctlpb",
".",
"RunMysqlUpgradeResponse",
",",
"error",
")",
"{",
"return",
"&",
"mysqlctlpb",
".",
"RunMysqlUpgradeResponse",
"{",
"}",
",",
"s",
".",
"mysqld",
".",
"RunMysqlUpgrade",
"(",
")",
"\n",
"}"
] | // RunMysqlUpgrade implements the server side of the MysqlctlClient interface. | [
"RunMysqlUpgrade",
"implements",
"the",
"server",
"side",
"of",
"the",
"MysqlctlClient",
"interface",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/grpcmysqlctlserver/server.go#L49-L51 | train |
vitessio/vitess | go/vt/mysqlctl/grpcmysqlctlserver/server.go | ReinitConfig | func (s *server) ReinitConfig(ctx context.Context, request *mysqlctlpb.ReinitConfigRequest) (*mysqlctlpb.ReinitConfigResponse, error) {
return &mysqlctlpb.ReinitConfigResponse{}, s.mysqld.ReinitConfig(ctx, s.cnf)
} | go | func (s *server) ReinitConfig(ctx context.Context, request *mysqlctlpb.ReinitConfigRequest) (*mysqlctlpb.ReinitConfigResponse, error) {
return &mysqlctlpb.ReinitConfigResponse{}, s.mysqld.ReinitConfig(ctx, s.cnf)
} | [
"func",
"(",
"s",
"*",
"server",
")",
"ReinitConfig",
"(",
"ctx",
"context",
".",
"Context",
",",
"request",
"*",
"mysqlctlpb",
".",
"ReinitConfigRequest",
")",
"(",
"*",
"mysqlctlpb",
".",
"ReinitConfigResponse",
",",
"error",
")",
"{",
"return",
"&",
"mysqlctlpb",
".",
"ReinitConfigResponse",
"{",
"}",
",",
"s",
".",
"mysqld",
".",
"ReinitConfig",
"(",
"ctx",
",",
"s",
".",
"cnf",
")",
"\n",
"}"
] | // ReinitConfig implements the server side of the MysqlctlClient interface. | [
"ReinitConfig",
"implements",
"the",
"server",
"side",
"of",
"the",
"MysqlctlClient",
"interface",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/grpcmysqlctlserver/server.go#L54-L56 | train |
vitessio/vitess | go/vt/mysqlctl/grpcmysqlctlserver/server.go | RefreshConfig | func (s *server) RefreshConfig(ctx context.Context, request *mysqlctlpb.RefreshConfigRequest) (*mysqlctlpb.RefreshConfigResponse, error) {
return &mysqlctlpb.RefreshConfigResponse{}, s.mysqld.RefreshConfig(ctx, s.cnf)
} | go | func (s *server) RefreshConfig(ctx context.Context, request *mysqlctlpb.RefreshConfigRequest) (*mysqlctlpb.RefreshConfigResponse, error) {
return &mysqlctlpb.RefreshConfigResponse{}, s.mysqld.RefreshConfig(ctx, s.cnf)
} | [
"func",
"(",
"s",
"*",
"server",
")",
"RefreshConfig",
"(",
"ctx",
"context",
".",
"Context",
",",
"request",
"*",
"mysqlctlpb",
".",
"RefreshConfigRequest",
")",
"(",
"*",
"mysqlctlpb",
".",
"RefreshConfigResponse",
",",
"error",
")",
"{",
"return",
"&",
"mysqlctlpb",
".",
"RefreshConfigResponse",
"{",
"}",
",",
"s",
".",
"mysqld",
".",
"RefreshConfig",
"(",
"ctx",
",",
"s",
".",
"cnf",
")",
"\n",
"}"
] | // RefreshConfig implements the server side of the MysqlctlClient interface. | [
"RefreshConfig",
"implements",
"the",
"server",
"side",
"of",
"the",
"MysqlctlClient",
"interface",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/grpcmysqlctlserver/server.go#L59-L61 | train |
vitessio/vitess | go/vt/mysqlctl/grpcmysqlctlserver/server.go | StartServer | func StartServer(s *grpc.Server, cnf *mysqlctl.Mycnf, mysqld *mysqlctl.Mysqld) {
mysqlctlpb.RegisterMysqlCtlServer(s, &server{cnf: cnf, mysqld: mysqld})
} | go | func StartServer(s *grpc.Server, cnf *mysqlctl.Mycnf, mysqld *mysqlctl.Mysqld) {
mysqlctlpb.RegisterMysqlCtlServer(s, &server{cnf: cnf, mysqld: mysqld})
} | [
"func",
"StartServer",
"(",
"s",
"*",
"grpc",
".",
"Server",
",",
"cnf",
"*",
"mysqlctl",
".",
"Mycnf",
",",
"mysqld",
"*",
"mysqlctl",
".",
"Mysqld",
")",
"{",
"mysqlctlpb",
".",
"RegisterMysqlCtlServer",
"(",
"s",
",",
"&",
"server",
"{",
"cnf",
":",
"cnf",
",",
"mysqld",
":",
"mysqld",
"}",
")",
"\n",
"}"
] | // StartServer registers the Server for RPCs. | [
"StartServer",
"registers",
"the",
"Server",
"for",
"RPCs",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/mysqlctl/grpcmysqlctlserver/server.go#L64-L66 | train |
vitessio/vitess | go/vt/vtgate/vindexes/numeric.go | NewNumeric | func NewNumeric(name string, _ map[string]string) (Vindex, error) {
return &Numeric{name: name}, nil
} | go | func NewNumeric(name string, _ map[string]string) (Vindex, error) {
return &Numeric{name: name}, nil
} | [
"func",
"NewNumeric",
"(",
"name",
"string",
",",
"_",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"Vindex",
",",
"error",
")",
"{",
"return",
"&",
"Numeric",
"{",
"name",
":",
"name",
"}",
",",
"nil",
"\n",
"}"
] | // NewNumeric creates a Numeric vindex. | [
"NewNumeric",
"creates",
"a",
"Numeric",
"vindex",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vindexes/numeric.go#L41-L43 | train |
vitessio/vitess | go/vt/throttler/max_rate_module.go | SetMaxRate | func (m *MaxRateModule) SetMaxRate(rate int64) {
m.maxRate.Set(rate)
m.rateUpdateChan <- struct{}{}
} | go | func (m *MaxRateModule) SetMaxRate(rate int64) {
m.maxRate.Set(rate)
m.rateUpdateChan <- struct{}{}
} | [
"func",
"(",
"m",
"*",
"MaxRateModule",
")",
"SetMaxRate",
"(",
"rate",
"int64",
")",
"{",
"m",
".",
"maxRate",
".",
"Set",
"(",
"rate",
")",
"\n",
"m",
".",
"rateUpdateChan",
"<-",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}"
] | // SetMaxRate sets the current max rate and notifies the throttler about the
// rate update. | [
"SetMaxRate",
"sets",
"the",
"current",
"max",
"rate",
"and",
"notifies",
"the",
"throttler",
"about",
"the",
"rate",
"update",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/max_rate_module.go#L53-L56 | train |
vitessio/vitess | go/vt/vtgate/vindexes/null.go | NewNull | func NewNull(name string, m map[string]string) (Vindex, error) {
return &Null{name: name}, nil
} | go | func NewNull(name string, m map[string]string) (Vindex, error) {
return &Null{name: name}, nil
} | [
"func",
"NewNull",
"(",
"name",
"string",
",",
"m",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"Vindex",
",",
"error",
")",
"{",
"return",
"&",
"Null",
"{",
"name",
":",
"name",
"}",
",",
"nil",
"\n",
"}"
] | // NewNull creates a new Null. | [
"NewNull",
"creates",
"a",
"new",
"Null",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vindexes/null.go#L42-L44 | train |
vitessio/vitess | go/vt/binlog/binlogplayer/mock_dbclient.go | NewMockDBClient | func NewMockDBClient(t *testing.T) *MockDBClient {
return &MockDBClient{
t: t,
done: make(chan struct{}),
}
} | go | func NewMockDBClient(t *testing.T) *MockDBClient {
return &MockDBClient{
t: t,
done: make(chan struct{}),
}
} | [
"func",
"NewMockDBClient",
"(",
"t",
"*",
"testing",
".",
"T",
")",
"*",
"MockDBClient",
"{",
"return",
"&",
"MockDBClient",
"{",
"t",
":",
"t",
",",
"done",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"}",
"\n",
"}"
] | // NewMockDBClient returns a new DBClientMock. | [
"NewMockDBClient",
"returns",
"a",
"new",
"DBClientMock",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/binlog/binlogplayer/mock_dbclient.go#L44-L49 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.