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/mysql/conn.go | writeErrorPacketFromError | func (c *Conn) writeErrorPacketFromError(err error) error {
if se, ok := err.(*SQLError); ok {
return c.writeErrorPacket(uint16(se.Num), se.State, "%v", se.Message)
}
return c.writeErrorPacket(ERUnknownError, SSUnknownSQLState, "unknown error: %v", err)
} | go | func (c *Conn) writeErrorPacketFromError(err error) error {
if se, ok := err.(*SQLError); ok {
return c.writeErrorPacket(uint16(se.Num), se.State, "%v", se.Message)
}
return c.writeErrorPacket(ERUnknownError, SSUnknownSQLState, "unknown error: %v", err)
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"writeErrorPacketFromError",
"(",
"err",
"error",
")",
"error",
"{",
"if",
"se",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"SQLError",
")",
";",
"ok",
"{",
"return",
"c",
".",
"writeErrorPacket",
"(",
"uint16",
"(",
"se",
".",
"Num",
")",
",",
"se",
".",
"State",
",",
"\"",
"\"",
",",
"se",
".",
"Message",
")",
"\n",
"}",
"\n\n",
"return",
"c",
".",
"writeErrorPacket",
"(",
"ERUnknownError",
",",
"SSUnknownSQLState",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}"
] | // writeErrorPacketFromError writes an error packet, from a regular error.
// See writeErrorPacket for other info. | [
"writeErrorPacketFromError",
"writes",
"an",
"error",
"packet",
"from",
"a",
"regular",
"error",
".",
"See",
"writeErrorPacket",
"for",
"other",
"info",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/conn.go#L668-L674 | train |
vitessio/vitess | go/mysql/conn.go | ParseErrorPacket | func ParseErrorPacket(data []byte) error {
// We already read the type.
pos := 1
// Error code is 2 bytes.
code, pos, ok := readUint16(data, pos)
if !ok {
return NewSQLError(CRUnknownError, SSUnknownSQLState, "invalid error packet code: %v", data)
}
// '#' marker of the SQL state is 1 byte. Ignored.
pos++
// SQL state is 5 bytes
sqlState, pos, ok := readBytes(data, pos, 5)
if !ok {
return NewSQLError(CRUnknownError, SSUnknownSQLState, "invalid error packet sqlState: %v", data)
}
// Human readable error message is the rest.
msg := string(data[pos:])
return NewSQLError(int(code), string(sqlState), "%v", msg)
} | go | func ParseErrorPacket(data []byte) error {
// We already read the type.
pos := 1
// Error code is 2 bytes.
code, pos, ok := readUint16(data, pos)
if !ok {
return NewSQLError(CRUnknownError, SSUnknownSQLState, "invalid error packet code: %v", data)
}
// '#' marker of the SQL state is 1 byte. Ignored.
pos++
// SQL state is 5 bytes
sqlState, pos, ok := readBytes(data, pos, 5)
if !ok {
return NewSQLError(CRUnknownError, SSUnknownSQLState, "invalid error packet sqlState: %v", data)
}
// Human readable error message is the rest.
msg := string(data[pos:])
return NewSQLError(int(code), string(sqlState), "%v", msg)
} | [
"func",
"ParseErrorPacket",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"// We already read the type.",
"pos",
":=",
"1",
"\n\n",
"// Error code is 2 bytes.",
"code",
",",
"pos",
",",
"ok",
":=",
"readUint16",
"(",
"data",
",",
"pos",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"NewSQLError",
"(",
"CRUnknownError",
",",
"SSUnknownSQLState",
",",
"\"",
"\"",
",",
"data",
")",
"\n",
"}",
"\n\n",
"// '#' marker of the SQL state is 1 byte. Ignored.",
"pos",
"++",
"\n\n",
"// SQL state is 5 bytes",
"sqlState",
",",
"pos",
",",
"ok",
":=",
"readBytes",
"(",
"data",
",",
"pos",
",",
"5",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"NewSQLError",
"(",
"CRUnknownError",
",",
"SSUnknownSQLState",
",",
"\"",
"\"",
",",
"data",
")",
"\n",
"}",
"\n\n",
"// Human readable error message is the rest.",
"msg",
":=",
"string",
"(",
"data",
"[",
"pos",
":",
"]",
")",
"\n\n",
"return",
"NewSQLError",
"(",
"int",
"(",
"code",
")",
",",
"string",
"(",
"sqlState",
")",
",",
"\"",
"\"",
",",
"msg",
")",
"\n",
"}"
] | // ParseErrorPacket parses the error packet and returns a SQLError. | [
"ParseErrorPacket",
"parses",
"the",
"error",
"packet",
"and",
"returns",
"a",
"SQLError",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/conn.go#L963-L986 | train |
vitessio/vitess | go/mysql/query.go | readColumnDefinitionType | func (c *Conn) readColumnDefinitionType(field *querypb.Field, index int) error {
colDef, err := c.readEphemeralPacket()
if err != nil {
return NewSQLError(CRServerLost, SSUnknownSQLState, "%v", err)
}
defer c.recycleReadPacket()
// catalog, schema, table, orgTable, name and orgName are
// strings, all skipped.
pos, ok := skipLenEncString(colDef, 0)
if !ok {
return NewSQLError(CRMalformedPacket, SSUnknownSQLState, "skipping col %v catalog failed", index)
}
pos, ok = skipLenEncString(colDef, pos)
if !ok {
return NewSQLError(CRMalformedPacket, SSUnknownSQLState, "skipping col %v schema failed", index)
}
pos, ok = skipLenEncString(colDef, pos)
if !ok {
return NewSQLError(CRMalformedPacket, SSUnknownSQLState, "skipping col %v table failed", index)
}
pos, ok = skipLenEncString(colDef, pos)
if !ok {
return NewSQLError(CRMalformedPacket, SSUnknownSQLState, "skipping col %v org_table failed", index)
}
pos, ok = skipLenEncString(colDef, pos)
if !ok {
return NewSQLError(CRMalformedPacket, SSUnknownSQLState, "skipping col %v name failed", index)
}
pos, ok = skipLenEncString(colDef, pos)
if !ok {
return NewSQLError(CRMalformedPacket, SSUnknownSQLState, "skipping col %v org_name failed", index)
}
// Skip length of fixed-length fields.
pos++
// characterSet is a uint16.
_, pos, ok = readUint16(colDef, pos)
if !ok {
return NewSQLError(CRMalformedPacket, SSUnknownSQLState, "extracting col %v characterSet failed", index)
}
// columnLength is a uint32.
_, pos, ok = readUint32(colDef, pos)
if !ok {
return NewSQLError(CRMalformedPacket, SSUnknownSQLState, "extracting col %v columnLength failed", index)
}
// type is one byte
t, pos, ok := readByte(colDef, pos)
if !ok {
return NewSQLError(CRMalformedPacket, SSUnknownSQLState, "extracting col %v type failed", index)
}
// flags is 2 bytes
flags, _, ok := readUint16(colDef, pos)
if !ok {
return NewSQLError(CRMalformedPacket, SSUnknownSQLState, "extracting col %v flags failed", index)
}
// Convert MySQL type to Vitess type.
field.Type, err = sqltypes.MySQLToType(int64(t), int64(flags))
if err != nil {
return NewSQLError(CRMalformedPacket, SSUnknownSQLState, "MySQLToType(%v,%v) failed for column %v: %v", t, flags, index, err)
}
// skip decimals
return nil
} | go | func (c *Conn) readColumnDefinitionType(field *querypb.Field, index int) error {
colDef, err := c.readEphemeralPacket()
if err != nil {
return NewSQLError(CRServerLost, SSUnknownSQLState, "%v", err)
}
defer c.recycleReadPacket()
// catalog, schema, table, orgTable, name and orgName are
// strings, all skipped.
pos, ok := skipLenEncString(colDef, 0)
if !ok {
return NewSQLError(CRMalformedPacket, SSUnknownSQLState, "skipping col %v catalog failed", index)
}
pos, ok = skipLenEncString(colDef, pos)
if !ok {
return NewSQLError(CRMalformedPacket, SSUnknownSQLState, "skipping col %v schema failed", index)
}
pos, ok = skipLenEncString(colDef, pos)
if !ok {
return NewSQLError(CRMalformedPacket, SSUnknownSQLState, "skipping col %v table failed", index)
}
pos, ok = skipLenEncString(colDef, pos)
if !ok {
return NewSQLError(CRMalformedPacket, SSUnknownSQLState, "skipping col %v org_table failed", index)
}
pos, ok = skipLenEncString(colDef, pos)
if !ok {
return NewSQLError(CRMalformedPacket, SSUnknownSQLState, "skipping col %v name failed", index)
}
pos, ok = skipLenEncString(colDef, pos)
if !ok {
return NewSQLError(CRMalformedPacket, SSUnknownSQLState, "skipping col %v org_name failed", index)
}
// Skip length of fixed-length fields.
pos++
// characterSet is a uint16.
_, pos, ok = readUint16(colDef, pos)
if !ok {
return NewSQLError(CRMalformedPacket, SSUnknownSQLState, "extracting col %v characterSet failed", index)
}
// columnLength is a uint32.
_, pos, ok = readUint32(colDef, pos)
if !ok {
return NewSQLError(CRMalformedPacket, SSUnknownSQLState, "extracting col %v columnLength failed", index)
}
// type is one byte
t, pos, ok := readByte(colDef, pos)
if !ok {
return NewSQLError(CRMalformedPacket, SSUnknownSQLState, "extracting col %v type failed", index)
}
// flags is 2 bytes
flags, _, ok := readUint16(colDef, pos)
if !ok {
return NewSQLError(CRMalformedPacket, SSUnknownSQLState, "extracting col %v flags failed", index)
}
// Convert MySQL type to Vitess type.
field.Type, err = sqltypes.MySQLToType(int64(t), int64(flags))
if err != nil {
return NewSQLError(CRMalformedPacket, SSUnknownSQLState, "MySQLToType(%v,%v) failed for column %v: %v", t, flags, index, err)
}
// skip decimals
return nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"readColumnDefinitionType",
"(",
"field",
"*",
"querypb",
".",
"Field",
",",
"index",
"int",
")",
"error",
"{",
"colDef",
",",
"err",
":=",
"c",
".",
"readEphemeralPacket",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"NewSQLError",
"(",
"CRServerLost",
",",
"SSUnknownSQLState",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"c",
".",
"recycleReadPacket",
"(",
")",
"\n\n",
"// catalog, schema, table, orgTable, name and orgName are",
"// strings, all skipped.",
"pos",
",",
"ok",
":=",
"skipLenEncString",
"(",
"colDef",
",",
"0",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"NewSQLError",
"(",
"CRMalformedPacket",
",",
"SSUnknownSQLState",
",",
"\"",
"\"",
",",
"index",
")",
"\n",
"}",
"\n",
"pos",
",",
"ok",
"=",
"skipLenEncString",
"(",
"colDef",
",",
"pos",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"NewSQLError",
"(",
"CRMalformedPacket",
",",
"SSUnknownSQLState",
",",
"\"",
"\"",
",",
"index",
")",
"\n",
"}",
"\n",
"pos",
",",
"ok",
"=",
"skipLenEncString",
"(",
"colDef",
",",
"pos",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"NewSQLError",
"(",
"CRMalformedPacket",
",",
"SSUnknownSQLState",
",",
"\"",
"\"",
",",
"index",
")",
"\n",
"}",
"\n",
"pos",
",",
"ok",
"=",
"skipLenEncString",
"(",
"colDef",
",",
"pos",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"NewSQLError",
"(",
"CRMalformedPacket",
",",
"SSUnknownSQLState",
",",
"\"",
"\"",
",",
"index",
")",
"\n",
"}",
"\n",
"pos",
",",
"ok",
"=",
"skipLenEncString",
"(",
"colDef",
",",
"pos",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"NewSQLError",
"(",
"CRMalformedPacket",
",",
"SSUnknownSQLState",
",",
"\"",
"\"",
",",
"index",
")",
"\n",
"}",
"\n",
"pos",
",",
"ok",
"=",
"skipLenEncString",
"(",
"colDef",
",",
"pos",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"NewSQLError",
"(",
"CRMalformedPacket",
",",
"SSUnknownSQLState",
",",
"\"",
"\"",
",",
"index",
")",
"\n",
"}",
"\n\n",
"// Skip length of fixed-length fields.",
"pos",
"++",
"\n\n",
"// characterSet is a uint16.",
"_",
",",
"pos",
",",
"ok",
"=",
"readUint16",
"(",
"colDef",
",",
"pos",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"NewSQLError",
"(",
"CRMalformedPacket",
",",
"SSUnknownSQLState",
",",
"\"",
"\"",
",",
"index",
")",
"\n",
"}",
"\n\n",
"// columnLength is a uint32.",
"_",
",",
"pos",
",",
"ok",
"=",
"readUint32",
"(",
"colDef",
",",
"pos",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"NewSQLError",
"(",
"CRMalformedPacket",
",",
"SSUnknownSQLState",
",",
"\"",
"\"",
",",
"index",
")",
"\n",
"}",
"\n\n",
"// type is one byte",
"t",
",",
"pos",
",",
"ok",
":=",
"readByte",
"(",
"colDef",
",",
"pos",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"NewSQLError",
"(",
"CRMalformedPacket",
",",
"SSUnknownSQLState",
",",
"\"",
"\"",
",",
"index",
")",
"\n",
"}",
"\n\n",
"// flags is 2 bytes",
"flags",
",",
"_",
",",
"ok",
":=",
"readUint16",
"(",
"colDef",
",",
"pos",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"NewSQLError",
"(",
"CRMalformedPacket",
",",
"SSUnknownSQLState",
",",
"\"",
"\"",
",",
"index",
")",
"\n",
"}",
"\n\n",
"// Convert MySQL type to Vitess type.",
"field",
".",
"Type",
",",
"err",
"=",
"sqltypes",
".",
"MySQLToType",
"(",
"int64",
"(",
"t",
")",
",",
"int64",
"(",
"flags",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"NewSQLError",
"(",
"CRMalformedPacket",
",",
"SSUnknownSQLState",
",",
"\"",
"\"",
",",
"t",
",",
"flags",
",",
"index",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// skip decimals",
"return",
"nil",
"\n",
"}"
] | // readColumnDefinitionType is a faster version of
// readColumnDefinition that only fills in the Type.
// Returns a SQLError. | [
"readColumnDefinitionType",
"is",
"a",
"faster",
"version",
"of",
"readColumnDefinition",
"that",
"only",
"fills",
"in",
"the",
"Type",
".",
"Returns",
"a",
"SQLError",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/query.go#L175-L245 | train |
vitessio/vitess | go/mysql/query.go | parseRow | func (c *Conn) parseRow(data []byte, fields []*querypb.Field) ([]sqltypes.Value, error) {
colNumber := len(fields)
result := make([]sqltypes.Value, colNumber)
pos := 0
for i := 0; i < colNumber; i++ {
if data[pos] == 0xfb {
pos++
continue
}
var s []byte
var ok bool
s, pos, ok = readLenEncStringAsBytes(data, pos)
if !ok {
return nil, NewSQLError(CRMalformedPacket, SSUnknownSQLState, "decoding string failed")
}
result[i] = sqltypes.MakeTrusted(fields[i].Type, s)
}
return result, nil
} | go | func (c *Conn) parseRow(data []byte, fields []*querypb.Field) ([]sqltypes.Value, error) {
colNumber := len(fields)
result := make([]sqltypes.Value, colNumber)
pos := 0
for i := 0; i < colNumber; i++ {
if data[pos] == 0xfb {
pos++
continue
}
var s []byte
var ok bool
s, pos, ok = readLenEncStringAsBytes(data, pos)
if !ok {
return nil, NewSQLError(CRMalformedPacket, SSUnknownSQLState, "decoding string failed")
}
result[i] = sqltypes.MakeTrusted(fields[i].Type, s)
}
return result, nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"parseRow",
"(",
"data",
"[",
"]",
"byte",
",",
"fields",
"[",
"]",
"*",
"querypb",
".",
"Field",
")",
"(",
"[",
"]",
"sqltypes",
".",
"Value",
",",
"error",
")",
"{",
"colNumber",
":=",
"len",
"(",
"fields",
")",
"\n",
"result",
":=",
"make",
"(",
"[",
"]",
"sqltypes",
".",
"Value",
",",
"colNumber",
")",
"\n",
"pos",
":=",
"0",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"colNumber",
";",
"i",
"++",
"{",
"if",
"data",
"[",
"pos",
"]",
"==",
"0xfb",
"{",
"pos",
"++",
"\n",
"continue",
"\n",
"}",
"\n",
"var",
"s",
"[",
"]",
"byte",
"\n",
"var",
"ok",
"bool",
"\n",
"s",
",",
"pos",
",",
"ok",
"=",
"readLenEncStringAsBytes",
"(",
"data",
",",
"pos",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"NewSQLError",
"(",
"CRMalformedPacket",
",",
"SSUnknownSQLState",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"result",
"[",
"i",
"]",
"=",
"sqltypes",
".",
"MakeTrusted",
"(",
"fields",
"[",
"i",
"]",
".",
"Type",
",",
"s",
")",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // parseRow parses an individual row.
// Returns a SQLError. | [
"parseRow",
"parses",
"an",
"individual",
"row",
".",
"Returns",
"a",
"SQLError",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/query.go#L249-L267 | train |
vitessio/vitess | go/mysql/query.go | ExecuteFetchMulti | func (c *Conn) ExecuteFetchMulti(query string, maxrows int, wantfields bool) (result *sqltypes.Result, more bool, err error) {
defer func() {
if err != nil {
if sqlerr, ok := err.(*SQLError); ok {
sqlerr.Query = query
}
}
}()
// Send the query as a COM_QUERY packet.
if err = c.WriteComQuery(query); err != nil {
return nil, false, err
}
res, more, _, err := c.ReadQueryResult(maxrows, wantfields)
return res, more, err
} | go | func (c *Conn) ExecuteFetchMulti(query string, maxrows int, wantfields bool) (result *sqltypes.Result, more bool, err error) {
defer func() {
if err != nil {
if sqlerr, ok := err.(*SQLError); ok {
sqlerr.Query = query
}
}
}()
// Send the query as a COM_QUERY packet.
if err = c.WriteComQuery(query); err != nil {
return nil, false, err
}
res, more, _, err := c.ReadQueryResult(maxrows, wantfields)
return res, more, err
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"ExecuteFetchMulti",
"(",
"query",
"string",
",",
"maxrows",
"int",
",",
"wantfields",
"bool",
")",
"(",
"result",
"*",
"sqltypes",
".",
"Result",
",",
"more",
"bool",
",",
"err",
"error",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
"!=",
"nil",
"{",
"if",
"sqlerr",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"SQLError",
")",
";",
"ok",
"{",
"sqlerr",
".",
"Query",
"=",
"query",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"// Send the query as a COM_QUERY packet.",
"if",
"err",
"=",
"c",
".",
"WriteComQuery",
"(",
"query",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"res",
",",
"more",
",",
"_",
",",
"err",
":=",
"c",
".",
"ReadQueryResult",
"(",
"maxrows",
",",
"wantfields",
")",
"\n",
"return",
"res",
",",
"more",
",",
"err",
"\n",
"}"
] | // ExecuteFetchMulti is for fetching multiple results from a multi-statement result.
// It returns an additional 'more' flag. If it is set, you must fetch the additional
// results using ReadQueryResult. | [
"ExecuteFetchMulti",
"is",
"for",
"fetching",
"multiple",
"results",
"from",
"a",
"multi",
"-",
"statement",
"result",
".",
"It",
"returns",
"an",
"additional",
"more",
"flag",
".",
"If",
"it",
"is",
"set",
"you",
"must",
"fetch",
"the",
"additional",
"results",
"using",
"ReadQueryResult",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/query.go#L300-L316 | train |
vitessio/vitess | go/mysql/query.go | drainResults | func (c *Conn) drainResults() error {
for {
data, err := c.readEphemeralPacket()
if err != nil {
return NewSQLError(CRServerLost, SSUnknownSQLState, "%v", err)
}
if isEOFPacket(data) {
c.recycleReadPacket()
return nil
} else if isErrorPacket(data) {
defer c.recycleReadPacket()
return ParseErrorPacket(data)
}
c.recycleReadPacket()
}
} | go | func (c *Conn) drainResults() error {
for {
data, err := c.readEphemeralPacket()
if err != nil {
return NewSQLError(CRServerLost, SSUnknownSQLState, "%v", err)
}
if isEOFPacket(data) {
c.recycleReadPacket()
return nil
} else if isErrorPacket(data) {
defer c.recycleReadPacket()
return ParseErrorPacket(data)
}
c.recycleReadPacket()
}
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"drainResults",
"(",
")",
"error",
"{",
"for",
"{",
"data",
",",
"err",
":=",
"c",
".",
"readEphemeralPacket",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"NewSQLError",
"(",
"CRServerLost",
",",
"SSUnknownSQLState",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"isEOFPacket",
"(",
"data",
")",
"{",
"c",
".",
"recycleReadPacket",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}",
"else",
"if",
"isErrorPacket",
"(",
"data",
")",
"{",
"defer",
"c",
".",
"recycleReadPacket",
"(",
")",
"\n",
"return",
"ParseErrorPacket",
"(",
"data",
")",
"\n",
"}",
"\n",
"c",
".",
"recycleReadPacket",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // drainResults will read all packets for a result set and ignore them. | [
"drainResults",
"will",
"read",
"all",
"packets",
"for",
"a",
"result",
"set",
"and",
"ignore",
"them",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/query.go#L452-L467 | train |
vitessio/vitess | go/mysql/query.go | writeFields | func (c *Conn) writeFields(result *sqltypes.Result) error {
// Send the number of fields first.
if err := c.sendColumnCount(uint64(len(result.Fields))); err != nil {
return err
}
// Now send each Field.
for _, field := range result.Fields {
if err := c.writeColumnDefinition(field); err != nil {
return err
}
}
// Now send an EOF packet.
if c.Capabilities&CapabilityClientDeprecateEOF == 0 {
// With CapabilityClientDeprecateEOF, we do not send this EOF.
if err := c.writeEOFPacket(c.StatusFlags, 0); err != nil {
return err
}
}
return nil
} | go | func (c *Conn) writeFields(result *sqltypes.Result) error {
// Send the number of fields first.
if err := c.sendColumnCount(uint64(len(result.Fields))); err != nil {
return err
}
// Now send each Field.
for _, field := range result.Fields {
if err := c.writeColumnDefinition(field); err != nil {
return err
}
}
// Now send an EOF packet.
if c.Capabilities&CapabilityClientDeprecateEOF == 0 {
// With CapabilityClientDeprecateEOF, we do not send this EOF.
if err := c.writeEOFPacket(c.StatusFlags, 0); err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"writeFields",
"(",
"result",
"*",
"sqltypes",
".",
"Result",
")",
"error",
"{",
"// Send the number of fields first.",
"if",
"err",
":=",
"c",
".",
"sendColumnCount",
"(",
"uint64",
"(",
"len",
"(",
"result",
".",
"Fields",
")",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Now send each Field.",
"for",
"_",
",",
"field",
":=",
"range",
"result",
".",
"Fields",
"{",
"if",
"err",
":=",
"c",
".",
"writeColumnDefinition",
"(",
"field",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Now send an EOF packet.",
"if",
"c",
".",
"Capabilities",
"&",
"CapabilityClientDeprecateEOF",
"==",
"0",
"{",
"// With CapabilityClientDeprecateEOF, we do not send this EOF.",
"if",
"err",
":=",
"c",
".",
"writeEOFPacket",
"(",
"c",
".",
"StatusFlags",
",",
"0",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // writeFields writes the fields of a Result. It should be called only
// if there are valid columns in the result. | [
"writeFields",
"writes",
"the",
"fields",
"of",
"a",
"Result",
".",
"It",
"should",
"be",
"called",
"only",
"if",
"there",
"are",
"valid",
"columns",
"in",
"the",
"result",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/query.go#L603-L624 | train |
vitessio/vitess | go/mysql/query.go | writeRows | func (c *Conn) writeRows(result *sqltypes.Result) error {
for _, row := range result.Rows {
if err := c.writeRow(row); err != nil {
return err
}
}
return nil
} | go | func (c *Conn) writeRows(result *sqltypes.Result) error {
for _, row := range result.Rows {
if err := c.writeRow(row); err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"writeRows",
"(",
"result",
"*",
"sqltypes",
".",
"Result",
")",
"error",
"{",
"for",
"_",
",",
"row",
":=",
"range",
"result",
".",
"Rows",
"{",
"if",
"err",
":=",
"c",
".",
"writeRow",
"(",
"row",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // writeRows sends the rows of a Result. | [
"writeRows",
"sends",
"the",
"rows",
"of",
"a",
"Result",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/query.go#L627-L634 | train |
vitessio/vitess | go/mysql/query.go | writeEndResult | func (c *Conn) writeEndResult(more bool, affectedRows, lastInsertID uint64, warnings uint16) error {
// Send either an EOF, or an OK packet.
// See doc.go.
flags := c.StatusFlags
if more {
flags |= ServerMoreResultsExists
}
if c.Capabilities&CapabilityClientDeprecateEOF == 0 {
if err := c.writeEOFPacket(flags, warnings); err != nil {
return err
}
} else {
// This will flush too.
if err := c.writeOKPacketWithEOFHeader(affectedRows, lastInsertID, flags, warnings); err != nil {
return err
}
}
return nil
} | go | func (c *Conn) writeEndResult(more bool, affectedRows, lastInsertID uint64, warnings uint16) error {
// Send either an EOF, or an OK packet.
// See doc.go.
flags := c.StatusFlags
if more {
flags |= ServerMoreResultsExists
}
if c.Capabilities&CapabilityClientDeprecateEOF == 0 {
if err := c.writeEOFPacket(flags, warnings); err != nil {
return err
}
} else {
// This will flush too.
if err := c.writeOKPacketWithEOFHeader(affectedRows, lastInsertID, flags, warnings); err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"c",
"*",
"Conn",
")",
"writeEndResult",
"(",
"more",
"bool",
",",
"affectedRows",
",",
"lastInsertID",
"uint64",
",",
"warnings",
"uint16",
")",
"error",
"{",
"// Send either an EOF, or an OK packet.",
"// See doc.go.",
"flags",
":=",
"c",
".",
"StatusFlags",
"\n",
"if",
"more",
"{",
"flags",
"|=",
"ServerMoreResultsExists",
"\n",
"}",
"\n",
"if",
"c",
".",
"Capabilities",
"&",
"CapabilityClientDeprecateEOF",
"==",
"0",
"{",
"if",
"err",
":=",
"c",
".",
"writeEOFPacket",
"(",
"flags",
",",
"warnings",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// This will flush too.",
"if",
"err",
":=",
"c",
".",
"writeOKPacketWithEOFHeader",
"(",
"affectedRows",
",",
"lastInsertID",
",",
"flags",
",",
"warnings",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // writeEndResult concludes the sending of a Result.
// if more is set to true, then it means there are more results afterwords | [
"writeEndResult",
"concludes",
"the",
"sending",
"of",
"a",
"Result",
".",
"if",
"more",
"is",
"set",
"to",
"true",
"then",
"it",
"means",
"there",
"are",
"more",
"results",
"afterwords"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/query.go#L638-L657 | train |
vitessio/vitess | go/vt/sqlparser/parsed_query.go | NewParsedQuery | func NewParsedQuery(node SQLNode) *ParsedQuery {
buf := NewTrackedBuffer(nil)
buf.Myprintf("%v", node)
return buf.ParsedQuery()
} | go | func NewParsedQuery(node SQLNode) *ParsedQuery {
buf := NewTrackedBuffer(nil)
buf.Myprintf("%v", node)
return buf.ParsedQuery()
} | [
"func",
"NewParsedQuery",
"(",
"node",
"SQLNode",
")",
"*",
"ParsedQuery",
"{",
"buf",
":=",
"NewTrackedBuffer",
"(",
"nil",
")",
"\n",
"buf",
".",
"Myprintf",
"(",
"\"",
"\"",
",",
"node",
")",
"\n",
"return",
"buf",
".",
"ParsedQuery",
"(",
")",
"\n",
"}"
] | // NewParsedQuery returns a ParsedQuery of the ast. | [
"NewParsedQuery",
"returns",
"a",
"ParsedQuery",
"of",
"the",
"ast",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/parsed_query.go#L41-L45 | train |
vitessio/vitess | go/vt/sqlparser/parsed_query.go | GenerateQuery | func (pq *ParsedQuery) GenerateQuery(bindVariables map[string]*querypb.BindVariable, extras map[string]Encodable) (string, error) {
if len(pq.bindLocations) == 0 {
return pq.Query, nil
}
var buf strings.Builder
buf.Grow(len(pq.Query))
if err := pq.Append(&buf, bindVariables, extras); err != nil {
return "", err
}
return buf.String(), nil
} | go | func (pq *ParsedQuery) GenerateQuery(bindVariables map[string]*querypb.BindVariable, extras map[string]Encodable) (string, error) {
if len(pq.bindLocations) == 0 {
return pq.Query, nil
}
var buf strings.Builder
buf.Grow(len(pq.Query))
if err := pq.Append(&buf, bindVariables, extras); err != nil {
return "", err
}
return buf.String(), nil
} | [
"func",
"(",
"pq",
"*",
"ParsedQuery",
")",
"GenerateQuery",
"(",
"bindVariables",
"map",
"[",
"string",
"]",
"*",
"querypb",
".",
"BindVariable",
",",
"extras",
"map",
"[",
"string",
"]",
"Encodable",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"len",
"(",
"pq",
".",
"bindLocations",
")",
"==",
"0",
"{",
"return",
"pq",
".",
"Query",
",",
"nil",
"\n",
"}",
"\n",
"var",
"buf",
"strings",
".",
"Builder",
"\n",
"buf",
".",
"Grow",
"(",
"len",
"(",
"pq",
".",
"Query",
")",
")",
"\n",
"if",
"err",
":=",
"pq",
".",
"Append",
"(",
"&",
"buf",
",",
"bindVariables",
",",
"extras",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
",",
"nil",
"\n",
"}"
] | // GenerateQuery generates a query by substituting the specified
// bindVariables. The extras parameter specifies special parameters
// that can perform custom encoding. | [
"GenerateQuery",
"generates",
"a",
"query",
"by",
"substituting",
"the",
"specified",
"bindVariables",
".",
"The",
"extras",
"parameter",
"specifies",
"special",
"parameters",
"that",
"can",
"perform",
"custom",
"encoding",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/parsed_query.go#L50-L60 | train |
vitessio/vitess | go/vt/sqlparser/parsed_query.go | Append | func (pq *ParsedQuery) Append(buf *strings.Builder, bindVariables map[string]*querypb.BindVariable, extras map[string]Encodable) error {
current := 0
for _, loc := range pq.bindLocations {
buf.WriteString(pq.Query[current:loc.offset])
name := pq.Query[loc.offset : loc.offset+loc.length]
if encodable, ok := extras[name[1:]]; ok {
encodable.EncodeSQL(buf)
} else {
supplied, _, err := FetchBindVar(name, bindVariables)
if err != nil {
return err
}
EncodeValue(buf, supplied)
}
current = loc.offset + loc.length
}
buf.WriteString(pq.Query[current:])
return nil
} | go | func (pq *ParsedQuery) Append(buf *strings.Builder, bindVariables map[string]*querypb.BindVariable, extras map[string]Encodable) error {
current := 0
for _, loc := range pq.bindLocations {
buf.WriteString(pq.Query[current:loc.offset])
name := pq.Query[loc.offset : loc.offset+loc.length]
if encodable, ok := extras[name[1:]]; ok {
encodable.EncodeSQL(buf)
} else {
supplied, _, err := FetchBindVar(name, bindVariables)
if err != nil {
return err
}
EncodeValue(buf, supplied)
}
current = loc.offset + loc.length
}
buf.WriteString(pq.Query[current:])
return nil
} | [
"func",
"(",
"pq",
"*",
"ParsedQuery",
")",
"Append",
"(",
"buf",
"*",
"strings",
".",
"Builder",
",",
"bindVariables",
"map",
"[",
"string",
"]",
"*",
"querypb",
".",
"BindVariable",
",",
"extras",
"map",
"[",
"string",
"]",
"Encodable",
")",
"error",
"{",
"current",
":=",
"0",
"\n",
"for",
"_",
",",
"loc",
":=",
"range",
"pq",
".",
"bindLocations",
"{",
"buf",
".",
"WriteString",
"(",
"pq",
".",
"Query",
"[",
"current",
":",
"loc",
".",
"offset",
"]",
")",
"\n",
"name",
":=",
"pq",
".",
"Query",
"[",
"loc",
".",
"offset",
":",
"loc",
".",
"offset",
"+",
"loc",
".",
"length",
"]",
"\n",
"if",
"encodable",
",",
"ok",
":=",
"extras",
"[",
"name",
"[",
"1",
":",
"]",
"]",
";",
"ok",
"{",
"encodable",
".",
"EncodeSQL",
"(",
"buf",
")",
"\n",
"}",
"else",
"{",
"supplied",
",",
"_",
",",
"err",
":=",
"FetchBindVar",
"(",
"name",
",",
"bindVariables",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"EncodeValue",
"(",
"buf",
",",
"supplied",
")",
"\n",
"}",
"\n",
"current",
"=",
"loc",
".",
"offset",
"+",
"loc",
".",
"length",
"\n",
"}",
"\n",
"buf",
".",
"WriteString",
"(",
"pq",
".",
"Query",
"[",
"current",
":",
"]",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Append appends the generated query to the provided buffer. | [
"Append",
"appends",
"the",
"generated",
"query",
"to",
"the",
"provided",
"buffer",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/parsed_query.go#L63-L81 | train |
vitessio/vitess | go/vt/sqlparser/parsed_query.go | MarshalJSON | func (pq *ParsedQuery) MarshalJSON() ([]byte, error) {
return json.Marshal(TruncateForUI(pq.Query))
} | go | func (pq *ParsedQuery) MarshalJSON() ([]byte, error) {
return json.Marshal(TruncateForUI(pq.Query))
} | [
"func",
"(",
"pq",
"*",
"ParsedQuery",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"json",
".",
"Marshal",
"(",
"TruncateForUI",
"(",
"pq",
".",
"Query",
")",
")",
"\n",
"}"
] | // MarshalJSON is a custom JSON marshaler for ParsedQuery.
// Note that any queries longer that 512 bytes will be truncated. | [
"MarshalJSON",
"is",
"a",
"custom",
"JSON",
"marshaler",
"for",
"ParsedQuery",
".",
"Note",
"that",
"any",
"queries",
"longer",
"that",
"512",
"bytes",
"will",
"be",
"truncated",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/parsed_query.go#L85-L87 | train |
vitessio/vitess | go/vt/sqlparser/parsed_query.go | FetchBindVar | func FetchBindVar(name string, bindVariables map[string]*querypb.BindVariable) (val *querypb.BindVariable, isList bool, err error) {
name = name[1:]
if name[0] == ':' {
name = name[1:]
isList = true
}
supplied, ok := bindVariables[name]
if !ok {
return nil, false, fmt.Errorf("missing bind var %s", name)
}
if isList {
if supplied.Type != querypb.Type_TUPLE {
return nil, false, fmt.Errorf("unexpected list arg type (%v) for key %s", supplied.Type, name)
}
if len(supplied.Values) == 0 {
return nil, false, fmt.Errorf("empty list supplied for %s", name)
}
return supplied, true, nil
}
if supplied.Type == querypb.Type_TUPLE {
return nil, false, fmt.Errorf("unexpected arg type (TUPLE) for non-list key %s", name)
}
return supplied, false, nil
} | go | func FetchBindVar(name string, bindVariables map[string]*querypb.BindVariable) (val *querypb.BindVariable, isList bool, err error) {
name = name[1:]
if name[0] == ':' {
name = name[1:]
isList = true
}
supplied, ok := bindVariables[name]
if !ok {
return nil, false, fmt.Errorf("missing bind var %s", name)
}
if isList {
if supplied.Type != querypb.Type_TUPLE {
return nil, false, fmt.Errorf("unexpected list arg type (%v) for key %s", supplied.Type, name)
}
if len(supplied.Values) == 0 {
return nil, false, fmt.Errorf("empty list supplied for %s", name)
}
return supplied, true, nil
}
if supplied.Type == querypb.Type_TUPLE {
return nil, false, fmt.Errorf("unexpected arg type (TUPLE) for non-list key %s", name)
}
return supplied, false, nil
} | [
"func",
"FetchBindVar",
"(",
"name",
"string",
",",
"bindVariables",
"map",
"[",
"string",
"]",
"*",
"querypb",
".",
"BindVariable",
")",
"(",
"val",
"*",
"querypb",
".",
"BindVariable",
",",
"isList",
"bool",
",",
"err",
"error",
")",
"{",
"name",
"=",
"name",
"[",
"1",
":",
"]",
"\n",
"if",
"name",
"[",
"0",
"]",
"==",
"':'",
"{",
"name",
"=",
"name",
"[",
"1",
":",
"]",
"\n",
"isList",
"=",
"true",
"\n",
"}",
"\n",
"supplied",
",",
"ok",
":=",
"bindVariables",
"[",
"name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n\n",
"if",
"isList",
"{",
"if",
"supplied",
".",
"Type",
"!=",
"querypb",
".",
"Type_TUPLE",
"{",
"return",
"nil",
",",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"supplied",
".",
"Type",
",",
"name",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"supplied",
".",
"Values",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"return",
"supplied",
",",
"true",
",",
"nil",
"\n",
"}",
"\n\n",
"if",
"supplied",
".",
"Type",
"==",
"querypb",
".",
"Type_TUPLE",
"{",
"return",
"nil",
",",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n\n",
"return",
"supplied",
",",
"false",
",",
"nil",
"\n",
"}"
] | // FetchBindVar resolves the bind variable by fetching it from bindVariables. | [
"FetchBindVar",
"resolves",
"the",
"bind",
"variable",
"by",
"fetching",
"it",
"from",
"bindVariables",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/parsed_query.go#L110-L136 | train |
vitessio/vitess | go/vt/concurrency/error_recorder.go | Error | func (fer *FirstErrorRecorder) Error() error {
fer.mu.Lock()
defer fer.mu.Unlock()
return fer.firstError
} | go | func (fer *FirstErrorRecorder) Error() error {
fer.mu.Lock()
defer fer.mu.Unlock()
return fer.firstError
} | [
"func",
"(",
"fer",
"*",
"FirstErrorRecorder",
")",
"Error",
"(",
")",
"error",
"{",
"fer",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"fer",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"fer",
".",
"firstError",
"\n",
"}"
] | // Error returns the first error we saw, or nil | [
"Error",
"returns",
"the",
"first",
"error",
"we",
"saw",
"or",
"nil"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/concurrency/error_recorder.go#L70-L74 | train |
vitessio/vitess | go/vt/concurrency/error_recorder.go | AggrError | func (aer *AllErrorRecorder) AggrError(aggr AllErrorAggregator) error {
aer.mu.Lock()
defer aer.mu.Unlock()
if len(aer.Errors) == 0 {
return nil
}
return aggr(aer.Errors)
} | go | func (aer *AllErrorRecorder) AggrError(aggr AllErrorAggregator) error {
aer.mu.Lock()
defer aer.mu.Unlock()
if len(aer.Errors) == 0 {
return nil
}
return aggr(aer.Errors)
} | [
"func",
"(",
"aer",
"*",
"AllErrorRecorder",
")",
"AggrError",
"(",
"aggr",
"AllErrorAggregator",
")",
"error",
"{",
"aer",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"aer",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"len",
"(",
"aer",
".",
"Errors",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"aggr",
"(",
"aer",
".",
"Errors",
")",
"\n",
"}"
] | // AggrError runs the provided aggregator over all errors
// and returns the error from aggregator. | [
"AggrError",
"runs",
"the",
"provided",
"aggregator",
"over",
"all",
"errors",
"and",
"returns",
"the",
"error",
"from",
"aggregator",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/concurrency/error_recorder.go#L105-L112 | train |
vitessio/vitess | go/vt/concurrency/error_recorder.go | Error | func (aer *AllErrorRecorder) Error() error {
return aer.AggrError(func(errors []error) error {
errs := make([]string, 0, len(errors))
for _, e := range errors {
errs = append(errs, e.Error())
}
return fmt.Errorf("%v", strings.Join(errs, ";"))
})
} | go | func (aer *AllErrorRecorder) Error() error {
return aer.AggrError(func(errors []error) error {
errs := make([]string, 0, len(errors))
for _, e := range errors {
errs = append(errs, e.Error())
}
return fmt.Errorf("%v", strings.Join(errs, ";"))
})
} | [
"func",
"(",
"aer",
"*",
"AllErrorRecorder",
")",
"Error",
"(",
")",
"error",
"{",
"return",
"aer",
".",
"AggrError",
"(",
"func",
"(",
"errors",
"[",
"]",
"error",
")",
"error",
"{",
"errs",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"errors",
")",
")",
"\n",
"for",
"_",
",",
"e",
":=",
"range",
"errors",
"{",
"errs",
"=",
"append",
"(",
"errs",
",",
"e",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"strings",
".",
"Join",
"(",
"errs",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
")",
"\n",
"}"
] | // Error returns an aggregate of all errors by concatenation. | [
"Error",
"returns",
"an",
"aggregate",
"of",
"all",
"errors",
"by",
"concatenation",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/concurrency/error_recorder.go#L115-L123 | train |
vitessio/vitess | go/vt/concurrency/error_recorder.go | ErrorStrings | func (aer *AllErrorRecorder) ErrorStrings() []string {
aer.mu.Lock()
defer aer.mu.Unlock()
if len(aer.Errors) == 0 {
return nil
}
errs := make([]string, 0, len(aer.Errors))
for _, e := range aer.Errors {
errs = append(errs, e.Error())
}
return errs
} | go | func (aer *AllErrorRecorder) ErrorStrings() []string {
aer.mu.Lock()
defer aer.mu.Unlock()
if len(aer.Errors) == 0 {
return nil
}
errs := make([]string, 0, len(aer.Errors))
for _, e := range aer.Errors {
errs = append(errs, e.Error())
}
return errs
} | [
"func",
"(",
"aer",
"*",
"AllErrorRecorder",
")",
"ErrorStrings",
"(",
")",
"[",
"]",
"string",
"{",
"aer",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"aer",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"len",
"(",
"aer",
".",
"Errors",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"errs",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"aer",
".",
"Errors",
")",
")",
"\n",
"for",
"_",
",",
"e",
":=",
"range",
"aer",
".",
"Errors",
"{",
"errs",
"=",
"append",
"(",
"errs",
",",
"e",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"errs",
"\n",
"}"
] | // ErrorStrings returns all errors as string array. | [
"ErrorStrings",
"returns",
"all",
"errors",
"as",
"string",
"array",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/concurrency/error_recorder.go#L126-L137 | train |
vitessio/vitess | go/vt/concurrency/error_recorder.go | GetErrors | func (aer *AllErrorRecorder) GetErrors() []error {
aer.mu.Lock()
defer aer.mu.Unlock()
return aer.Errors
} | go | func (aer *AllErrorRecorder) GetErrors() []error {
aer.mu.Lock()
defer aer.mu.Unlock()
return aer.Errors
} | [
"func",
"(",
"aer",
"*",
"AllErrorRecorder",
")",
"GetErrors",
"(",
")",
"[",
"]",
"error",
"{",
"aer",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"aer",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"aer",
".",
"Errors",
"\n",
"}"
] | // GetErrors returns a reference to the internal errors array.
//
// Note that the array is not copied, so this should only be used
// once the recording is complete. | [
"GetErrors",
"returns",
"a",
"reference",
"to",
"the",
"internal",
"errors",
"array",
".",
"Note",
"that",
"the",
"array",
"is",
"not",
"copied",
"so",
"this",
"should",
"only",
"be",
"used",
"once",
"the",
"recording",
"is",
"complete",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/concurrency/error_recorder.go#L143-L147 | train |
vitessio/vitess | go/vt/workflow/parallel_runner.go | NewParallelRunner | func NewParallelRunner(ctx context.Context, rootUINode *Node, cp *CheckpointWriter, tasks []*workflowpb.Task, executeFunc func(context.Context, *workflowpb.Task) error, concurrencyLevel level, enableApprovals bool) *ParallelRunner {
if len(tasks) < 1 {
log.Fatal("BUG: No tasks passed into ParallelRunner")
}
phaseID := path.Dir(tasks[0].Id)
phaseUINode, err := rootUINode.GetChildByPath(phaseID)
if err != nil {
log.Fatalf("BUG: nodepath %v not found", phaseID)
}
p := &ParallelRunner{
ctx: ctx,
uiLogger: logutil.NewMemoryLogger(),
rootUINode: rootUINode,
phaseUINode: phaseUINode,
checkpointWriter: cp,
tasks: tasks,
executeFunc: executeFunc,
concurrencyLevel: concurrencyLevel,
retryActionRegistry: make(map[string]chan struct{}),
enableApprovals: enableApprovals,
}
if p.enableApprovals {
p.initApprovalActions()
}
return p
} | go | func NewParallelRunner(ctx context.Context, rootUINode *Node, cp *CheckpointWriter, tasks []*workflowpb.Task, executeFunc func(context.Context, *workflowpb.Task) error, concurrencyLevel level, enableApprovals bool) *ParallelRunner {
if len(tasks) < 1 {
log.Fatal("BUG: No tasks passed into ParallelRunner")
}
phaseID := path.Dir(tasks[0].Id)
phaseUINode, err := rootUINode.GetChildByPath(phaseID)
if err != nil {
log.Fatalf("BUG: nodepath %v not found", phaseID)
}
p := &ParallelRunner{
ctx: ctx,
uiLogger: logutil.NewMemoryLogger(),
rootUINode: rootUINode,
phaseUINode: phaseUINode,
checkpointWriter: cp,
tasks: tasks,
executeFunc: executeFunc,
concurrencyLevel: concurrencyLevel,
retryActionRegistry: make(map[string]chan struct{}),
enableApprovals: enableApprovals,
}
if p.enableApprovals {
p.initApprovalActions()
}
return p
} | [
"func",
"NewParallelRunner",
"(",
"ctx",
"context",
".",
"Context",
",",
"rootUINode",
"*",
"Node",
",",
"cp",
"*",
"CheckpointWriter",
",",
"tasks",
"[",
"]",
"*",
"workflowpb",
".",
"Task",
",",
"executeFunc",
"func",
"(",
"context",
".",
"Context",
",",
"*",
"workflowpb",
".",
"Task",
")",
"error",
",",
"concurrencyLevel",
"level",
",",
"enableApprovals",
"bool",
")",
"*",
"ParallelRunner",
"{",
"if",
"len",
"(",
"tasks",
")",
"<",
"1",
"{",
"log",
".",
"Fatal",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"phaseID",
":=",
"path",
".",
"Dir",
"(",
"tasks",
"[",
"0",
"]",
".",
"Id",
")",
"\n",
"phaseUINode",
",",
"err",
":=",
"rootUINode",
".",
"GetChildByPath",
"(",
"phaseID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"phaseID",
")",
"\n",
"}",
"\n\n",
"p",
":=",
"&",
"ParallelRunner",
"{",
"ctx",
":",
"ctx",
",",
"uiLogger",
":",
"logutil",
".",
"NewMemoryLogger",
"(",
")",
",",
"rootUINode",
":",
"rootUINode",
",",
"phaseUINode",
":",
"phaseUINode",
",",
"checkpointWriter",
":",
"cp",
",",
"tasks",
":",
"tasks",
",",
"executeFunc",
":",
"executeFunc",
",",
"concurrencyLevel",
":",
"concurrencyLevel",
",",
"retryActionRegistry",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"chan",
"struct",
"{",
"}",
")",
",",
"enableApprovals",
":",
"enableApprovals",
",",
"}",
"\n\n",
"if",
"p",
".",
"enableApprovals",
"{",
"p",
".",
"initApprovalActions",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"p",
"\n",
"}"
] | // NewParallelRunner returns a new ParallelRunner. | [
"NewParallelRunner",
"returns",
"a",
"new",
"ParallelRunner",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/parallel_runner.go#L84-L113 | train |
vitessio/vitess | go/vt/workflow/parallel_runner.go | Run | func (p *ParallelRunner) Run() error {
// default value is 0. The task will not run in this case.
var parallelNum int
switch p.concurrencyLevel {
case Sequential:
parallelNum = 1
case Parallel:
parallelNum = len(p.tasks)
default:
log.Fatalf("BUG: Invalid concurrency level: %v", p.concurrencyLevel)
}
// sem is a channel used to control the level of concurrency.
sem := make(chan bool, parallelNum)
wg := sync.WaitGroup{}
for i, task := range p.tasks {
if isTaskSucceeded(task) {
continue
}
sem <- true
if p.enableApprovals && !isTaskRunning(task) {
p.waitForApproval(i)
}
select {
case <-p.ctx.Done():
// Break this run and return early. Do not try to execute any subsequent tasks.
log.Infof("Workflow is cancelled, remaining tasks will be aborted")
return nil
default:
wg.Add(1)
go func(t *workflowpb.Task) {
defer wg.Done()
p.setUIMessage(fmt.Sprintf("Launch task: %v.", t.Id))
defer func() { <-sem }()
p.executeTask(t)
}(task)
}
}
wg.Wait()
if p.enableApprovals {
p.clearPhaseActions()
}
// TODO(yipeiw): collect error message from tasks.Error instead,
// s.t. if the task is retried, we can update the error
return nil
} | go | func (p *ParallelRunner) Run() error {
// default value is 0. The task will not run in this case.
var parallelNum int
switch p.concurrencyLevel {
case Sequential:
parallelNum = 1
case Parallel:
parallelNum = len(p.tasks)
default:
log.Fatalf("BUG: Invalid concurrency level: %v", p.concurrencyLevel)
}
// sem is a channel used to control the level of concurrency.
sem := make(chan bool, parallelNum)
wg := sync.WaitGroup{}
for i, task := range p.tasks {
if isTaskSucceeded(task) {
continue
}
sem <- true
if p.enableApprovals && !isTaskRunning(task) {
p.waitForApproval(i)
}
select {
case <-p.ctx.Done():
// Break this run and return early. Do not try to execute any subsequent tasks.
log.Infof("Workflow is cancelled, remaining tasks will be aborted")
return nil
default:
wg.Add(1)
go func(t *workflowpb.Task) {
defer wg.Done()
p.setUIMessage(fmt.Sprintf("Launch task: %v.", t.Id))
defer func() { <-sem }()
p.executeTask(t)
}(task)
}
}
wg.Wait()
if p.enableApprovals {
p.clearPhaseActions()
}
// TODO(yipeiw): collect error message from tasks.Error instead,
// s.t. if the task is retried, we can update the error
return nil
} | [
"func",
"(",
"p",
"*",
"ParallelRunner",
")",
"Run",
"(",
")",
"error",
"{",
"// default value is 0. The task will not run in this case.",
"var",
"parallelNum",
"int",
"\n",
"switch",
"p",
".",
"concurrencyLevel",
"{",
"case",
"Sequential",
":",
"parallelNum",
"=",
"1",
"\n",
"case",
"Parallel",
":",
"parallelNum",
"=",
"len",
"(",
"p",
".",
"tasks",
")",
"\n",
"default",
":",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"p",
".",
"concurrencyLevel",
")",
"\n",
"}",
"\n",
"// sem is a channel used to control the level of concurrency.",
"sem",
":=",
"make",
"(",
"chan",
"bool",
",",
"parallelNum",
")",
"\n",
"wg",
":=",
"sync",
".",
"WaitGroup",
"{",
"}",
"\n",
"for",
"i",
",",
"task",
":=",
"range",
"p",
".",
"tasks",
"{",
"if",
"isTaskSucceeded",
"(",
"task",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"sem",
"<-",
"true",
"\n",
"if",
"p",
".",
"enableApprovals",
"&&",
"!",
"isTaskRunning",
"(",
"task",
")",
"{",
"p",
".",
"waitForApproval",
"(",
"i",
")",
"\n",
"}",
"\n",
"select",
"{",
"case",
"<-",
"p",
".",
"ctx",
".",
"Done",
"(",
")",
":",
"// Break this run and return early. Do not try to execute any subsequent tasks.",
"log",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"default",
":",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
"t",
"*",
"workflowpb",
".",
"Task",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n",
"p",
".",
"setUIMessage",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"t",
".",
"Id",
")",
")",
"\n",
"defer",
"func",
"(",
")",
"{",
"<-",
"sem",
"}",
"(",
")",
"\n",
"p",
".",
"executeTask",
"(",
"t",
")",
"\n",
"}",
"(",
"task",
")",
"\n",
"}",
"\n",
"}",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n\n",
"if",
"p",
".",
"enableApprovals",
"{",
"p",
".",
"clearPhaseActions",
"(",
")",
"\n",
"}",
"\n",
"// TODO(yipeiw): collect error message from tasks.Error instead,",
"// s.t. if the task is retried, we can update the error",
"return",
"nil",
"\n",
"}"
] | // Run is the entry point for controlling task executions. | [
"Run",
"is",
"the",
"entry",
"point",
"for",
"controlling",
"task",
"executions",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/parallel_runner.go#L116-L162 | train |
vitessio/vitess | go/vt/workflow/parallel_runner.go | Action | func (p *ParallelRunner) Action(ctx context.Context, path, name string) error {
switch name {
case actionNameRetry:
// Extract the path relative to the root node.
parts := strings.Split(path, "/")
taskID := strings.Join(parts[2:], "/")
return p.triggerRetry(taskID)
case actionNameApproveFirstTask:
p.mu.Lock()
defer p.mu.Unlock()
if p.firstTaskApproved != nil {
close(p.firstTaskApproved)
p.firstTaskApproved = nil
return nil
}
return fmt.Errorf("ignored the approval action %v because no pending approval found: it might be already approved before", actionNameApproveFirstTask)
case actionNameApproveRemainingTasks:
p.mu.Lock()
defer p.mu.Unlock()
if p.remainingTasksApproved != nil {
close(p.remainingTasksApproved)
p.remainingTasksApproved = nil
return nil
}
return fmt.Errorf("ignored the approval action %v because no pending approval found: it might be already approved before", actionNameApproveRemainingTasks)
default:
return fmt.Errorf("unknown action: %v", name)
}
} | go | func (p *ParallelRunner) Action(ctx context.Context, path, name string) error {
switch name {
case actionNameRetry:
// Extract the path relative to the root node.
parts := strings.Split(path, "/")
taskID := strings.Join(parts[2:], "/")
return p.triggerRetry(taskID)
case actionNameApproveFirstTask:
p.mu.Lock()
defer p.mu.Unlock()
if p.firstTaskApproved != nil {
close(p.firstTaskApproved)
p.firstTaskApproved = nil
return nil
}
return fmt.Errorf("ignored the approval action %v because no pending approval found: it might be already approved before", actionNameApproveFirstTask)
case actionNameApproveRemainingTasks:
p.mu.Lock()
defer p.mu.Unlock()
if p.remainingTasksApproved != nil {
close(p.remainingTasksApproved)
p.remainingTasksApproved = nil
return nil
}
return fmt.Errorf("ignored the approval action %v because no pending approval found: it might be already approved before", actionNameApproveRemainingTasks)
default:
return fmt.Errorf("unknown action: %v", name)
}
} | [
"func",
"(",
"p",
"*",
"ParallelRunner",
")",
"Action",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
",",
"name",
"string",
")",
"error",
"{",
"switch",
"name",
"{",
"case",
"actionNameRetry",
":",
"// Extract the path relative to the root node.",
"parts",
":=",
"strings",
".",
"Split",
"(",
"path",
",",
"\"",
"\"",
")",
"\n",
"taskID",
":=",
"strings",
".",
"Join",
"(",
"parts",
"[",
"2",
":",
"]",
",",
"\"",
"\"",
")",
"\n",
"return",
"p",
".",
"triggerRetry",
"(",
"taskID",
")",
"\n",
"case",
"actionNameApproveFirstTask",
":",
"p",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"p",
".",
"firstTaskApproved",
"!=",
"nil",
"{",
"close",
"(",
"p",
".",
"firstTaskApproved",
")",
"\n",
"p",
".",
"firstTaskApproved",
"=",
"nil",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"actionNameApproveFirstTask",
")",
"\n",
"case",
"actionNameApproveRemainingTasks",
":",
"p",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"p",
".",
"remainingTasksApproved",
"!=",
"nil",
"{",
"close",
"(",
"p",
".",
"remainingTasksApproved",
")",
"\n",
"p",
".",
"remainingTasksApproved",
"=",
"nil",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"actionNameApproveRemainingTasks",
")",
"\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"}"
] | // Action handles retrying, approval of the first task and approval of the
// remaining tasks actions. It implements the interface ActionListener. | [
"Action",
"handles",
"retrying",
"approval",
"of",
"the",
"first",
"task",
"and",
"approval",
"of",
"the",
"remaining",
"tasks",
"actions",
".",
"It",
"implements",
"the",
"interface",
"ActionListener",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/parallel_runner.go#L208-L238 | train |
vitessio/vitess | go/vt/workflow/parallel_runner.go | VerifyAllTasksDone | func VerifyAllTasksDone(ctx context.Context, ts *topo.Server, uuid string) error {
return verifyAllTasksState(ctx, ts, uuid, workflowpb.TaskState_TaskDone)
} | go | func VerifyAllTasksDone(ctx context.Context, ts *topo.Server, uuid string) error {
return verifyAllTasksState(ctx, ts, uuid, workflowpb.TaskState_TaskDone)
} | [
"func",
"VerifyAllTasksDone",
"(",
"ctx",
"context",
".",
"Context",
",",
"ts",
"*",
"topo",
".",
"Server",
",",
"uuid",
"string",
")",
"error",
"{",
"return",
"verifyAllTasksState",
"(",
"ctx",
",",
"ts",
",",
"uuid",
",",
"workflowpb",
".",
"TaskState_TaskDone",
")",
"\n",
"}"
] | // VerifyAllTasksDone checks that all tasks are done in a workflow. This should only be used for test purposes. | [
"VerifyAllTasksDone",
"checks",
"that",
"all",
"tasks",
"are",
"done",
"in",
"a",
"workflow",
".",
"This",
"should",
"only",
"be",
"used",
"for",
"test",
"purposes",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/parallel_runner.go#L429-L431 | train |
vitessio/vitess | go/vt/workflow/parallel_runner.go | verifyAllTasksState | func verifyAllTasksState(ctx context.Context, ts *topo.Server, uuid string, taskState workflowpb.TaskState) error {
checkpoint, err := checkpoint(ctx, ts, uuid)
if err != nil {
return err
}
for _, task := range checkpoint.Tasks {
if task.State != taskState || task.Error != "" {
return fmt.Errorf("task: %v should succeed: task status: %v, %v", task.Id, task.State, task.Attributes)
}
}
return nil
} | go | func verifyAllTasksState(ctx context.Context, ts *topo.Server, uuid string, taskState workflowpb.TaskState) error {
checkpoint, err := checkpoint(ctx, ts, uuid)
if err != nil {
return err
}
for _, task := range checkpoint.Tasks {
if task.State != taskState || task.Error != "" {
return fmt.Errorf("task: %v should succeed: task status: %v, %v", task.Id, task.State, task.Attributes)
}
}
return nil
} | [
"func",
"verifyAllTasksState",
"(",
"ctx",
"context",
".",
"Context",
",",
"ts",
"*",
"topo",
".",
"Server",
",",
"uuid",
"string",
",",
"taskState",
"workflowpb",
".",
"TaskState",
")",
"error",
"{",
"checkpoint",
",",
"err",
":=",
"checkpoint",
"(",
"ctx",
",",
"ts",
",",
"uuid",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"task",
":=",
"range",
"checkpoint",
".",
"Tasks",
"{",
"if",
"task",
".",
"State",
"!=",
"taskState",
"||",
"task",
".",
"Error",
"!=",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"task",
".",
"Id",
",",
"task",
".",
"State",
",",
"task",
".",
"Attributes",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | //verifyAllTasksState verifies that all tasks are in taskState. Only for tests purposes. | [
"verifyAllTasksState",
"verifies",
"that",
"all",
"tasks",
"are",
"in",
"taskState",
".",
"Only",
"for",
"tests",
"purposes",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/parallel_runner.go#L434-L446 | train |
vitessio/vitess | go/vt/workflow/parallel_runner.go | verifyTask | func verifyTask(ctx context.Context, ts *topo.Server, uuid, taskID string, taskState workflowpb.TaskState, taskError string) error {
checkpoint, err := checkpoint(ctx, ts, uuid)
if err != nil {
return err
}
task := checkpoint.Tasks[taskID]
if task.State != taskState || task.Error != taskError {
return fmt.Errorf("task status: %v, %v fails to match expected status: %v, %v", task.State, task.Error, taskState, taskError)
}
return nil
} | go | func verifyTask(ctx context.Context, ts *topo.Server, uuid, taskID string, taskState workflowpb.TaskState, taskError string) error {
checkpoint, err := checkpoint(ctx, ts, uuid)
if err != nil {
return err
}
task := checkpoint.Tasks[taskID]
if task.State != taskState || task.Error != taskError {
return fmt.Errorf("task status: %v, %v fails to match expected status: %v, %v", task.State, task.Error, taskState, taskError)
}
return nil
} | [
"func",
"verifyTask",
"(",
"ctx",
"context",
".",
"Context",
",",
"ts",
"*",
"topo",
".",
"Server",
",",
"uuid",
",",
"taskID",
"string",
",",
"taskState",
"workflowpb",
".",
"TaskState",
",",
"taskError",
"string",
")",
"error",
"{",
"checkpoint",
",",
"err",
":=",
"checkpoint",
"(",
"ctx",
",",
"ts",
",",
"uuid",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"task",
":=",
"checkpoint",
".",
"Tasks",
"[",
"taskID",
"]",
"\n\n",
"if",
"task",
".",
"State",
"!=",
"taskState",
"||",
"task",
".",
"Error",
"!=",
"taskError",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"task",
".",
"State",
",",
"task",
".",
"Error",
",",
"taskState",
",",
"taskError",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // verifyTask verifies that a task is in taskState. Only for test purposes. | [
"verifyTask",
"verifies",
"that",
"a",
"task",
"is",
"in",
"taskState",
".",
"Only",
"for",
"test",
"purposes",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/parallel_runner.go#L449-L460 | train |
vitessio/vitess | go/vt/workflow/parallel_runner.go | checkpoint | func checkpoint(ctx context.Context, ts *topo.Server, uuid string) (*workflowpb.WorkflowCheckpoint, error) {
wi, err := ts.GetWorkflow(ctx, uuid)
if err != nil {
return nil, fmt.Errorf("fail to get workflow for: %v", uuid)
}
checkpoint := &workflowpb.WorkflowCheckpoint{}
if err := proto.Unmarshal(wi.Data, checkpoint); err != nil {
return nil, fmt.Errorf("fails to get checkpoint for the workflow: %v", err)
}
return checkpoint, nil
} | go | func checkpoint(ctx context.Context, ts *topo.Server, uuid string) (*workflowpb.WorkflowCheckpoint, error) {
wi, err := ts.GetWorkflow(ctx, uuid)
if err != nil {
return nil, fmt.Errorf("fail to get workflow for: %v", uuid)
}
checkpoint := &workflowpb.WorkflowCheckpoint{}
if err := proto.Unmarshal(wi.Data, checkpoint); err != nil {
return nil, fmt.Errorf("fails to get checkpoint for the workflow: %v", err)
}
return checkpoint, nil
} | [
"func",
"checkpoint",
"(",
"ctx",
"context",
".",
"Context",
",",
"ts",
"*",
"topo",
".",
"Server",
",",
"uuid",
"string",
")",
"(",
"*",
"workflowpb",
".",
"WorkflowCheckpoint",
",",
"error",
")",
"{",
"wi",
",",
"err",
":=",
"ts",
".",
"GetWorkflow",
"(",
"ctx",
",",
"uuid",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"uuid",
")",
"\n",
"}",
"\n",
"checkpoint",
":=",
"&",
"workflowpb",
".",
"WorkflowCheckpoint",
"{",
"}",
"\n",
"if",
"err",
":=",
"proto",
".",
"Unmarshal",
"(",
"wi",
".",
"Data",
",",
"checkpoint",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"checkpoint",
",",
"nil",
"\n",
"}"
] | // checkpoint gets Worfklow from topo server. Only for test purposes. | [
"checkpoint",
"gets",
"Worfklow",
"from",
"topo",
"server",
".",
"Only",
"for",
"test",
"purposes",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/parallel_runner.go#L463-L473 | train |
vitessio/vitess | go/vt/topo/stats_conn.go | NewStatsConn | func NewStatsConn(cell string, conn Conn) *StatsConn {
return &StatsConn{
cell: cell,
conn: conn,
}
} | go | func NewStatsConn(cell string, conn Conn) *StatsConn {
return &StatsConn{
cell: cell,
conn: conn,
}
} | [
"func",
"NewStatsConn",
"(",
"cell",
"string",
",",
"conn",
"Conn",
")",
"*",
"StatsConn",
"{",
"return",
"&",
"StatsConn",
"{",
"cell",
":",
"cell",
",",
"conn",
":",
"conn",
",",
"}",
"\n",
"}"
] | // NewStatsConn returns a StatsConn | [
"NewStatsConn",
"returns",
"a",
"StatsConn"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/stats_conn.go#L45-L50 | train |
vitessio/vitess | go/vt/topo/stats_conn.go | ListDir | func (st *StatsConn) ListDir(ctx context.Context, dirPath string, full bool) ([]DirEntry, error) {
startTime := time.Now()
statsKey := []string{"ListDir", st.cell}
defer topoStatsConnTimings.Record(statsKey, startTime)
res, err := st.conn.ListDir(ctx, dirPath, full)
if err != nil {
topoStatsConnErrors.Add(statsKey, int64(1))
return res, err
}
return res, err
} | go | func (st *StatsConn) ListDir(ctx context.Context, dirPath string, full bool) ([]DirEntry, error) {
startTime := time.Now()
statsKey := []string{"ListDir", st.cell}
defer topoStatsConnTimings.Record(statsKey, startTime)
res, err := st.conn.ListDir(ctx, dirPath, full)
if err != nil {
topoStatsConnErrors.Add(statsKey, int64(1))
return res, err
}
return res, err
} | [
"func",
"(",
"st",
"*",
"StatsConn",
")",
"ListDir",
"(",
"ctx",
"context",
".",
"Context",
",",
"dirPath",
"string",
",",
"full",
"bool",
")",
"(",
"[",
"]",
"DirEntry",
",",
"error",
")",
"{",
"startTime",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"statsKey",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"st",
".",
"cell",
"}",
"\n",
"defer",
"topoStatsConnTimings",
".",
"Record",
"(",
"statsKey",
",",
"startTime",
")",
"\n",
"res",
",",
"err",
":=",
"st",
".",
"conn",
".",
"ListDir",
"(",
"ctx",
",",
"dirPath",
",",
"full",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"topoStatsConnErrors",
".",
"Add",
"(",
"statsKey",
",",
"int64",
"(",
"1",
")",
")",
"\n",
"return",
"res",
",",
"err",
"\n",
"}",
"\n",
"return",
"res",
",",
"err",
"\n",
"}"
] | // ListDir is part of the Conn interface | [
"ListDir",
"is",
"part",
"of",
"the",
"Conn",
"interface"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/stats_conn.go#L53-L63 | train |
vitessio/vitess | go/vt/topo/stats_conn.go | Create | func (st *StatsConn) Create(ctx context.Context, filePath string, contents []byte) (Version, error) {
startTime := time.Now()
statsKey := []string{"Create", st.cell}
defer topoStatsConnTimings.Record(statsKey, startTime)
res, err := st.conn.Create(ctx, filePath, contents)
if err != nil {
topoStatsConnErrors.Add(statsKey, int64(1))
return res, err
}
return res, err
} | go | func (st *StatsConn) Create(ctx context.Context, filePath string, contents []byte) (Version, error) {
startTime := time.Now()
statsKey := []string{"Create", st.cell}
defer topoStatsConnTimings.Record(statsKey, startTime)
res, err := st.conn.Create(ctx, filePath, contents)
if err != nil {
topoStatsConnErrors.Add(statsKey, int64(1))
return res, err
}
return res, err
} | [
"func",
"(",
"st",
"*",
"StatsConn",
")",
"Create",
"(",
"ctx",
"context",
".",
"Context",
",",
"filePath",
"string",
",",
"contents",
"[",
"]",
"byte",
")",
"(",
"Version",
",",
"error",
")",
"{",
"startTime",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"statsKey",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"st",
".",
"cell",
"}",
"\n",
"defer",
"topoStatsConnTimings",
".",
"Record",
"(",
"statsKey",
",",
"startTime",
")",
"\n",
"res",
",",
"err",
":=",
"st",
".",
"conn",
".",
"Create",
"(",
"ctx",
",",
"filePath",
",",
"contents",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"topoStatsConnErrors",
".",
"Add",
"(",
"statsKey",
",",
"int64",
"(",
"1",
")",
")",
"\n",
"return",
"res",
",",
"err",
"\n",
"}",
"\n",
"return",
"res",
",",
"err",
"\n",
"}"
] | // Create is part of the Conn interface | [
"Create",
"is",
"part",
"of",
"the",
"Conn",
"interface"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/stats_conn.go#L66-L76 | train |
vitessio/vitess | go/vt/topo/stats_conn.go | Lock | func (st *StatsConn) Lock(ctx context.Context, dirPath, contents string) (LockDescriptor, error) {
startTime := time.Now()
statsKey := []string{"Lock", st.cell}
defer topoStatsConnTimings.Record(statsKey, startTime)
res, err := st.conn.Lock(ctx, dirPath, contents)
if err != nil {
topoStatsConnErrors.Add(statsKey, int64(1))
return res, err
}
return res, err
} | go | func (st *StatsConn) Lock(ctx context.Context, dirPath, contents string) (LockDescriptor, error) {
startTime := time.Now()
statsKey := []string{"Lock", st.cell}
defer topoStatsConnTimings.Record(statsKey, startTime)
res, err := st.conn.Lock(ctx, dirPath, contents)
if err != nil {
topoStatsConnErrors.Add(statsKey, int64(1))
return res, err
}
return res, err
} | [
"func",
"(",
"st",
"*",
"StatsConn",
")",
"Lock",
"(",
"ctx",
"context",
".",
"Context",
",",
"dirPath",
",",
"contents",
"string",
")",
"(",
"LockDescriptor",
",",
"error",
")",
"{",
"startTime",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"statsKey",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"st",
".",
"cell",
"}",
"\n",
"defer",
"topoStatsConnTimings",
".",
"Record",
"(",
"statsKey",
",",
"startTime",
")",
"\n",
"res",
",",
"err",
":=",
"st",
".",
"conn",
".",
"Lock",
"(",
"ctx",
",",
"dirPath",
",",
"contents",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"topoStatsConnErrors",
".",
"Add",
"(",
"statsKey",
",",
"int64",
"(",
"1",
")",
")",
"\n",
"return",
"res",
",",
"err",
"\n",
"}",
"\n",
"return",
"res",
",",
"err",
"\n",
"}"
] | // Lock is part of the Conn interface | [
"Lock",
"is",
"part",
"of",
"the",
"Conn",
"interface"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/stats_conn.go#L118-L128 | train |
vitessio/vitess | go/vt/topo/stats_conn.go | Watch | func (st *StatsConn) Watch(ctx context.Context, filePath string) (current *WatchData, changes <-chan *WatchData, cancel CancelFunc) {
startTime := time.Now()
statsKey := []string{"Watch", st.cell}
defer topoStatsConnTimings.Record(statsKey, startTime)
return st.conn.Watch(ctx, filePath)
} | go | func (st *StatsConn) Watch(ctx context.Context, filePath string) (current *WatchData, changes <-chan *WatchData, cancel CancelFunc) {
startTime := time.Now()
statsKey := []string{"Watch", st.cell}
defer topoStatsConnTimings.Record(statsKey, startTime)
return st.conn.Watch(ctx, filePath)
} | [
"func",
"(",
"st",
"*",
"StatsConn",
")",
"Watch",
"(",
"ctx",
"context",
".",
"Context",
",",
"filePath",
"string",
")",
"(",
"current",
"*",
"WatchData",
",",
"changes",
"<-",
"chan",
"*",
"WatchData",
",",
"cancel",
"CancelFunc",
")",
"{",
"startTime",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"statsKey",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"st",
".",
"cell",
"}",
"\n",
"defer",
"topoStatsConnTimings",
".",
"Record",
"(",
"statsKey",
",",
"startTime",
")",
"\n",
"return",
"st",
".",
"conn",
".",
"Watch",
"(",
"ctx",
",",
"filePath",
")",
"\n",
"}"
] | // Watch is part of the Conn interface | [
"Watch",
"is",
"part",
"of",
"the",
"Conn",
"interface"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/stats_conn.go#L131-L136 | train |
vitessio/vitess | go/vt/topo/stats_conn.go | NewMasterParticipation | func (st *StatsConn) NewMasterParticipation(name, id string) (MasterParticipation, error) {
startTime := time.Now()
statsKey := []string{"NewMasterParticipation", st.cell}
defer topoStatsConnTimings.Record(statsKey, startTime)
res, err := st.conn.NewMasterParticipation(name, id)
if err != nil {
topoStatsConnErrors.Add(statsKey, int64(1))
return res, err
}
return res, err
} | go | func (st *StatsConn) NewMasterParticipation(name, id string) (MasterParticipation, error) {
startTime := time.Now()
statsKey := []string{"NewMasterParticipation", st.cell}
defer topoStatsConnTimings.Record(statsKey, startTime)
res, err := st.conn.NewMasterParticipation(name, id)
if err != nil {
topoStatsConnErrors.Add(statsKey, int64(1))
return res, err
}
return res, err
} | [
"func",
"(",
"st",
"*",
"StatsConn",
")",
"NewMasterParticipation",
"(",
"name",
",",
"id",
"string",
")",
"(",
"MasterParticipation",
",",
"error",
")",
"{",
"startTime",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"statsKey",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"st",
".",
"cell",
"}",
"\n",
"defer",
"topoStatsConnTimings",
".",
"Record",
"(",
"statsKey",
",",
"startTime",
")",
"\n",
"res",
",",
"err",
":=",
"st",
".",
"conn",
".",
"NewMasterParticipation",
"(",
"name",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"topoStatsConnErrors",
".",
"Add",
"(",
"statsKey",
",",
"int64",
"(",
"1",
")",
")",
"\n",
"return",
"res",
",",
"err",
"\n",
"}",
"\n",
"return",
"res",
",",
"err",
"\n",
"}"
] | // NewMasterParticipation is part of the Conn interface | [
"NewMasterParticipation",
"is",
"part",
"of",
"the",
"Conn",
"interface"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/stats_conn.go#L139-L149 | train |
vitessio/vitess | go/vt/topo/stats_conn.go | Close | func (st *StatsConn) Close() {
startTime := time.Now()
statsKey := []string{"Close", st.cell}
defer topoStatsConnTimings.Record(statsKey, startTime)
st.conn.Close()
} | go | func (st *StatsConn) Close() {
startTime := time.Now()
statsKey := []string{"Close", st.cell}
defer topoStatsConnTimings.Record(statsKey, startTime)
st.conn.Close()
} | [
"func",
"(",
"st",
"*",
"StatsConn",
")",
"Close",
"(",
")",
"{",
"startTime",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"statsKey",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"st",
".",
"cell",
"}",
"\n",
"defer",
"topoStatsConnTimings",
".",
"Record",
"(",
"statsKey",
",",
"startTime",
")",
"\n",
"st",
".",
"conn",
".",
"Close",
"(",
")",
"\n",
"}"
] | // Close is part of the Conn interface | [
"Close",
"is",
"part",
"of",
"the",
"Conn",
"interface"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/stats_conn.go#L152-L157 | train |
vitessio/vitess | go/vt/vttablet/tabletmanager/vreplication/table_plan_builder.go | buildReplicatorPlan | func buildReplicatorPlan(filter *binlogdatapb.Filter, tableKeys map[string][]string, copyState map[string]*sqltypes.Result) (*ReplicatorPlan, error) {
plan := &ReplicatorPlan{
VStreamFilter: &binlogdatapb.Filter{},
TargetTables: make(map[string]*TablePlan),
TablePlans: make(map[string]*TablePlan),
tableKeys: tableKeys,
}
nextTable:
for tableName := range tableKeys {
lastpk, ok := copyState[tableName]
if ok && lastpk == nil {
// Don't replicate uncopied tables.
continue
}
for _, rule := range filter.Rules {
switch {
case strings.HasPrefix(rule.Match, "/"):
expr := strings.Trim(rule.Match, "/")
result, err := regexp.MatchString(expr, tableName)
if err != nil {
return nil, err
}
if !result {
continue
}
sendRule := &binlogdatapb.Rule{
Match: tableName,
Filter: buildQuery(tableName, rule.Filter),
}
plan.VStreamFilter.Rules = append(plan.VStreamFilter.Rules, sendRule)
tablePlan := &TablePlan{
TargetName: tableName,
SendRule: sendRule,
}
plan.TargetTables[tableName] = tablePlan
plan.TablePlans[tableName] = tablePlan
continue nextTable
case rule.Match == tableName:
tablePlan, err := buildTablePlan(rule, tableKeys, lastpk)
if err != nil {
return nil, err
}
if _, ok := plan.TablePlans[tablePlan.SendRule.Match]; ok {
continue
}
plan.VStreamFilter.Rules = append(plan.VStreamFilter.Rules, tablePlan.SendRule)
plan.TargetTables[tableName] = tablePlan
plan.TablePlans[tablePlan.SendRule.Match] = tablePlan
continue nextTable
}
}
}
return plan, nil
} | go | func buildReplicatorPlan(filter *binlogdatapb.Filter, tableKeys map[string][]string, copyState map[string]*sqltypes.Result) (*ReplicatorPlan, error) {
plan := &ReplicatorPlan{
VStreamFilter: &binlogdatapb.Filter{},
TargetTables: make(map[string]*TablePlan),
TablePlans: make(map[string]*TablePlan),
tableKeys: tableKeys,
}
nextTable:
for tableName := range tableKeys {
lastpk, ok := copyState[tableName]
if ok && lastpk == nil {
// Don't replicate uncopied tables.
continue
}
for _, rule := range filter.Rules {
switch {
case strings.HasPrefix(rule.Match, "/"):
expr := strings.Trim(rule.Match, "/")
result, err := regexp.MatchString(expr, tableName)
if err != nil {
return nil, err
}
if !result {
continue
}
sendRule := &binlogdatapb.Rule{
Match: tableName,
Filter: buildQuery(tableName, rule.Filter),
}
plan.VStreamFilter.Rules = append(plan.VStreamFilter.Rules, sendRule)
tablePlan := &TablePlan{
TargetName: tableName,
SendRule: sendRule,
}
plan.TargetTables[tableName] = tablePlan
plan.TablePlans[tableName] = tablePlan
continue nextTable
case rule.Match == tableName:
tablePlan, err := buildTablePlan(rule, tableKeys, lastpk)
if err != nil {
return nil, err
}
if _, ok := plan.TablePlans[tablePlan.SendRule.Match]; ok {
continue
}
plan.VStreamFilter.Rules = append(plan.VStreamFilter.Rules, tablePlan.SendRule)
plan.TargetTables[tableName] = tablePlan
plan.TablePlans[tablePlan.SendRule.Match] = tablePlan
continue nextTable
}
}
}
return plan, nil
} | [
"func",
"buildReplicatorPlan",
"(",
"filter",
"*",
"binlogdatapb",
".",
"Filter",
",",
"tableKeys",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
",",
"copyState",
"map",
"[",
"string",
"]",
"*",
"sqltypes",
".",
"Result",
")",
"(",
"*",
"ReplicatorPlan",
",",
"error",
")",
"{",
"plan",
":=",
"&",
"ReplicatorPlan",
"{",
"VStreamFilter",
":",
"&",
"binlogdatapb",
".",
"Filter",
"{",
"}",
",",
"TargetTables",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"TablePlan",
")",
",",
"TablePlans",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"TablePlan",
")",
",",
"tableKeys",
":",
"tableKeys",
",",
"}",
"\n",
"nextTable",
":",
"for",
"tableName",
":=",
"range",
"tableKeys",
"{",
"lastpk",
",",
"ok",
":=",
"copyState",
"[",
"tableName",
"]",
"\n",
"if",
"ok",
"&&",
"lastpk",
"==",
"nil",
"{",
"// Don't replicate uncopied tables.",
"continue",
"\n",
"}",
"\n",
"for",
"_",
",",
"rule",
":=",
"range",
"filter",
".",
"Rules",
"{",
"switch",
"{",
"case",
"strings",
".",
"HasPrefix",
"(",
"rule",
".",
"Match",
",",
"\"",
"\"",
")",
":",
"expr",
":=",
"strings",
".",
"Trim",
"(",
"rule",
".",
"Match",
",",
"\"",
"\"",
")",
"\n",
"result",
",",
"err",
":=",
"regexp",
".",
"MatchString",
"(",
"expr",
",",
"tableName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"!",
"result",
"{",
"continue",
"\n",
"}",
"\n",
"sendRule",
":=",
"&",
"binlogdatapb",
".",
"Rule",
"{",
"Match",
":",
"tableName",
",",
"Filter",
":",
"buildQuery",
"(",
"tableName",
",",
"rule",
".",
"Filter",
")",
",",
"}",
"\n",
"plan",
".",
"VStreamFilter",
".",
"Rules",
"=",
"append",
"(",
"plan",
".",
"VStreamFilter",
".",
"Rules",
",",
"sendRule",
")",
"\n",
"tablePlan",
":=",
"&",
"TablePlan",
"{",
"TargetName",
":",
"tableName",
",",
"SendRule",
":",
"sendRule",
",",
"}",
"\n",
"plan",
".",
"TargetTables",
"[",
"tableName",
"]",
"=",
"tablePlan",
"\n",
"plan",
".",
"TablePlans",
"[",
"tableName",
"]",
"=",
"tablePlan",
"\n",
"continue",
"nextTable",
"\n",
"case",
"rule",
".",
"Match",
"==",
"tableName",
":",
"tablePlan",
",",
"err",
":=",
"buildTablePlan",
"(",
"rule",
",",
"tableKeys",
",",
"lastpk",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"plan",
".",
"TablePlans",
"[",
"tablePlan",
".",
"SendRule",
".",
"Match",
"]",
";",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"plan",
".",
"VStreamFilter",
".",
"Rules",
"=",
"append",
"(",
"plan",
".",
"VStreamFilter",
".",
"Rules",
",",
"tablePlan",
".",
"SendRule",
")",
"\n",
"plan",
".",
"TargetTables",
"[",
"tableName",
"]",
"=",
"tablePlan",
"\n",
"plan",
".",
"TablePlans",
"[",
"tablePlan",
".",
"SendRule",
".",
"Match",
"]",
"=",
"tablePlan",
"\n",
"continue",
"nextTable",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"plan",
",",
"nil",
"\n",
"}"
] | // buildReplicatorPlan builds a ReplicatorPlan for the tables that match the filter.
// The filter is matched against the target schema. For every table matched,
// a table-specific rule is built to be sent to the source. We don't send the
// original rule to the source because it may not match the same tables as the
// target.
// The TablePlan built is a partial plan. The full plan for a table is built
// when we receive field information from events or rows sent by the source.
// buildExecutionPlan is the function that builds the full plan. | [
"buildReplicatorPlan",
"builds",
"a",
"ReplicatorPlan",
"for",
"the",
"tables",
"that",
"match",
"the",
"filter",
".",
"The",
"filter",
"is",
"matched",
"against",
"the",
"target",
"schema",
".",
"For",
"every",
"table",
"matched",
"a",
"table",
"-",
"specific",
"rule",
"is",
"built",
"to",
"be",
"sent",
"to",
"the",
"source",
".",
"We",
"don",
"t",
"send",
"the",
"original",
"rule",
"to",
"the",
"source",
"because",
"it",
"may",
"not",
"match",
"the",
"same",
"tables",
"as",
"the",
"target",
".",
"The",
"TablePlan",
"built",
"is",
"a",
"partial",
"plan",
".",
"The",
"full",
"plan",
"for",
"a",
"table",
"is",
"built",
"when",
"we",
"receive",
"field",
"information",
"from",
"events",
"or",
"rows",
"sent",
"by",
"the",
"source",
".",
"buildExecutionPlan",
"is",
"the",
"function",
"that",
"builds",
"the",
"full",
"plan",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletmanager/vreplication/table_plan_builder.go#L84-L137 | train |
vitessio/vitess | go/vt/throttler/grpcthrottlerserver/grpcthrottlerserver.go | MaxRates | func (s *Server) MaxRates(_ context.Context, request *throttlerdatapb.MaxRatesRequest) (_ *throttlerdatapb.MaxRatesResponse, err error) {
defer servenv.HandlePanic("throttler", &err)
rates := s.manager.MaxRates()
return &throttlerdatapb.MaxRatesResponse{
Rates: rates,
}, nil
} | go | func (s *Server) MaxRates(_ context.Context, request *throttlerdatapb.MaxRatesRequest) (_ *throttlerdatapb.MaxRatesResponse, err error) {
defer servenv.HandlePanic("throttler", &err)
rates := s.manager.MaxRates()
return &throttlerdatapb.MaxRatesResponse{
Rates: rates,
}, nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"MaxRates",
"(",
"_",
"context",
".",
"Context",
",",
"request",
"*",
"throttlerdatapb",
".",
"MaxRatesRequest",
")",
"(",
"_",
"*",
"throttlerdatapb",
".",
"MaxRatesResponse",
",",
"err",
"error",
")",
"{",
"defer",
"servenv",
".",
"HandlePanic",
"(",
"\"",
"\"",
",",
"&",
"err",
")",
"\n\n",
"rates",
":=",
"s",
".",
"manager",
".",
"MaxRates",
"(",
")",
"\n",
"return",
"&",
"throttlerdatapb",
".",
"MaxRatesResponse",
"{",
"Rates",
":",
"rates",
",",
"}",
",",
"nil",
"\n",
"}"
] | // MaxRates implements the gRPC server interface. It returns the current max
// rate for each throttler of the process. | [
"MaxRates",
"implements",
"the",
"gRPC",
"server",
"interface",
".",
"It",
"returns",
"the",
"current",
"max",
"rate",
"for",
"each",
"throttler",
"of",
"the",
"process",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/grpcthrottlerserver/grpcthrottlerserver.go#L44-L51 | train |
vitessio/vitess | go/vt/throttler/grpcthrottlerserver/grpcthrottlerserver.go | SetMaxRate | func (s *Server) SetMaxRate(_ context.Context, request *throttlerdatapb.SetMaxRateRequest) (_ *throttlerdatapb.SetMaxRateResponse, err error) {
defer servenv.HandlePanic("throttler", &err)
names := s.manager.SetMaxRate(request.Rate)
return &throttlerdatapb.SetMaxRateResponse{
Names: names,
}, nil
} | go | func (s *Server) SetMaxRate(_ context.Context, request *throttlerdatapb.SetMaxRateRequest) (_ *throttlerdatapb.SetMaxRateResponse, err error) {
defer servenv.HandlePanic("throttler", &err)
names := s.manager.SetMaxRate(request.Rate)
return &throttlerdatapb.SetMaxRateResponse{
Names: names,
}, nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"SetMaxRate",
"(",
"_",
"context",
".",
"Context",
",",
"request",
"*",
"throttlerdatapb",
".",
"SetMaxRateRequest",
")",
"(",
"_",
"*",
"throttlerdatapb",
".",
"SetMaxRateResponse",
",",
"err",
"error",
")",
"{",
"defer",
"servenv",
".",
"HandlePanic",
"(",
"\"",
"\"",
",",
"&",
"err",
")",
"\n\n",
"names",
":=",
"s",
".",
"manager",
".",
"SetMaxRate",
"(",
"request",
".",
"Rate",
")",
"\n",
"return",
"&",
"throttlerdatapb",
".",
"SetMaxRateResponse",
"{",
"Names",
":",
"names",
",",
"}",
",",
"nil",
"\n",
"}"
] | // SetMaxRate implements the gRPC server interface. It sets the rate on all
// throttlers controlled by the manager. | [
"SetMaxRate",
"implements",
"the",
"gRPC",
"server",
"interface",
".",
"It",
"sets",
"the",
"rate",
"on",
"all",
"throttlers",
"controlled",
"by",
"the",
"manager",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/grpcthrottlerserver/grpcthrottlerserver.go#L55-L62 | train |
vitessio/vitess | go/vt/throttler/grpcthrottlerserver/grpcthrottlerserver.go | GetConfiguration | func (s *Server) GetConfiguration(_ context.Context, request *throttlerdatapb.GetConfigurationRequest) (_ *throttlerdatapb.GetConfigurationResponse, err error) {
defer servenv.HandlePanic("throttler", &err)
configurations, err := s.manager.GetConfiguration(request.ThrottlerName)
if err != nil {
return nil, err
}
return &throttlerdatapb.GetConfigurationResponse{
Configurations: configurations,
}, nil
} | go | func (s *Server) GetConfiguration(_ context.Context, request *throttlerdatapb.GetConfigurationRequest) (_ *throttlerdatapb.GetConfigurationResponse, err error) {
defer servenv.HandlePanic("throttler", &err)
configurations, err := s.manager.GetConfiguration(request.ThrottlerName)
if err != nil {
return nil, err
}
return &throttlerdatapb.GetConfigurationResponse{
Configurations: configurations,
}, nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"GetConfiguration",
"(",
"_",
"context",
".",
"Context",
",",
"request",
"*",
"throttlerdatapb",
".",
"GetConfigurationRequest",
")",
"(",
"_",
"*",
"throttlerdatapb",
".",
"GetConfigurationResponse",
",",
"err",
"error",
")",
"{",
"defer",
"servenv",
".",
"HandlePanic",
"(",
"\"",
"\"",
",",
"&",
"err",
")",
"\n\n",
"configurations",
",",
"err",
":=",
"s",
".",
"manager",
".",
"GetConfiguration",
"(",
"request",
".",
"ThrottlerName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"throttlerdatapb",
".",
"GetConfigurationResponse",
"{",
"Configurations",
":",
"configurations",
",",
"}",
",",
"nil",
"\n",
"}"
] | // GetConfiguration implements the gRPC server interface. | [
"GetConfiguration",
"implements",
"the",
"gRPC",
"server",
"interface",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/grpcthrottlerserver/grpcthrottlerserver.go#L65-L75 | train |
vitessio/vitess | go/vt/throttler/grpcthrottlerserver/grpcthrottlerserver.go | UpdateConfiguration | func (s *Server) UpdateConfiguration(_ context.Context, request *throttlerdatapb.UpdateConfigurationRequest) (_ *throttlerdatapb.UpdateConfigurationResponse, err error) {
defer servenv.HandlePanic("throttler", &err)
names, err := s.manager.UpdateConfiguration(request.ThrottlerName, request.Configuration, request.CopyZeroValues)
if err != nil {
return nil, err
}
return &throttlerdatapb.UpdateConfigurationResponse{
Names: names,
}, nil
} | go | func (s *Server) UpdateConfiguration(_ context.Context, request *throttlerdatapb.UpdateConfigurationRequest) (_ *throttlerdatapb.UpdateConfigurationResponse, err error) {
defer servenv.HandlePanic("throttler", &err)
names, err := s.manager.UpdateConfiguration(request.ThrottlerName, request.Configuration, request.CopyZeroValues)
if err != nil {
return nil, err
}
return &throttlerdatapb.UpdateConfigurationResponse{
Names: names,
}, nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"UpdateConfiguration",
"(",
"_",
"context",
".",
"Context",
",",
"request",
"*",
"throttlerdatapb",
".",
"UpdateConfigurationRequest",
")",
"(",
"_",
"*",
"throttlerdatapb",
".",
"UpdateConfigurationResponse",
",",
"err",
"error",
")",
"{",
"defer",
"servenv",
".",
"HandlePanic",
"(",
"\"",
"\"",
",",
"&",
"err",
")",
"\n\n",
"names",
",",
"err",
":=",
"s",
".",
"manager",
".",
"UpdateConfiguration",
"(",
"request",
".",
"ThrottlerName",
",",
"request",
".",
"Configuration",
",",
"request",
".",
"CopyZeroValues",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"throttlerdatapb",
".",
"UpdateConfigurationResponse",
"{",
"Names",
":",
"names",
",",
"}",
",",
"nil",
"\n",
"}"
] | // UpdateConfiguration implements the gRPC server interface. | [
"UpdateConfiguration",
"implements",
"the",
"gRPC",
"server",
"interface",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/grpcthrottlerserver/grpcthrottlerserver.go#L78-L88 | train |
vitessio/vitess | go/vt/throttler/grpcthrottlerserver/grpcthrottlerserver.go | ResetConfiguration | func (s *Server) ResetConfiguration(_ context.Context, request *throttlerdatapb.ResetConfigurationRequest) (_ *throttlerdatapb.ResetConfigurationResponse, err error) {
defer servenv.HandlePanic("throttler", &err)
names, err := s.manager.ResetConfiguration(request.ThrottlerName)
if err != nil {
return nil, err
}
return &throttlerdatapb.ResetConfigurationResponse{
Names: names,
}, nil
} | go | func (s *Server) ResetConfiguration(_ context.Context, request *throttlerdatapb.ResetConfigurationRequest) (_ *throttlerdatapb.ResetConfigurationResponse, err error) {
defer servenv.HandlePanic("throttler", &err)
names, err := s.manager.ResetConfiguration(request.ThrottlerName)
if err != nil {
return nil, err
}
return &throttlerdatapb.ResetConfigurationResponse{
Names: names,
}, nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"ResetConfiguration",
"(",
"_",
"context",
".",
"Context",
",",
"request",
"*",
"throttlerdatapb",
".",
"ResetConfigurationRequest",
")",
"(",
"_",
"*",
"throttlerdatapb",
".",
"ResetConfigurationResponse",
",",
"err",
"error",
")",
"{",
"defer",
"servenv",
".",
"HandlePanic",
"(",
"\"",
"\"",
",",
"&",
"err",
")",
"\n\n",
"names",
",",
"err",
":=",
"s",
".",
"manager",
".",
"ResetConfiguration",
"(",
"request",
".",
"ThrottlerName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"throttlerdatapb",
".",
"ResetConfigurationResponse",
"{",
"Names",
":",
"names",
",",
"}",
",",
"nil",
"\n",
"}"
] | // ResetConfiguration implements the gRPC server interface. | [
"ResetConfiguration",
"implements",
"the",
"gRPC",
"server",
"interface",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/grpcthrottlerserver/grpcthrottlerserver.go#L91-L101 | train |
vitessio/vitess | go/vt/throttler/grpcthrottlerserver/grpcthrottlerserver.go | RegisterServer | func RegisterServer(s *grpc.Server, m throttler.Manager) {
throttlerservicepb.RegisterThrottlerServer(s, NewServer(m))
} | go | func RegisterServer(s *grpc.Server, m throttler.Manager) {
throttlerservicepb.RegisterThrottlerServer(s, NewServer(m))
} | [
"func",
"RegisterServer",
"(",
"s",
"*",
"grpc",
".",
"Server",
",",
"m",
"throttler",
".",
"Manager",
")",
"{",
"throttlerservicepb",
".",
"RegisterThrottlerServer",
"(",
"s",
",",
"NewServer",
"(",
"m",
")",
")",
"\n",
"}"
] | // RegisterServer registers a new throttler server instance with the gRPC server. | [
"RegisterServer",
"registers",
"a",
"new",
"throttler",
"server",
"instance",
"with",
"the",
"gRPC",
"server",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/throttler/grpcthrottlerserver/grpcthrottlerserver.go#L104-L106 | train |
vitessio/vitess | go/vt/topo/etcd2topo/error.go | convertError | func convertError(err error, nodePath string) error {
if err == nil {
return nil
}
if typeErr, ok := err.(rpctypes.EtcdError); ok {
switch typeErr.Code() {
case codes.NotFound:
return topo.NewError(topo.NoNode, nodePath)
case codes.Unavailable, codes.DeadlineExceeded:
// The etcd2 client library may return this error:
// grpc.Errorf(codes.Unavailable,
// "etcdserver: request timed out") which seems to be
// misclassified, it should be using
// codes.DeadlineExceeded. All timeouts errors
// seem to be using the codes.Unavailable
// category. So changing all of them to ErrTimeout.
// The other reasons for codes.Unavailable are when
// etcd master election is failing, so timeout
// also sounds reasonable there.
return topo.NewError(topo.Timeout, nodePath)
}
return err
}
if s, ok := status.FromError(err); ok {
// This is a gRPC error.
switch s.Code() {
case codes.NotFound:
return topo.NewError(topo.NoNode, nodePath)
case codes.Canceled:
return topo.NewError(topo.Interrupted, nodePath)
case codes.DeadlineExceeded:
return topo.NewError(topo.Timeout, nodePath)
default:
return err
}
}
switch err {
case context.Canceled:
return topo.NewError(topo.Interrupted, nodePath)
case context.DeadlineExceeded:
return topo.NewError(topo.Timeout, nodePath)
default:
return err
}
} | go | func convertError(err error, nodePath string) error {
if err == nil {
return nil
}
if typeErr, ok := err.(rpctypes.EtcdError); ok {
switch typeErr.Code() {
case codes.NotFound:
return topo.NewError(topo.NoNode, nodePath)
case codes.Unavailable, codes.DeadlineExceeded:
// The etcd2 client library may return this error:
// grpc.Errorf(codes.Unavailable,
// "etcdserver: request timed out") which seems to be
// misclassified, it should be using
// codes.DeadlineExceeded. All timeouts errors
// seem to be using the codes.Unavailable
// category. So changing all of them to ErrTimeout.
// The other reasons for codes.Unavailable are when
// etcd master election is failing, so timeout
// also sounds reasonable there.
return topo.NewError(topo.Timeout, nodePath)
}
return err
}
if s, ok := status.FromError(err); ok {
// This is a gRPC error.
switch s.Code() {
case codes.NotFound:
return topo.NewError(topo.NoNode, nodePath)
case codes.Canceled:
return topo.NewError(topo.Interrupted, nodePath)
case codes.DeadlineExceeded:
return topo.NewError(topo.Timeout, nodePath)
default:
return err
}
}
switch err {
case context.Canceled:
return topo.NewError(topo.Interrupted, nodePath)
case context.DeadlineExceeded:
return topo.NewError(topo.Timeout, nodePath)
default:
return err
}
} | [
"func",
"convertError",
"(",
"err",
"error",
",",
"nodePath",
"string",
")",
"error",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"typeErr",
",",
"ok",
":=",
"err",
".",
"(",
"rpctypes",
".",
"EtcdError",
")",
";",
"ok",
"{",
"switch",
"typeErr",
".",
"Code",
"(",
")",
"{",
"case",
"codes",
".",
"NotFound",
":",
"return",
"topo",
".",
"NewError",
"(",
"topo",
".",
"NoNode",
",",
"nodePath",
")",
"\n",
"case",
"codes",
".",
"Unavailable",
",",
"codes",
".",
"DeadlineExceeded",
":",
"// The etcd2 client library may return this error:",
"// grpc.Errorf(codes.Unavailable,",
"// \"etcdserver: request timed out\") which seems to be",
"// misclassified, it should be using",
"// codes.DeadlineExceeded. All timeouts errors",
"// seem to be using the codes.Unavailable",
"// category. So changing all of them to ErrTimeout.",
"// The other reasons for codes.Unavailable are when",
"// etcd master election is failing, so timeout",
"// also sounds reasonable there.",
"return",
"topo",
".",
"NewError",
"(",
"topo",
".",
"Timeout",
",",
"nodePath",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"s",
",",
"ok",
":=",
"status",
".",
"FromError",
"(",
"err",
")",
";",
"ok",
"{",
"// This is a gRPC error.",
"switch",
"s",
".",
"Code",
"(",
")",
"{",
"case",
"codes",
".",
"NotFound",
":",
"return",
"topo",
".",
"NewError",
"(",
"topo",
".",
"NoNode",
",",
"nodePath",
")",
"\n",
"case",
"codes",
".",
"Canceled",
":",
"return",
"topo",
".",
"NewError",
"(",
"topo",
".",
"Interrupted",
",",
"nodePath",
")",
"\n",
"case",
"codes",
".",
"DeadlineExceeded",
":",
"return",
"topo",
".",
"NewError",
"(",
"topo",
".",
"Timeout",
",",
"nodePath",
")",
"\n",
"default",
":",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"switch",
"err",
"{",
"case",
"context",
".",
"Canceled",
":",
"return",
"topo",
".",
"NewError",
"(",
"topo",
".",
"Interrupted",
",",
"nodePath",
")",
"\n",
"case",
"context",
".",
"DeadlineExceeded",
":",
"return",
"topo",
".",
"NewError",
"(",
"topo",
".",
"Timeout",
",",
"nodePath",
")",
"\n",
"default",
":",
"return",
"err",
"\n",
"}",
"\n",
"}"
] | // convertError converts an etcd error into a topo error. All errors
// are either application-level errors, or context errors. | [
"convertError",
"converts",
"an",
"etcd",
"error",
"into",
"a",
"topo",
"error",
".",
"All",
"errors",
"are",
"either",
"application",
"-",
"level",
"errors",
"or",
"context",
"errors",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/etcd2topo/error.go#L42-L89 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/tabletenv/config.go | Init | func Init() {
switch *streamlog.QueryLogFormat {
case streamlog.QueryLogFormatText:
case streamlog.QueryLogFormatJSON:
default:
log.Exitf("Invalid querylog-format value %v: must be either text or json", *streamlog.QueryLogFormat)
}
if *queryLogHandler != "" {
StatsLogger.ServeLogs(*queryLogHandler, streamlog.GetFormatter(StatsLogger))
}
if *txLogHandler != "" {
TxLogger.ServeLogs(*txLogHandler, streamlog.GetFormatter(TxLogger))
}
} | go | func Init() {
switch *streamlog.QueryLogFormat {
case streamlog.QueryLogFormatText:
case streamlog.QueryLogFormatJSON:
default:
log.Exitf("Invalid querylog-format value %v: must be either text or json", *streamlog.QueryLogFormat)
}
if *queryLogHandler != "" {
StatsLogger.ServeLogs(*queryLogHandler, streamlog.GetFormatter(StatsLogger))
}
if *txLogHandler != "" {
TxLogger.ServeLogs(*txLogHandler, streamlog.GetFormatter(TxLogger))
}
} | [
"func",
"Init",
"(",
")",
"{",
"switch",
"*",
"streamlog",
".",
"QueryLogFormat",
"{",
"case",
"streamlog",
".",
"QueryLogFormatText",
":",
"case",
"streamlog",
".",
"QueryLogFormatJSON",
":",
"default",
":",
"log",
".",
"Exitf",
"(",
"\"",
"\"",
",",
"*",
"streamlog",
".",
"QueryLogFormat",
")",
"\n",
"}",
"\n\n",
"if",
"*",
"queryLogHandler",
"!=",
"\"",
"\"",
"{",
"StatsLogger",
".",
"ServeLogs",
"(",
"*",
"queryLogHandler",
",",
"streamlog",
".",
"GetFormatter",
"(",
"StatsLogger",
")",
")",
"\n",
"}",
"\n\n",
"if",
"*",
"txLogHandler",
"!=",
"\"",
"\"",
"{",
"TxLogger",
".",
"ServeLogs",
"(",
"*",
"txLogHandler",
",",
"streamlog",
".",
"GetFormatter",
"(",
"TxLogger",
")",
")",
"\n",
"}",
"\n",
"}"
] | // Init must be called after flag.Parse, and before doing any other operations. | [
"Init",
"must",
"be",
"called",
"after",
"flag",
".",
"Parse",
"and",
"before",
"doing",
"any",
"other",
"operations",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletenv/config.go#L107-L122 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/tabletenv/config.go | verifyTransactionLimitConfig | func (c *TabletConfig) verifyTransactionLimitConfig() error {
actual, dryRun := c.EnableTransactionLimit, c.EnableTransactionLimitDryRun
if actual && dryRun {
return errors.New("only one of two flags allowed: -enable_transaction_limit or -enable_transaction_limit_dry_run")
}
// Skip other checks if this is not enabled
if !actual && !dryRun {
return nil
}
var (
byUser = c.TransactionLimitByUsername
byPrincipal = c.TransactionLimitByPrincipal
byComp = c.TransactionLimitByComponent
bySubcomp = c.TransactionLimitBySubcomponent
)
if byAny := byUser || byPrincipal || byComp || bySubcomp; !byAny {
return errors.New("no user discriminating fields selected for transaction limiter, everyone would share single chunk of transaction pool. Override with at least one of -transaction_limit_by flags set to true")
}
if v := c.TransactionLimitPerUser; v <= 0 || v >= 1 {
return fmt.Errorf("-transaction_limit_per_user should be a fraction within range (0, 1) (specified value: %v)", v)
}
if limit := int(c.TransactionLimitPerUser * float64(c.TransactionCap)); limit == 0 {
return fmt.Errorf("effective transaction limit per user is 0 due to rounding, increase -transaction_limit_per_user")
}
return nil
} | go | func (c *TabletConfig) verifyTransactionLimitConfig() error {
actual, dryRun := c.EnableTransactionLimit, c.EnableTransactionLimitDryRun
if actual && dryRun {
return errors.New("only one of two flags allowed: -enable_transaction_limit or -enable_transaction_limit_dry_run")
}
// Skip other checks if this is not enabled
if !actual && !dryRun {
return nil
}
var (
byUser = c.TransactionLimitByUsername
byPrincipal = c.TransactionLimitByPrincipal
byComp = c.TransactionLimitByComponent
bySubcomp = c.TransactionLimitBySubcomponent
)
if byAny := byUser || byPrincipal || byComp || bySubcomp; !byAny {
return errors.New("no user discriminating fields selected for transaction limiter, everyone would share single chunk of transaction pool. Override with at least one of -transaction_limit_by flags set to true")
}
if v := c.TransactionLimitPerUser; v <= 0 || v >= 1 {
return fmt.Errorf("-transaction_limit_per_user should be a fraction within range (0, 1) (specified value: %v)", v)
}
if limit := int(c.TransactionLimitPerUser * float64(c.TransactionCap)); limit == 0 {
return fmt.Errorf("effective transaction limit per user is 0 due to rounding, increase -transaction_limit_per_user")
}
return nil
} | [
"func",
"(",
"c",
"*",
"TabletConfig",
")",
"verifyTransactionLimitConfig",
"(",
")",
"error",
"{",
"actual",
",",
"dryRun",
":=",
"c",
".",
"EnableTransactionLimit",
",",
"c",
".",
"EnableTransactionLimitDryRun",
"\n",
"if",
"actual",
"&&",
"dryRun",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Skip other checks if this is not enabled",
"if",
"!",
"actual",
"&&",
"!",
"dryRun",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"var",
"(",
"byUser",
"=",
"c",
".",
"TransactionLimitByUsername",
"\n",
"byPrincipal",
"=",
"c",
".",
"TransactionLimitByPrincipal",
"\n",
"byComp",
"=",
"c",
".",
"TransactionLimitByComponent",
"\n",
"bySubcomp",
"=",
"c",
".",
"TransactionLimitBySubcomponent",
"\n",
")",
"\n",
"if",
"byAny",
":=",
"byUser",
"||",
"byPrincipal",
"||",
"byComp",
"||",
"bySubcomp",
";",
"!",
"byAny",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"v",
":=",
"c",
".",
"TransactionLimitPerUser",
";",
"v",
"<=",
"0",
"||",
"v",
">=",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"v",
")",
"\n",
"}",
"\n",
"if",
"limit",
":=",
"int",
"(",
"c",
".",
"TransactionLimitPerUser",
"*",
"float64",
"(",
"c",
".",
"TransactionCap",
")",
")",
";",
"limit",
"==",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // verifyTransactionLimitConfig checks TransactionLimitConfig for sanity | [
"verifyTransactionLimitConfig",
"checks",
"TransactionLimitConfig",
"for",
"sanity"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletenv/config.go#L283-L310 | train |
vitessio/vitess | go/vt/vttablet/tabletserver/tabletenv/config.go | VerifyConfig | func VerifyConfig() error {
if err := Config.verifyTransactionLimitConfig(); err != nil {
return err
}
if actual, dryRun := Config.EnableHotRowProtection, Config.EnableHotRowProtectionDryRun; actual && dryRun {
return errors.New("only one of two flags allowed: -enable_hot_row_protection or -enable_hot_row_protection_dry_run")
}
if v := Config.HotRowProtectionMaxQueueSize; v <= 0 {
return fmt.Errorf("-hot_row_protection_max_queue_size must be > 0 (specified value: %v)", v)
}
if v := Config.HotRowProtectionMaxGlobalQueueSize; v <= 0 {
return fmt.Errorf("-hot_row_protection_max_global_queue_size must be > 0 (specified value: %v)", v)
}
if globalSize, size := Config.HotRowProtectionMaxGlobalQueueSize, Config.HotRowProtectionMaxQueueSize; globalSize < size {
return fmt.Errorf("global queue size must be >= per row (range) queue size: -hot_row_protection_max_global_queue_size < hot_row_protection_max_queue_size (%v < %v)", globalSize, size)
}
if v := Config.HotRowProtectionConcurrentTransactions; v <= 0 {
return fmt.Errorf("-hot_row_protection_concurrent_transactions must be > 0 (specified value: %v)", v)
}
return nil
} | go | func VerifyConfig() error {
if err := Config.verifyTransactionLimitConfig(); err != nil {
return err
}
if actual, dryRun := Config.EnableHotRowProtection, Config.EnableHotRowProtectionDryRun; actual && dryRun {
return errors.New("only one of two flags allowed: -enable_hot_row_protection or -enable_hot_row_protection_dry_run")
}
if v := Config.HotRowProtectionMaxQueueSize; v <= 0 {
return fmt.Errorf("-hot_row_protection_max_queue_size must be > 0 (specified value: %v)", v)
}
if v := Config.HotRowProtectionMaxGlobalQueueSize; v <= 0 {
return fmt.Errorf("-hot_row_protection_max_global_queue_size must be > 0 (specified value: %v)", v)
}
if globalSize, size := Config.HotRowProtectionMaxGlobalQueueSize, Config.HotRowProtectionMaxQueueSize; globalSize < size {
return fmt.Errorf("global queue size must be >= per row (range) queue size: -hot_row_protection_max_global_queue_size < hot_row_protection_max_queue_size (%v < %v)", globalSize, size)
}
if v := Config.HotRowProtectionConcurrentTransactions; v <= 0 {
return fmt.Errorf("-hot_row_protection_concurrent_transactions must be > 0 (specified value: %v)", v)
}
return nil
} | [
"func",
"VerifyConfig",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"Config",
".",
"verifyTransactionLimitConfig",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"actual",
",",
"dryRun",
":=",
"Config",
".",
"EnableHotRowProtection",
",",
"Config",
".",
"EnableHotRowProtectionDryRun",
";",
"actual",
"&&",
"dryRun",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"v",
":=",
"Config",
".",
"HotRowProtectionMaxQueueSize",
";",
"v",
"<=",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"v",
")",
"\n",
"}",
"\n",
"if",
"v",
":=",
"Config",
".",
"HotRowProtectionMaxGlobalQueueSize",
";",
"v",
"<=",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"v",
")",
"\n",
"}",
"\n",
"if",
"globalSize",
",",
"size",
":=",
"Config",
".",
"HotRowProtectionMaxGlobalQueueSize",
",",
"Config",
".",
"HotRowProtectionMaxQueueSize",
";",
"globalSize",
"<",
"size",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"globalSize",
",",
"size",
")",
"\n",
"}",
"\n",
"if",
"v",
":=",
"Config",
".",
"HotRowProtectionConcurrentTransactions",
";",
"v",
"<=",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"v",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // VerifyConfig checks "Config" for contradicting flags. | [
"VerifyConfig",
"checks",
"Config",
"for",
"contradicting",
"flags",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletserver/tabletenv/config.go#L317-L337 | train |
vitessio/vitess | go/mysql/mysql56_gtid_set.go | SIDs | func (set Mysql56GTIDSet) SIDs() []SID {
sids := make([]SID, 0, len(set))
for sid := range set {
sids = append(sids, sid)
}
sort.Sort(sidList(sids))
return sids
} | go | func (set Mysql56GTIDSet) SIDs() []SID {
sids := make([]SID, 0, len(set))
for sid := range set {
sids = append(sids, sid)
}
sort.Sort(sidList(sids))
return sids
} | [
"func",
"(",
"set",
"Mysql56GTIDSet",
")",
"SIDs",
"(",
")",
"[",
"]",
"SID",
"{",
"sids",
":=",
"make",
"(",
"[",
"]",
"SID",
",",
"0",
",",
"len",
"(",
"set",
")",
")",
"\n",
"for",
"sid",
":=",
"range",
"set",
"{",
"sids",
"=",
"append",
"(",
"sids",
",",
"sid",
")",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"sidList",
"(",
"sids",
")",
")",
"\n",
"return",
"sids",
"\n",
"}"
] | // SIDs returns a sorted list of SIDs in the set. | [
"SIDs",
"returns",
"a",
"sorted",
"list",
"of",
"SIDs",
"in",
"the",
"set",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/mysql56_gtid_set.go#L130-L137 | train |
vitessio/vitess | go/mysql/mysql56_gtid_set.go | String | func (set Mysql56GTIDSet) String() string {
buf := &bytes.Buffer{}
for i, sid := range set.SIDs() {
if i != 0 {
buf.WriteByte(',')
}
buf.WriteString(sid.String())
for _, interval := range set[sid] {
buf.WriteByte(':')
buf.WriteString(strconv.FormatInt(interval.start, 10))
if interval.end != interval.start {
buf.WriteByte('-')
buf.WriteString(strconv.FormatInt(interval.end, 10))
}
}
}
return buf.String()
} | go | func (set Mysql56GTIDSet) String() string {
buf := &bytes.Buffer{}
for i, sid := range set.SIDs() {
if i != 0 {
buf.WriteByte(',')
}
buf.WriteString(sid.String())
for _, interval := range set[sid] {
buf.WriteByte(':')
buf.WriteString(strconv.FormatInt(interval.start, 10))
if interval.end != interval.start {
buf.WriteByte('-')
buf.WriteString(strconv.FormatInt(interval.end, 10))
}
}
}
return buf.String()
} | [
"func",
"(",
"set",
"Mysql56GTIDSet",
")",
"String",
"(",
")",
"string",
"{",
"buf",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n\n",
"for",
"i",
",",
"sid",
":=",
"range",
"set",
".",
"SIDs",
"(",
")",
"{",
"if",
"i",
"!=",
"0",
"{",
"buf",
".",
"WriteByte",
"(",
"','",
")",
"\n",
"}",
"\n",
"buf",
".",
"WriteString",
"(",
"sid",
".",
"String",
"(",
")",
")",
"\n\n",
"for",
"_",
",",
"interval",
":=",
"range",
"set",
"[",
"sid",
"]",
"{",
"buf",
".",
"WriteByte",
"(",
"':'",
")",
"\n",
"buf",
".",
"WriteString",
"(",
"strconv",
".",
"FormatInt",
"(",
"interval",
".",
"start",
",",
"10",
")",
")",
"\n\n",
"if",
"interval",
".",
"end",
"!=",
"interval",
".",
"start",
"{",
"buf",
".",
"WriteByte",
"(",
"'-'",
")",
"\n",
"buf",
".",
"WriteString",
"(",
"strconv",
".",
"FormatInt",
"(",
"interval",
".",
"end",
",",
"10",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] | // String implements GTIDSet. | [
"String",
"implements",
"GTIDSet",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/mysql56_gtid_set.go#L151-L172 | train |
vitessio/vitess | go/mysql/mysql56_gtid_set.go | ContainsGTID | func (set Mysql56GTIDSet) ContainsGTID(gtid GTID) bool {
gtid56, ok := gtid.(Mysql56GTID)
if !ok {
return false
}
for _, iv := range set[gtid56.Server] {
if iv.start > gtid56.Sequence {
// We assume intervals are sorted, so we can skip the rest.
return false
}
if gtid56.Sequence <= iv.end {
// Now we know that: start <= Sequence <= end.
return true
}
}
// Server wasn't in the set, or no interval contained gtid.
return false
} | go | func (set Mysql56GTIDSet) ContainsGTID(gtid GTID) bool {
gtid56, ok := gtid.(Mysql56GTID)
if !ok {
return false
}
for _, iv := range set[gtid56.Server] {
if iv.start > gtid56.Sequence {
// We assume intervals are sorted, so we can skip the rest.
return false
}
if gtid56.Sequence <= iv.end {
// Now we know that: start <= Sequence <= end.
return true
}
}
// Server wasn't in the set, or no interval contained gtid.
return false
} | [
"func",
"(",
"set",
"Mysql56GTIDSet",
")",
"ContainsGTID",
"(",
"gtid",
"GTID",
")",
"bool",
"{",
"gtid56",
",",
"ok",
":=",
"gtid",
".",
"(",
"Mysql56GTID",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"iv",
":=",
"range",
"set",
"[",
"gtid56",
".",
"Server",
"]",
"{",
"if",
"iv",
".",
"start",
">",
"gtid56",
".",
"Sequence",
"{",
"// We assume intervals are sorted, so we can skip the rest.",
"return",
"false",
"\n",
"}",
"\n",
"if",
"gtid56",
".",
"Sequence",
"<=",
"iv",
".",
"end",
"{",
"// Now we know that: start <= Sequence <= end.",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"// Server wasn't in the set, or no interval contained gtid.",
"return",
"false",
"\n",
"}"
] | // ContainsGTID implements GTIDSet. | [
"ContainsGTID",
"implements",
"GTIDSet",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/mysql56_gtid_set.go#L178-L196 | train |
vitessio/vitess | go/mysql/mysql56_gtid_set.go | Contains | func (set Mysql56GTIDSet) Contains(other GTIDSet) bool {
other56, ok := other.(Mysql56GTIDSet)
if !ok {
return false
}
// Check each SID in the other set.
for sid, otherIntervals := range other56 {
i := 0
intervals := set[sid]
count := len(intervals)
// Check each interval for this SID in the other set.
for _, iv := range otherIntervals {
// Check that interval against each of our intervals.
// Intervals are monotonically increasing,
// so we don't need to reset the index each time.
for {
if i >= count {
// We ran out of intervals to check against.
return false
}
if intervals[i].contains(iv) {
// Yes it's covered. Go on to the next one.
break
}
i++
}
}
}
// No uncovered intervals were found.
return true
} | go | func (set Mysql56GTIDSet) Contains(other GTIDSet) bool {
other56, ok := other.(Mysql56GTIDSet)
if !ok {
return false
}
// Check each SID in the other set.
for sid, otherIntervals := range other56 {
i := 0
intervals := set[sid]
count := len(intervals)
// Check each interval for this SID in the other set.
for _, iv := range otherIntervals {
// Check that interval against each of our intervals.
// Intervals are monotonically increasing,
// so we don't need to reset the index each time.
for {
if i >= count {
// We ran out of intervals to check against.
return false
}
if intervals[i].contains(iv) {
// Yes it's covered. Go on to the next one.
break
}
i++
}
}
}
// No uncovered intervals were found.
return true
} | [
"func",
"(",
"set",
"Mysql56GTIDSet",
")",
"Contains",
"(",
"other",
"GTIDSet",
")",
"bool",
"{",
"other56",
",",
"ok",
":=",
"other",
".",
"(",
"Mysql56GTIDSet",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"// Check each SID in the other set.",
"for",
"sid",
",",
"otherIntervals",
":=",
"range",
"other56",
"{",
"i",
":=",
"0",
"\n",
"intervals",
":=",
"set",
"[",
"sid",
"]",
"\n",
"count",
":=",
"len",
"(",
"intervals",
")",
"\n\n",
"// Check each interval for this SID in the other set.",
"for",
"_",
",",
"iv",
":=",
"range",
"otherIntervals",
"{",
"// Check that interval against each of our intervals.",
"// Intervals are monotonically increasing,",
"// so we don't need to reset the index each time.",
"for",
"{",
"if",
"i",
">=",
"count",
"{",
"// We ran out of intervals to check against.",
"return",
"false",
"\n",
"}",
"\n",
"if",
"intervals",
"[",
"i",
"]",
".",
"contains",
"(",
"iv",
")",
"{",
"// Yes it's covered. Go on to the next one.",
"break",
"\n",
"}",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// No uncovered intervals were found.",
"return",
"true",
"\n",
"}"
] | // Contains implements GTIDSet. | [
"Contains",
"implements",
"GTIDSet",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/mysql56_gtid_set.go#L199-L232 | train |
vitessio/vitess | go/mysql/mysql56_gtid_set.go | Equal | func (set Mysql56GTIDSet) Equal(other GTIDSet) bool {
other56, ok := other.(Mysql56GTIDSet)
if !ok {
return false
}
// Check for same number of SIDs.
if len(set) != len(other56) {
return false
}
// Compare each SID.
for sid, intervals := range set {
otherIntervals := other56[sid]
// Check for same number of intervals.
if len(intervals) != len(otherIntervals) {
return false
}
// Compare each interval.
// Since intervals are sorted, they have to be in the same order.
for i, iv := range intervals {
if iv != otherIntervals[i] {
return false
}
}
}
// No discrepancies were found.
return true
} | go | func (set Mysql56GTIDSet) Equal(other GTIDSet) bool {
other56, ok := other.(Mysql56GTIDSet)
if !ok {
return false
}
// Check for same number of SIDs.
if len(set) != len(other56) {
return false
}
// Compare each SID.
for sid, intervals := range set {
otherIntervals := other56[sid]
// Check for same number of intervals.
if len(intervals) != len(otherIntervals) {
return false
}
// Compare each interval.
// Since intervals are sorted, they have to be in the same order.
for i, iv := range intervals {
if iv != otherIntervals[i] {
return false
}
}
}
// No discrepancies were found.
return true
} | [
"func",
"(",
"set",
"Mysql56GTIDSet",
")",
"Equal",
"(",
"other",
"GTIDSet",
")",
"bool",
"{",
"other56",
",",
"ok",
":=",
"other",
".",
"(",
"Mysql56GTIDSet",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"// Check for same number of SIDs.",
"if",
"len",
"(",
"set",
")",
"!=",
"len",
"(",
"other56",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"// Compare each SID.",
"for",
"sid",
",",
"intervals",
":=",
"range",
"set",
"{",
"otherIntervals",
":=",
"other56",
"[",
"sid",
"]",
"\n\n",
"// Check for same number of intervals.",
"if",
"len",
"(",
"intervals",
")",
"!=",
"len",
"(",
"otherIntervals",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"// Compare each interval.",
"// Since intervals are sorted, they have to be in the same order.",
"for",
"i",
",",
"iv",
":=",
"range",
"intervals",
"{",
"if",
"iv",
"!=",
"otherIntervals",
"[",
"i",
"]",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// No discrepancies were found.",
"return",
"true",
"\n",
"}"
] | // Equal implements GTIDSet. | [
"Equal",
"implements",
"GTIDSet",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/mysql56_gtid_set.go#L235-L266 | train |
vitessio/vitess | go/mysql/mysql56_gtid_set.go | AddGTID | func (set Mysql56GTIDSet) AddGTID(gtid GTID) GTIDSet {
gtid56, ok := gtid.(Mysql56GTID)
if !ok {
return set
}
// If it's already in the set, we can return the same instance.
// This is safe because GTIDSets are immutable.
if set.ContainsGTID(gtid) {
return set
}
// Make a copy and add the new GTID in the proper place.
// This function is not supposed to modify the original set.
newSet := make(Mysql56GTIDSet)
added := false
for sid, intervals := range set {
newIntervals := make([]interval, 0, len(intervals))
if sid == gtid56.Server {
// Look for the right place to add this GTID.
for _, iv := range intervals {
if !added {
switch {
case gtid56.Sequence == iv.start-1:
// Expand the interval at the beginning.
iv.start = gtid56.Sequence
added = true
case gtid56.Sequence == iv.end+1:
// Expand the interval at the end.
iv.end = gtid56.Sequence
added = true
case gtid56.Sequence < iv.start-1:
// The next interval is beyond the new GTID, but it can't
// be expanded, so we have to insert a new interval.
newIntervals = append(newIntervals, interval{start: gtid56.Sequence, end: gtid56.Sequence})
added = true
}
}
// Check if this interval can be merged with the previous one.
count := len(newIntervals)
if count != 0 && iv.start == newIntervals[count-1].end+1 {
// Merge instead of appending.
newIntervals[count-1].end = iv.end
} else {
// Can't be merged.
newIntervals = append(newIntervals, iv)
}
}
} else {
// Just copy everything.
newIntervals = append(newIntervals, intervals...)
}
newSet[sid] = newIntervals
}
if !added {
// There wasn't any place to insert the new GTID, so just append it
// as a new interval.
newSet[gtid56.Server] = append(newSet[gtid56.Server], interval{start: gtid56.Sequence, end: gtid56.Sequence})
}
return newSet
} | go | func (set Mysql56GTIDSet) AddGTID(gtid GTID) GTIDSet {
gtid56, ok := gtid.(Mysql56GTID)
if !ok {
return set
}
// If it's already in the set, we can return the same instance.
// This is safe because GTIDSets are immutable.
if set.ContainsGTID(gtid) {
return set
}
// Make a copy and add the new GTID in the proper place.
// This function is not supposed to modify the original set.
newSet := make(Mysql56GTIDSet)
added := false
for sid, intervals := range set {
newIntervals := make([]interval, 0, len(intervals))
if sid == gtid56.Server {
// Look for the right place to add this GTID.
for _, iv := range intervals {
if !added {
switch {
case gtid56.Sequence == iv.start-1:
// Expand the interval at the beginning.
iv.start = gtid56.Sequence
added = true
case gtid56.Sequence == iv.end+1:
// Expand the interval at the end.
iv.end = gtid56.Sequence
added = true
case gtid56.Sequence < iv.start-1:
// The next interval is beyond the new GTID, but it can't
// be expanded, so we have to insert a new interval.
newIntervals = append(newIntervals, interval{start: gtid56.Sequence, end: gtid56.Sequence})
added = true
}
}
// Check if this interval can be merged with the previous one.
count := len(newIntervals)
if count != 0 && iv.start == newIntervals[count-1].end+1 {
// Merge instead of appending.
newIntervals[count-1].end = iv.end
} else {
// Can't be merged.
newIntervals = append(newIntervals, iv)
}
}
} else {
// Just copy everything.
newIntervals = append(newIntervals, intervals...)
}
newSet[sid] = newIntervals
}
if !added {
// There wasn't any place to insert the new GTID, so just append it
// as a new interval.
newSet[gtid56.Server] = append(newSet[gtid56.Server], interval{start: gtid56.Sequence, end: gtid56.Sequence})
}
return newSet
} | [
"func",
"(",
"set",
"Mysql56GTIDSet",
")",
"AddGTID",
"(",
"gtid",
"GTID",
")",
"GTIDSet",
"{",
"gtid56",
",",
"ok",
":=",
"gtid",
".",
"(",
"Mysql56GTID",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"set",
"\n",
"}",
"\n\n",
"// If it's already in the set, we can return the same instance.",
"// This is safe because GTIDSets are immutable.",
"if",
"set",
".",
"ContainsGTID",
"(",
"gtid",
")",
"{",
"return",
"set",
"\n",
"}",
"\n\n",
"// Make a copy and add the new GTID in the proper place.",
"// This function is not supposed to modify the original set.",
"newSet",
":=",
"make",
"(",
"Mysql56GTIDSet",
")",
"\n\n",
"added",
":=",
"false",
"\n\n",
"for",
"sid",
",",
"intervals",
":=",
"range",
"set",
"{",
"newIntervals",
":=",
"make",
"(",
"[",
"]",
"interval",
",",
"0",
",",
"len",
"(",
"intervals",
")",
")",
"\n\n",
"if",
"sid",
"==",
"gtid56",
".",
"Server",
"{",
"// Look for the right place to add this GTID.",
"for",
"_",
",",
"iv",
":=",
"range",
"intervals",
"{",
"if",
"!",
"added",
"{",
"switch",
"{",
"case",
"gtid56",
".",
"Sequence",
"==",
"iv",
".",
"start",
"-",
"1",
":",
"// Expand the interval at the beginning.",
"iv",
".",
"start",
"=",
"gtid56",
".",
"Sequence",
"\n",
"added",
"=",
"true",
"\n",
"case",
"gtid56",
".",
"Sequence",
"==",
"iv",
".",
"end",
"+",
"1",
":",
"// Expand the interval at the end.",
"iv",
".",
"end",
"=",
"gtid56",
".",
"Sequence",
"\n",
"added",
"=",
"true",
"\n",
"case",
"gtid56",
".",
"Sequence",
"<",
"iv",
".",
"start",
"-",
"1",
":",
"// The next interval is beyond the new GTID, but it can't",
"// be expanded, so we have to insert a new interval.",
"newIntervals",
"=",
"append",
"(",
"newIntervals",
",",
"interval",
"{",
"start",
":",
"gtid56",
".",
"Sequence",
",",
"end",
":",
"gtid56",
".",
"Sequence",
"}",
")",
"\n",
"added",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"// Check if this interval can be merged with the previous one.",
"count",
":=",
"len",
"(",
"newIntervals",
")",
"\n",
"if",
"count",
"!=",
"0",
"&&",
"iv",
".",
"start",
"==",
"newIntervals",
"[",
"count",
"-",
"1",
"]",
".",
"end",
"+",
"1",
"{",
"// Merge instead of appending.",
"newIntervals",
"[",
"count",
"-",
"1",
"]",
".",
"end",
"=",
"iv",
".",
"end",
"\n",
"}",
"else",
"{",
"// Can't be merged.",
"newIntervals",
"=",
"append",
"(",
"newIntervals",
",",
"iv",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// Just copy everything.",
"newIntervals",
"=",
"append",
"(",
"newIntervals",
",",
"intervals",
"...",
")",
"\n",
"}",
"\n\n",
"newSet",
"[",
"sid",
"]",
"=",
"newIntervals",
"\n",
"}",
"\n\n",
"if",
"!",
"added",
"{",
"// There wasn't any place to insert the new GTID, so just append it",
"// as a new interval.",
"newSet",
"[",
"gtid56",
".",
"Server",
"]",
"=",
"append",
"(",
"newSet",
"[",
"gtid56",
".",
"Server",
"]",
",",
"interval",
"{",
"start",
":",
"gtid56",
".",
"Sequence",
",",
"end",
":",
"gtid56",
".",
"Sequence",
"}",
")",
"\n",
"}",
"\n\n",
"return",
"newSet",
"\n",
"}"
] | // AddGTID implements GTIDSet. | [
"AddGTID",
"implements",
"GTIDSet",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/mysql56_gtid_set.go#L269-L335 | train |
vitessio/vitess | go/vt/servenv/grpc_server.go | isGRPCEnabled | func isGRPCEnabled() bool {
if GRPCPort != nil && *GRPCPort != 0 {
return true
}
if SocketFile != nil && *SocketFile != "" {
return true
}
return false
} | go | func isGRPCEnabled() bool {
if GRPCPort != nil && *GRPCPort != 0 {
return true
}
if SocketFile != nil && *SocketFile != "" {
return true
}
return false
} | [
"func",
"isGRPCEnabled",
"(",
")",
"bool",
"{",
"if",
"GRPCPort",
"!=",
"nil",
"&&",
"*",
"GRPCPort",
"!=",
"0",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"if",
"SocketFile",
"!=",
"nil",
"&&",
"*",
"SocketFile",
"!=",
"\"",
"\"",
"{",
"return",
"true",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}"
] | // isGRPCEnabled returns true if gRPC server is set | [
"isGRPCEnabled",
"returns",
"true",
"if",
"gRPC",
"server",
"is",
"set"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/servenv/grpc_server.go#L100-L110 | train |
vitessio/vitess | go/vt/servenv/grpc_server.go | createGRPCServer | func createGRPCServer() {
// skip if not registered
if !isGRPCEnabled() {
log.Infof("Skipping gRPC server creation")
return
}
grpccommon.EnableTracingOpt()
var opts []grpc.ServerOption
if GRPCPort != nil && *GRPCCert != "" && *GRPCKey != "" {
config, err := vttls.ServerConfig(*GRPCCert, *GRPCKey, *GRPCCA)
if err != nil {
log.Exitf("Failed to log gRPC cert/key/ca: %v", err)
}
// create the creds server options
creds := credentials.NewTLS(config)
opts = []grpc.ServerOption{grpc.Creds(creds)}
}
// Override the default max message size for both send and receive
// (which is 4 MiB in gRPC 1.0.0).
// Large messages can occur when users try to insert or fetch very big
// rows. If they hit the limit, they'll see the following error:
// grpc: received message length XXXXXXX exceeding the max size 4194304
// Note: For gRPC 1.0.0 it's sufficient to set the limit on the server only
// because it's not enforced on the client side.
log.Infof("Setting grpc max message size to %d", *grpccommon.MaxMessageSize)
opts = append(opts, grpc.MaxRecvMsgSize(*grpccommon.MaxMessageSize))
opts = append(opts, grpc.MaxSendMsgSize(*grpccommon.MaxMessageSize))
if *GRPCInitialConnWindowSize != 0 {
log.Infof("Setting grpc server initial conn window size to %d", int32(*GRPCInitialConnWindowSize))
opts = append(opts, grpc.InitialConnWindowSize(int32(*GRPCInitialConnWindowSize)))
}
if *GRPCInitialWindowSize != 0 {
log.Infof("Setting grpc server initial window size to %d", int32(*GRPCInitialWindowSize))
opts = append(opts, grpc.InitialWindowSize(int32(*GRPCInitialWindowSize)))
}
ep := keepalive.EnforcementPolicy{
MinTime: *GRPCKeepAliveEnforcementPolicyMinTime,
PermitWithoutStream: *GRPCKeepAliveEnforcementPolicyPermitWithoutStream,
}
opts = append(opts, grpc.KeepaliveEnforcementPolicy(ep))
if GRPCMaxConnectionAge != nil {
ka := keepalive.ServerParameters{
MaxConnectionAge: *GRPCMaxConnectionAge,
}
if GRPCMaxConnectionAgeGrace != nil {
ka.MaxConnectionAgeGrace = *GRPCMaxConnectionAgeGrace
}
opts = append(opts, grpc.KeepaliveParams(ka))
}
opts = append(opts, interceptors()...)
GRPCServer = grpc.NewServer(opts...)
} | go | func createGRPCServer() {
// skip if not registered
if !isGRPCEnabled() {
log.Infof("Skipping gRPC server creation")
return
}
grpccommon.EnableTracingOpt()
var opts []grpc.ServerOption
if GRPCPort != nil && *GRPCCert != "" && *GRPCKey != "" {
config, err := vttls.ServerConfig(*GRPCCert, *GRPCKey, *GRPCCA)
if err != nil {
log.Exitf("Failed to log gRPC cert/key/ca: %v", err)
}
// create the creds server options
creds := credentials.NewTLS(config)
opts = []grpc.ServerOption{grpc.Creds(creds)}
}
// Override the default max message size for both send and receive
// (which is 4 MiB in gRPC 1.0.0).
// Large messages can occur when users try to insert or fetch very big
// rows. If they hit the limit, they'll see the following error:
// grpc: received message length XXXXXXX exceeding the max size 4194304
// Note: For gRPC 1.0.0 it's sufficient to set the limit on the server only
// because it's not enforced on the client side.
log.Infof("Setting grpc max message size to %d", *grpccommon.MaxMessageSize)
opts = append(opts, grpc.MaxRecvMsgSize(*grpccommon.MaxMessageSize))
opts = append(opts, grpc.MaxSendMsgSize(*grpccommon.MaxMessageSize))
if *GRPCInitialConnWindowSize != 0 {
log.Infof("Setting grpc server initial conn window size to %d", int32(*GRPCInitialConnWindowSize))
opts = append(opts, grpc.InitialConnWindowSize(int32(*GRPCInitialConnWindowSize)))
}
if *GRPCInitialWindowSize != 0 {
log.Infof("Setting grpc server initial window size to %d", int32(*GRPCInitialWindowSize))
opts = append(opts, grpc.InitialWindowSize(int32(*GRPCInitialWindowSize)))
}
ep := keepalive.EnforcementPolicy{
MinTime: *GRPCKeepAliveEnforcementPolicyMinTime,
PermitWithoutStream: *GRPCKeepAliveEnforcementPolicyPermitWithoutStream,
}
opts = append(opts, grpc.KeepaliveEnforcementPolicy(ep))
if GRPCMaxConnectionAge != nil {
ka := keepalive.ServerParameters{
MaxConnectionAge: *GRPCMaxConnectionAge,
}
if GRPCMaxConnectionAgeGrace != nil {
ka.MaxConnectionAgeGrace = *GRPCMaxConnectionAgeGrace
}
opts = append(opts, grpc.KeepaliveParams(ka))
}
opts = append(opts, interceptors()...)
GRPCServer = grpc.NewServer(opts...)
} | [
"func",
"createGRPCServer",
"(",
")",
"{",
"// skip if not registered",
"if",
"!",
"isGRPCEnabled",
"(",
")",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"grpccommon",
".",
"EnableTracingOpt",
"(",
")",
"\n\n",
"var",
"opts",
"[",
"]",
"grpc",
".",
"ServerOption",
"\n",
"if",
"GRPCPort",
"!=",
"nil",
"&&",
"*",
"GRPCCert",
"!=",
"\"",
"\"",
"&&",
"*",
"GRPCKey",
"!=",
"\"",
"\"",
"{",
"config",
",",
"err",
":=",
"vttls",
".",
"ServerConfig",
"(",
"*",
"GRPCCert",
",",
"*",
"GRPCKey",
",",
"*",
"GRPCCA",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Exitf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// create the creds server options",
"creds",
":=",
"credentials",
".",
"NewTLS",
"(",
"config",
")",
"\n",
"opts",
"=",
"[",
"]",
"grpc",
".",
"ServerOption",
"{",
"grpc",
".",
"Creds",
"(",
"creds",
")",
"}",
"\n",
"}",
"\n",
"// Override the default max message size for both send and receive",
"// (which is 4 MiB in gRPC 1.0.0).",
"// Large messages can occur when users try to insert or fetch very big",
"// rows. If they hit the limit, they'll see the following error:",
"// grpc: received message length XXXXXXX exceeding the max size 4194304",
"// Note: For gRPC 1.0.0 it's sufficient to set the limit on the server only",
"// because it's not enforced on the client side.",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"*",
"grpccommon",
".",
"MaxMessageSize",
")",
"\n",
"opts",
"=",
"append",
"(",
"opts",
",",
"grpc",
".",
"MaxRecvMsgSize",
"(",
"*",
"grpccommon",
".",
"MaxMessageSize",
")",
")",
"\n",
"opts",
"=",
"append",
"(",
"opts",
",",
"grpc",
".",
"MaxSendMsgSize",
"(",
"*",
"grpccommon",
".",
"MaxMessageSize",
")",
")",
"\n\n",
"if",
"*",
"GRPCInitialConnWindowSize",
"!=",
"0",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"int32",
"(",
"*",
"GRPCInitialConnWindowSize",
")",
")",
"\n",
"opts",
"=",
"append",
"(",
"opts",
",",
"grpc",
".",
"InitialConnWindowSize",
"(",
"int32",
"(",
"*",
"GRPCInitialConnWindowSize",
")",
")",
")",
"\n",
"}",
"\n\n",
"if",
"*",
"GRPCInitialWindowSize",
"!=",
"0",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"int32",
"(",
"*",
"GRPCInitialWindowSize",
")",
")",
"\n",
"opts",
"=",
"append",
"(",
"opts",
",",
"grpc",
".",
"InitialWindowSize",
"(",
"int32",
"(",
"*",
"GRPCInitialWindowSize",
")",
")",
")",
"\n",
"}",
"\n\n",
"ep",
":=",
"keepalive",
".",
"EnforcementPolicy",
"{",
"MinTime",
":",
"*",
"GRPCKeepAliveEnforcementPolicyMinTime",
",",
"PermitWithoutStream",
":",
"*",
"GRPCKeepAliveEnforcementPolicyPermitWithoutStream",
",",
"}",
"\n",
"opts",
"=",
"append",
"(",
"opts",
",",
"grpc",
".",
"KeepaliveEnforcementPolicy",
"(",
"ep",
")",
")",
"\n\n",
"if",
"GRPCMaxConnectionAge",
"!=",
"nil",
"{",
"ka",
":=",
"keepalive",
".",
"ServerParameters",
"{",
"MaxConnectionAge",
":",
"*",
"GRPCMaxConnectionAge",
",",
"}",
"\n",
"if",
"GRPCMaxConnectionAgeGrace",
"!=",
"nil",
"{",
"ka",
".",
"MaxConnectionAgeGrace",
"=",
"*",
"GRPCMaxConnectionAgeGrace",
"\n",
"}",
"\n",
"opts",
"=",
"append",
"(",
"opts",
",",
"grpc",
".",
"KeepaliveParams",
"(",
"ka",
")",
")",
"\n",
"}",
"\n\n",
"opts",
"=",
"append",
"(",
"opts",
",",
"interceptors",
"(",
")",
"...",
")",
"\n\n",
"GRPCServer",
"=",
"grpc",
".",
"NewServer",
"(",
"opts",
"...",
")",
"\n",
"}"
] | // createGRPCServer create the gRPC server we will be using.
// It has to be called after flags are parsed, but before
// services register themselves. | [
"createGRPCServer",
"create",
"the",
"gRPC",
"server",
"we",
"will",
"be",
"using",
".",
"It",
"has",
"to",
"be",
"called",
"after",
"flags",
"are",
"parsed",
"but",
"before",
"services",
"register",
"themselves",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/servenv/grpc_server.go#L115-L175 | train |
vitessio/vitess | go/vt/servenv/grpc_server.go | interceptors | func interceptors() []grpc.ServerOption {
interceptors := &serverInterceptorBuilder{}
if *GRPCAuth != "" {
log.Infof("enabling auth plugin %v", *GRPCAuth)
pluginInitializer := GetAuthenticator(*GRPCAuth)
authPluginImpl, err := pluginInitializer()
if err != nil {
log.Fatalf("Failed to load auth plugin: %v", err)
}
authPlugin = authPluginImpl
interceptors.Add(authenticatingStreamInterceptor, authenticatingUnaryInterceptor)
}
if *grpccommon.EnableGRPCPrometheus {
interceptors.Add(grpc_prometheus.StreamServerInterceptor, grpc_prometheus.UnaryServerInterceptor)
}
trace.AddGrpcServerOptions(interceptors.Add)
return interceptors.Build()
} | go | func interceptors() []grpc.ServerOption {
interceptors := &serverInterceptorBuilder{}
if *GRPCAuth != "" {
log.Infof("enabling auth plugin %v", *GRPCAuth)
pluginInitializer := GetAuthenticator(*GRPCAuth)
authPluginImpl, err := pluginInitializer()
if err != nil {
log.Fatalf("Failed to load auth plugin: %v", err)
}
authPlugin = authPluginImpl
interceptors.Add(authenticatingStreamInterceptor, authenticatingUnaryInterceptor)
}
if *grpccommon.EnableGRPCPrometheus {
interceptors.Add(grpc_prometheus.StreamServerInterceptor, grpc_prometheus.UnaryServerInterceptor)
}
trace.AddGrpcServerOptions(interceptors.Add)
return interceptors.Build()
} | [
"func",
"interceptors",
"(",
")",
"[",
"]",
"grpc",
".",
"ServerOption",
"{",
"interceptors",
":=",
"&",
"serverInterceptorBuilder",
"{",
"}",
"\n\n",
"if",
"*",
"GRPCAuth",
"!=",
"\"",
"\"",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"*",
"GRPCAuth",
")",
"\n",
"pluginInitializer",
":=",
"GetAuthenticator",
"(",
"*",
"GRPCAuth",
")",
"\n",
"authPluginImpl",
",",
"err",
":=",
"pluginInitializer",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"authPlugin",
"=",
"authPluginImpl",
"\n",
"interceptors",
".",
"Add",
"(",
"authenticatingStreamInterceptor",
",",
"authenticatingUnaryInterceptor",
")",
"\n",
"}",
"\n\n",
"if",
"*",
"grpccommon",
".",
"EnableGRPCPrometheus",
"{",
"interceptors",
".",
"Add",
"(",
"grpc_prometheus",
".",
"StreamServerInterceptor",
",",
"grpc_prometheus",
".",
"UnaryServerInterceptor",
")",
"\n",
"}",
"\n\n",
"trace",
".",
"AddGrpcServerOptions",
"(",
"interceptors",
".",
"Add",
")",
"\n\n",
"return",
"interceptors",
".",
"Build",
"(",
")",
"\n",
"}"
] | // We can only set a ServerInterceptor once, so we chain multiple interceptors into one | [
"We",
"can",
"only",
"set",
"a",
"ServerInterceptor",
"once",
"so",
"we",
"chain",
"multiple",
"interceptors",
"into",
"one"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/servenv/grpc_server.go#L178-L199 | train |
vitessio/vitess | go/vt/servenv/grpc_server.go | WrapServerStream | func WrapServerStream(stream grpc.ServerStream) *WrappedServerStream {
if existing, ok := stream.(*WrappedServerStream); ok {
return existing
}
return &WrappedServerStream{ServerStream: stream, WrappedContext: stream.Context()}
} | go | func WrapServerStream(stream grpc.ServerStream) *WrappedServerStream {
if existing, ok := stream.(*WrappedServerStream); ok {
return existing
}
return &WrappedServerStream{ServerStream: stream, WrappedContext: stream.Context()}
} | [
"func",
"WrapServerStream",
"(",
"stream",
"grpc",
".",
"ServerStream",
")",
"*",
"WrappedServerStream",
"{",
"if",
"existing",
",",
"ok",
":=",
"stream",
".",
"(",
"*",
"WrappedServerStream",
")",
";",
"ok",
"{",
"return",
"existing",
"\n",
"}",
"\n",
"return",
"&",
"WrappedServerStream",
"{",
"ServerStream",
":",
"stream",
",",
"WrappedContext",
":",
"stream",
".",
"Context",
"(",
")",
"}",
"\n",
"}"
] | // WrapServerStream returns a ServerStream that has the ability to overwrite context. | [
"WrapServerStream",
"returns",
"a",
"ServerStream",
"that",
"has",
"the",
"ability",
"to",
"overwrite",
"context",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/servenv/grpc_server.go#L279-L284 | train |
vitessio/vitess | go/vt/servenv/grpc_server.go | Add | func (collector *serverInterceptorBuilder) Add(s grpc.StreamServerInterceptor, u grpc.UnaryServerInterceptor) {
collector.streamInterceptors = append(collector.streamInterceptors, s)
collector.unaryInterceptors = append(collector.unaryInterceptors, u)
} | go | func (collector *serverInterceptorBuilder) Add(s grpc.StreamServerInterceptor, u grpc.UnaryServerInterceptor) {
collector.streamInterceptors = append(collector.streamInterceptors, s)
collector.unaryInterceptors = append(collector.unaryInterceptors, u)
} | [
"func",
"(",
"collector",
"*",
"serverInterceptorBuilder",
")",
"Add",
"(",
"s",
"grpc",
".",
"StreamServerInterceptor",
",",
"u",
"grpc",
".",
"UnaryServerInterceptor",
")",
"{",
"collector",
".",
"streamInterceptors",
"=",
"append",
"(",
"collector",
".",
"streamInterceptors",
",",
"s",
")",
"\n",
"collector",
".",
"unaryInterceptors",
"=",
"append",
"(",
"collector",
".",
"unaryInterceptors",
",",
"u",
")",
"\n",
"}"
] | // Add adds interceptors to the builder | [
"Add",
"adds",
"interceptors",
"to",
"the",
"builder"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/servenv/grpc_server.go#L293-L296 | train |
vitessio/vitess | go/vt/servenv/grpc_server.go | AddUnary | func (collector *serverInterceptorBuilder) AddUnary(u grpc.UnaryServerInterceptor) {
collector.unaryInterceptors = append(collector.unaryInterceptors, u)
} | go | func (collector *serverInterceptorBuilder) AddUnary(u grpc.UnaryServerInterceptor) {
collector.unaryInterceptors = append(collector.unaryInterceptors, u)
} | [
"func",
"(",
"collector",
"*",
"serverInterceptorBuilder",
")",
"AddUnary",
"(",
"u",
"grpc",
".",
"UnaryServerInterceptor",
")",
"{",
"collector",
".",
"unaryInterceptors",
"=",
"append",
"(",
"collector",
".",
"unaryInterceptors",
",",
"u",
")",
"\n",
"}"
] | // AddUnary adds a single unary interceptor to the builder | [
"AddUnary",
"adds",
"a",
"single",
"unary",
"interceptor",
"to",
"the",
"builder"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/servenv/grpc_server.go#L299-L301 | train |
vitessio/vitess | go/vt/workflow/sleep_workflow.go | Run | func (sw *SleepWorkflow) Run(ctx context.Context, manager *Manager, wi *topo.WorkflowInfo) error {
// Save all values, create a UI Node.
sw.mu.Lock()
sw.manager = manager
sw.wi = wi
sw.node.Listener = sw
sw.node.Display = NodeDisplayDeterminate
sw.node.Actions = []*Action{
{
Name: pauseAction,
State: ActionStateEnabled,
Style: ActionStyleNormal,
},
{
Name: resumeAction,
State: ActionStateDisabled,
Style: ActionStyleNormal,
},
}
sw.uiUpdateLocked()
sw.node.BroadcastChanges(false /* updateChildren */)
sw.mu.Unlock()
for {
sw.mu.Lock()
data := *sw.data
sw.mu.Unlock()
if data.Slept == data.Duration {
break
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(time.Second):
if !data.Paused {
sw.mu.Lock()
sw.data.Slept++
// UI update every second.
sw.uiUpdateLocked()
sw.node.BroadcastChanges(false /* updateChildren */)
// Checkpoint every 5 seconds.
if sw.data.Slept%5 == 0 {
if err := sw.checkpointLocked(ctx); err != nil {
sw.mu.Unlock()
return err
}
}
sw.mu.Unlock()
}
}
}
return nil
} | go | func (sw *SleepWorkflow) Run(ctx context.Context, manager *Manager, wi *topo.WorkflowInfo) error {
// Save all values, create a UI Node.
sw.mu.Lock()
sw.manager = manager
sw.wi = wi
sw.node.Listener = sw
sw.node.Display = NodeDisplayDeterminate
sw.node.Actions = []*Action{
{
Name: pauseAction,
State: ActionStateEnabled,
Style: ActionStyleNormal,
},
{
Name: resumeAction,
State: ActionStateDisabled,
Style: ActionStyleNormal,
},
}
sw.uiUpdateLocked()
sw.node.BroadcastChanges(false /* updateChildren */)
sw.mu.Unlock()
for {
sw.mu.Lock()
data := *sw.data
sw.mu.Unlock()
if data.Slept == data.Duration {
break
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(time.Second):
if !data.Paused {
sw.mu.Lock()
sw.data.Slept++
// UI update every second.
sw.uiUpdateLocked()
sw.node.BroadcastChanges(false /* updateChildren */)
// Checkpoint every 5 seconds.
if sw.data.Slept%5 == 0 {
if err := sw.checkpointLocked(ctx); err != nil {
sw.mu.Unlock()
return err
}
}
sw.mu.Unlock()
}
}
}
return nil
} | [
"func",
"(",
"sw",
"*",
"SleepWorkflow",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"manager",
"*",
"Manager",
",",
"wi",
"*",
"topo",
".",
"WorkflowInfo",
")",
"error",
"{",
"// Save all values, create a UI Node.",
"sw",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"sw",
".",
"manager",
"=",
"manager",
"\n",
"sw",
".",
"wi",
"=",
"wi",
"\n\n",
"sw",
".",
"node",
".",
"Listener",
"=",
"sw",
"\n",
"sw",
".",
"node",
".",
"Display",
"=",
"NodeDisplayDeterminate",
"\n",
"sw",
".",
"node",
".",
"Actions",
"=",
"[",
"]",
"*",
"Action",
"{",
"{",
"Name",
":",
"pauseAction",
",",
"State",
":",
"ActionStateEnabled",
",",
"Style",
":",
"ActionStyleNormal",
",",
"}",
",",
"{",
"Name",
":",
"resumeAction",
",",
"State",
":",
"ActionStateDisabled",
",",
"Style",
":",
"ActionStyleNormal",
",",
"}",
",",
"}",
"\n",
"sw",
".",
"uiUpdateLocked",
"(",
")",
"\n",
"sw",
".",
"node",
".",
"BroadcastChanges",
"(",
"false",
"/* updateChildren */",
")",
"\n",
"sw",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"for",
"{",
"sw",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"data",
":=",
"*",
"sw",
".",
"data",
"\n",
"sw",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"data",
".",
"Slept",
"==",
"data",
".",
"Duration",
"{",
"break",
"\n",
"}",
"\n\n",
"select",
"{",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"ctx",
".",
"Err",
"(",
")",
"\n",
"case",
"<-",
"time",
".",
"After",
"(",
"time",
".",
"Second",
")",
":",
"if",
"!",
"data",
".",
"Paused",
"{",
"sw",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"sw",
".",
"data",
".",
"Slept",
"++",
"\n",
"// UI update every second.",
"sw",
".",
"uiUpdateLocked",
"(",
")",
"\n",
"sw",
".",
"node",
".",
"BroadcastChanges",
"(",
"false",
"/* updateChildren */",
")",
"\n",
"// Checkpoint every 5 seconds.",
"if",
"sw",
".",
"data",
".",
"Slept",
"%",
"5",
"==",
"0",
"{",
"if",
"err",
":=",
"sw",
".",
"checkpointLocked",
"(",
"ctx",
")",
";",
"err",
"!=",
"nil",
"{",
"sw",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"sw",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Run is part of the workflow.Workflow interface.
// It updates the UI every second, and checkpoints every 5 seconds. | [
"Run",
"is",
"part",
"of",
"the",
"workflow",
".",
"Workflow",
"interface",
".",
"It",
"updates",
"the",
"UI",
"every",
"second",
"and",
"checkpoints",
"every",
"5",
"seconds",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/sleep_workflow.go#L83-L139 | train |
vitessio/vitess | go/vt/workflow/sleep_workflow.go | checkpointLocked | func (sw *SleepWorkflow) checkpointLocked(ctx context.Context) error {
var err error
sw.wi.Data, err = json.Marshal(sw.data)
if err != nil {
return err
}
err = sw.manager.TopoServer().SaveWorkflow(ctx, sw.wi)
if err != nil {
sw.logger.Errorf("SaveWorkflow failed: %v", err)
} else {
sw.logger.Infof("SaveWorkflow successful")
}
return err
} | go | func (sw *SleepWorkflow) checkpointLocked(ctx context.Context) error {
var err error
sw.wi.Data, err = json.Marshal(sw.data)
if err != nil {
return err
}
err = sw.manager.TopoServer().SaveWorkflow(ctx, sw.wi)
if err != nil {
sw.logger.Errorf("SaveWorkflow failed: %v", err)
} else {
sw.logger.Infof("SaveWorkflow successful")
}
return err
} | [
"func",
"(",
"sw",
"*",
"SleepWorkflow",
")",
"checkpointLocked",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"sw",
".",
"wi",
".",
"Data",
",",
"err",
"=",
"json",
".",
"Marshal",
"(",
"sw",
".",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"sw",
".",
"manager",
".",
"TopoServer",
"(",
")",
".",
"SaveWorkflow",
"(",
"ctx",
",",
"sw",
".",
"wi",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"sw",
".",
"logger",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"sw",
".",
"logger",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // checkpointLocked saves a checkpoint in topo server.
// Needs to be called with the lock. | [
"checkpointLocked",
"saves",
"a",
"checkpoint",
"in",
"topo",
"server",
".",
"Needs",
"to",
"be",
"called",
"with",
"the",
"lock",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/workflow/sleep_workflow.go#L190-L203 | train |
vitessio/vitess | go/vt/vtgate/vschema_stats.go | NewVSchemaStats | func NewVSchemaStats(vschema *vindexes.VSchema, errorMessage string) *VSchemaStats {
stats := &VSchemaStats{
Error: errorMessage,
Keyspaces: make([]*VSchemaKeyspaceStats, 0, len(vschema.Keyspaces)),
}
for n, k := range vschema.Keyspaces {
s := &VSchemaKeyspaceStats{
Keyspace: n,
}
if k.Keyspace != nil {
s.Sharded = k.Keyspace.Sharded
s.TableCount += len(k.Tables)
for _, t := range k.Tables {
s.VindexCount += len(t.ColumnVindexes) + len(t.Ordered) + len(t.Owned)
}
}
if k.Error != nil {
s.Error = k.Error.Error()
}
stats.Keyspaces = append(stats.Keyspaces, s)
}
sort.Slice(stats.Keyspaces, func(i, j int) bool { return stats.Keyspaces[i].Keyspace < stats.Keyspaces[j].Keyspace })
return stats
} | go | func NewVSchemaStats(vschema *vindexes.VSchema, errorMessage string) *VSchemaStats {
stats := &VSchemaStats{
Error: errorMessage,
Keyspaces: make([]*VSchemaKeyspaceStats, 0, len(vschema.Keyspaces)),
}
for n, k := range vschema.Keyspaces {
s := &VSchemaKeyspaceStats{
Keyspace: n,
}
if k.Keyspace != nil {
s.Sharded = k.Keyspace.Sharded
s.TableCount += len(k.Tables)
for _, t := range k.Tables {
s.VindexCount += len(t.ColumnVindexes) + len(t.Ordered) + len(t.Owned)
}
}
if k.Error != nil {
s.Error = k.Error.Error()
}
stats.Keyspaces = append(stats.Keyspaces, s)
}
sort.Slice(stats.Keyspaces, func(i, j int) bool { return stats.Keyspaces[i].Keyspace < stats.Keyspaces[j].Keyspace })
return stats
} | [
"func",
"NewVSchemaStats",
"(",
"vschema",
"*",
"vindexes",
".",
"VSchema",
",",
"errorMessage",
"string",
")",
"*",
"VSchemaStats",
"{",
"stats",
":=",
"&",
"VSchemaStats",
"{",
"Error",
":",
"errorMessage",
",",
"Keyspaces",
":",
"make",
"(",
"[",
"]",
"*",
"VSchemaKeyspaceStats",
",",
"0",
",",
"len",
"(",
"vschema",
".",
"Keyspaces",
")",
")",
",",
"}",
"\n",
"for",
"n",
",",
"k",
":=",
"range",
"vschema",
".",
"Keyspaces",
"{",
"s",
":=",
"&",
"VSchemaKeyspaceStats",
"{",
"Keyspace",
":",
"n",
",",
"}",
"\n",
"if",
"k",
".",
"Keyspace",
"!=",
"nil",
"{",
"s",
".",
"Sharded",
"=",
"k",
".",
"Keyspace",
".",
"Sharded",
"\n",
"s",
".",
"TableCount",
"+=",
"len",
"(",
"k",
".",
"Tables",
")",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"k",
".",
"Tables",
"{",
"s",
".",
"VindexCount",
"+=",
"len",
"(",
"t",
".",
"ColumnVindexes",
")",
"+",
"len",
"(",
"t",
".",
"Ordered",
")",
"+",
"len",
"(",
"t",
".",
"Owned",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"k",
".",
"Error",
"!=",
"nil",
"{",
"s",
".",
"Error",
"=",
"k",
".",
"Error",
".",
"Error",
"(",
")",
"\n",
"}",
"\n",
"stats",
".",
"Keyspaces",
"=",
"append",
"(",
"stats",
".",
"Keyspaces",
",",
"s",
")",
"\n",
"}",
"\n",
"sort",
".",
"Slice",
"(",
"stats",
".",
"Keyspaces",
",",
"func",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"return",
"stats",
".",
"Keyspaces",
"[",
"i",
"]",
".",
"Keyspace",
"<",
"stats",
".",
"Keyspaces",
"[",
"j",
"]",
".",
"Keyspace",
"}",
")",
"\n\n",
"return",
"stats",
"\n",
"}"
] | // NewVSchemaStats returns a new VSchemaStats from a VSchema. | [
"NewVSchemaStats",
"returns",
"a",
"new",
"VSchemaStats",
"from",
"a",
"VSchema",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vschema_stats.go#L44-L68 | train |
vitessio/vitess | go/vt/vtgate/engine/ordered_aggregate.go | MarshalJSON | func (code AggregateOpcode) MarshalJSON() ([]byte, error) {
return ([]byte)(fmt.Sprintf("\"%s\"", code.String())), nil
} | go | func (code AggregateOpcode) MarshalJSON() ([]byte, error) {
return ([]byte)(fmt.Sprintf("\"%s\"", code.String())), nil
} | [
"func",
"(",
"code",
"AggregateOpcode",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"(",
"[",
"]",
"byte",
")",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
",",
"code",
".",
"String",
"(",
")",
")",
")",
",",
"nil",
"\n",
"}"
] | // MarshalJSON serializes the AggregateOpcode as a JSON string.
// It's used for testing and diagnostics. | [
"MarshalJSON",
"serializes",
"the",
"AggregateOpcode",
"as",
"a",
"JSON",
"string",
".",
"It",
"s",
"used",
"for",
"testing",
"and",
"diagnostics",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/engine/ordered_aggregate.go#L90-L92 | train |
vitessio/vitess | go/vt/vtgate/engine/ordered_aggregate.go | Execute | func (oa *OrderedAggregate) Execute(vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool) (*sqltypes.Result, error) {
qr, err := oa.execute(vcursor, bindVars, wantfields)
if err != nil {
return nil, err
}
return qr.Truncate(oa.TruncateColumnCount), nil
} | go | func (oa *OrderedAggregate) Execute(vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool) (*sqltypes.Result, error) {
qr, err := oa.execute(vcursor, bindVars, wantfields)
if err != nil {
return nil, err
}
return qr.Truncate(oa.TruncateColumnCount), nil
} | [
"func",
"(",
"oa",
"*",
"OrderedAggregate",
")",
"Execute",
"(",
"vcursor",
"VCursor",
",",
"bindVars",
"map",
"[",
"string",
"]",
"*",
"querypb",
".",
"BindVariable",
",",
"wantfields",
"bool",
")",
"(",
"*",
"sqltypes",
".",
"Result",
",",
"error",
")",
"{",
"qr",
",",
"err",
":=",
"oa",
".",
"execute",
"(",
"vcursor",
",",
"bindVars",
",",
"wantfields",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"qr",
".",
"Truncate",
"(",
"oa",
".",
"TruncateColumnCount",
")",
",",
"nil",
"\n",
"}"
] | // Execute is a Primitive function. | [
"Execute",
"is",
"a",
"Primitive",
"function",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/engine/ordered_aggregate.go#L100-L106 | train |
vitessio/vitess | go/vt/vtgate/engine/ordered_aggregate.go | StreamExecute | func (oa *OrderedAggregate) StreamExecute(vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool, callback func(*sqltypes.Result) error) error {
var current []sqltypes.Value
var fields []*querypb.Field
cb := func(qr *sqltypes.Result) error {
return callback(qr.Truncate(oa.TruncateColumnCount))
}
err := oa.Input.StreamExecute(vcursor, bindVars, wantfields, func(qr *sqltypes.Result) error {
if len(qr.Fields) != 0 {
fields = qr.Fields
if err := cb(&sqltypes.Result{Fields: fields}); err != nil {
return err
}
}
// This code is similar to the one in Execute.
for _, row := range qr.Rows {
if current == nil {
current = row
continue
}
equal, err := oa.keysEqual(current, row)
if err != nil {
return err
}
if equal {
current, err = oa.merge(fields, current, row)
if err != nil {
return err
}
continue
}
if err := cb(&sqltypes.Result{Rows: [][]sqltypes.Value{current}}); err != nil {
return err
}
current = row
}
return nil
})
if err != nil {
return err
}
if current != nil {
if err := cb(&sqltypes.Result{Rows: [][]sqltypes.Value{current}}); err != nil {
return err
}
}
return nil
} | go | func (oa *OrderedAggregate) StreamExecute(vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool, callback func(*sqltypes.Result) error) error {
var current []sqltypes.Value
var fields []*querypb.Field
cb := func(qr *sqltypes.Result) error {
return callback(qr.Truncate(oa.TruncateColumnCount))
}
err := oa.Input.StreamExecute(vcursor, bindVars, wantfields, func(qr *sqltypes.Result) error {
if len(qr.Fields) != 0 {
fields = qr.Fields
if err := cb(&sqltypes.Result{Fields: fields}); err != nil {
return err
}
}
// This code is similar to the one in Execute.
for _, row := range qr.Rows {
if current == nil {
current = row
continue
}
equal, err := oa.keysEqual(current, row)
if err != nil {
return err
}
if equal {
current, err = oa.merge(fields, current, row)
if err != nil {
return err
}
continue
}
if err := cb(&sqltypes.Result{Rows: [][]sqltypes.Value{current}}); err != nil {
return err
}
current = row
}
return nil
})
if err != nil {
return err
}
if current != nil {
if err := cb(&sqltypes.Result{Rows: [][]sqltypes.Value{current}}); err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"oa",
"*",
"OrderedAggregate",
")",
"StreamExecute",
"(",
"vcursor",
"VCursor",
",",
"bindVars",
"map",
"[",
"string",
"]",
"*",
"querypb",
".",
"BindVariable",
",",
"wantfields",
"bool",
",",
"callback",
"func",
"(",
"*",
"sqltypes",
".",
"Result",
")",
"error",
")",
"error",
"{",
"var",
"current",
"[",
"]",
"sqltypes",
".",
"Value",
"\n",
"var",
"fields",
"[",
"]",
"*",
"querypb",
".",
"Field",
"\n\n",
"cb",
":=",
"func",
"(",
"qr",
"*",
"sqltypes",
".",
"Result",
")",
"error",
"{",
"return",
"callback",
"(",
"qr",
".",
"Truncate",
"(",
"oa",
".",
"TruncateColumnCount",
")",
")",
"\n",
"}",
"\n\n",
"err",
":=",
"oa",
".",
"Input",
".",
"StreamExecute",
"(",
"vcursor",
",",
"bindVars",
",",
"wantfields",
",",
"func",
"(",
"qr",
"*",
"sqltypes",
".",
"Result",
")",
"error",
"{",
"if",
"len",
"(",
"qr",
".",
"Fields",
")",
"!=",
"0",
"{",
"fields",
"=",
"qr",
".",
"Fields",
"\n",
"if",
"err",
":=",
"cb",
"(",
"&",
"sqltypes",
".",
"Result",
"{",
"Fields",
":",
"fields",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"// This code is similar to the one in Execute.",
"for",
"_",
",",
"row",
":=",
"range",
"qr",
".",
"Rows",
"{",
"if",
"current",
"==",
"nil",
"{",
"current",
"=",
"row",
"\n",
"continue",
"\n",
"}",
"\n\n",
"equal",
",",
"err",
":=",
"oa",
".",
"keysEqual",
"(",
"current",
",",
"row",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"equal",
"{",
"current",
",",
"err",
"=",
"oa",
".",
"merge",
"(",
"fields",
",",
"current",
",",
"row",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"err",
":=",
"cb",
"(",
"&",
"sqltypes",
".",
"Result",
"{",
"Rows",
":",
"[",
"]",
"[",
"]",
"sqltypes",
".",
"Value",
"{",
"current",
"}",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"current",
"=",
"row",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"current",
"!=",
"nil",
"{",
"if",
"err",
":=",
"cb",
"(",
"&",
"sqltypes",
".",
"Result",
"{",
"Rows",
":",
"[",
"]",
"[",
"]",
"sqltypes",
".",
"Value",
"{",
"current",
"}",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // StreamExecute is a Primitive function. | [
"StreamExecute",
"is",
"a",
"Primitive",
"function",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/engine/ordered_aggregate.go#L149-L200 | train |
vitessio/vitess | go/vt/vtgate/engine/ordered_aggregate.go | GetFields | func (oa *OrderedAggregate) GetFields(vcursor VCursor, bindVars map[string]*querypb.BindVariable) (*sqltypes.Result, error) {
qr, err := oa.Input.GetFields(vcursor, bindVars)
if err != nil {
return nil, err
}
return qr.Truncate(oa.TruncateColumnCount), nil
} | go | func (oa *OrderedAggregate) GetFields(vcursor VCursor, bindVars map[string]*querypb.BindVariable) (*sqltypes.Result, error) {
qr, err := oa.Input.GetFields(vcursor, bindVars)
if err != nil {
return nil, err
}
return qr.Truncate(oa.TruncateColumnCount), nil
} | [
"func",
"(",
"oa",
"*",
"OrderedAggregate",
")",
"GetFields",
"(",
"vcursor",
"VCursor",
",",
"bindVars",
"map",
"[",
"string",
"]",
"*",
"querypb",
".",
"BindVariable",
")",
"(",
"*",
"sqltypes",
".",
"Result",
",",
"error",
")",
"{",
"qr",
",",
"err",
":=",
"oa",
".",
"Input",
".",
"GetFields",
"(",
"vcursor",
",",
"bindVars",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"qr",
".",
"Truncate",
"(",
"oa",
".",
"TruncateColumnCount",
")",
",",
"nil",
"\n",
"}"
] | // GetFields is a Primitive function. | [
"GetFields",
"is",
"a",
"Primitive",
"function",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/engine/ordered_aggregate.go#L203-L209 | train |
vitessio/vitess | go/vt/vtgate/vindexes/binary.go | NewBinary | func NewBinary(name string, _ map[string]string) (Vindex, error) {
return &Binary{name: name}, nil
} | go | func NewBinary(name string, _ map[string]string) (Vindex, error) {
return &Binary{name: name}, nil
} | [
"func",
"NewBinary",
"(",
"name",
"string",
",",
"_",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"Vindex",
",",
"error",
")",
"{",
"return",
"&",
"Binary",
"{",
"name",
":",
"name",
"}",
",",
"nil",
"\n",
"}"
] | // NewBinary creates a new Binary. | [
"NewBinary",
"creates",
"a",
"new",
"Binary",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtgate/vindexes/binary.go#L38-L40 | train |
vitessio/vitess | go/vt/topo/topoproto/srvkeyspace.go | SrvKeyspaceGetPartition | func SrvKeyspaceGetPartition(sk *topodatapb.SrvKeyspace, tabletType topodatapb.TabletType) *topodatapb.SrvKeyspace_KeyspacePartition {
for _, p := range sk.Partitions {
if p.ServedType == tabletType {
return p
}
}
return nil
} | go | func SrvKeyspaceGetPartition(sk *topodatapb.SrvKeyspace, tabletType topodatapb.TabletType) *topodatapb.SrvKeyspace_KeyspacePartition {
for _, p := range sk.Partitions {
if p.ServedType == tabletType {
return p
}
}
return nil
} | [
"func",
"SrvKeyspaceGetPartition",
"(",
"sk",
"*",
"topodatapb",
".",
"SrvKeyspace",
",",
"tabletType",
"topodatapb",
".",
"TabletType",
")",
"*",
"topodatapb",
".",
"SrvKeyspace_KeyspacePartition",
"{",
"for",
"_",
",",
"p",
":=",
"range",
"sk",
".",
"Partitions",
"{",
"if",
"p",
".",
"ServedType",
"==",
"tabletType",
"{",
"return",
"p",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // SrvKeyspaceGetPartition returns a Partition for the given tablet type,
// or nil if it's not there. | [
"SrvKeyspaceGetPartition",
"returns",
"a",
"Partition",
"for",
"the",
"given",
"tablet",
"type",
"or",
"nil",
"if",
"it",
"s",
"not",
"there",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/topo/topoproto/srvkeyspace.go#L53-L60 | train |
vitessio/vitess | go/vt/sqlparser/normalizer.go | Normalize | func Normalize(stmt Statement, bindVars map[string]*querypb.BindVariable, prefix string) {
nz := newNormalizer(stmt, bindVars, prefix)
_ = Walk(nz.WalkStatement, stmt)
} | go | func Normalize(stmt Statement, bindVars map[string]*querypb.BindVariable, prefix string) {
nz := newNormalizer(stmt, bindVars, prefix)
_ = Walk(nz.WalkStatement, stmt)
} | [
"func",
"Normalize",
"(",
"stmt",
"Statement",
",",
"bindVars",
"map",
"[",
"string",
"]",
"*",
"querypb",
".",
"BindVariable",
",",
"prefix",
"string",
")",
"{",
"nz",
":=",
"newNormalizer",
"(",
"stmt",
",",
"bindVars",
",",
"prefix",
")",
"\n",
"_",
"=",
"Walk",
"(",
"nz",
".",
"WalkStatement",
",",
"stmt",
")",
"\n",
"}"
] | // Normalize changes the statement to use bind values, and
// updates the bind vars to those values. The supplied prefix
// is used to generate the bind var names. The function ensures
// that there are no collisions with existing bind vars.
// Within Select constructs, bind vars are deduped. This allows
// us to identify vindex equality. Otherwise, every value is
// treated as distinct. | [
"Normalize",
"changes",
"the",
"statement",
"to",
"use",
"bind",
"values",
"and",
"updates",
"the",
"bind",
"vars",
"to",
"those",
"values",
".",
"The",
"supplied",
"prefix",
"is",
"used",
"to",
"generate",
"the",
"bind",
"var",
"names",
".",
"The",
"function",
"ensures",
"that",
"there",
"are",
"no",
"collisions",
"with",
"existing",
"bind",
"vars",
".",
"Within",
"Select",
"constructs",
"bind",
"vars",
"are",
"deduped",
".",
"This",
"allows",
"us",
"to",
"identify",
"vindex",
"equality",
".",
"Otherwise",
"every",
"value",
"is",
"treated",
"as",
"distinct",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/normalizer.go#L34-L37 | train |
vitessio/vitess | go/vt/sqlparser/normalizer.go | WalkSelect | func (nz *normalizer) WalkSelect(node SQLNode) (bool, error) {
switch node := node.(type) {
case *SQLVal:
nz.convertSQLValDedup(node)
case *ComparisonExpr:
nz.convertComparison(node)
case *ColName, TableName:
// Common node types that never contain SQLVals or ListArgs but create a lot of object
// allocations.
return false, nil
case OrderBy, GroupBy:
// do not make a bind var for order by column_position
return false, nil
}
return true, nil
} | go | func (nz *normalizer) WalkSelect(node SQLNode) (bool, error) {
switch node := node.(type) {
case *SQLVal:
nz.convertSQLValDedup(node)
case *ComparisonExpr:
nz.convertComparison(node)
case *ColName, TableName:
// Common node types that never contain SQLVals or ListArgs but create a lot of object
// allocations.
return false, nil
case OrderBy, GroupBy:
// do not make a bind var for order by column_position
return false, nil
}
return true, nil
} | [
"func",
"(",
"nz",
"*",
"normalizer",
")",
"WalkSelect",
"(",
"node",
"SQLNode",
")",
"(",
"bool",
",",
"error",
")",
"{",
"switch",
"node",
":=",
"node",
".",
"(",
"type",
")",
"{",
"case",
"*",
"SQLVal",
":",
"nz",
".",
"convertSQLValDedup",
"(",
"node",
")",
"\n",
"case",
"*",
"ComparisonExpr",
":",
"nz",
".",
"convertComparison",
"(",
"node",
")",
"\n",
"case",
"*",
"ColName",
",",
"TableName",
":",
"// Common node types that never contain SQLVals or ListArgs but create a lot of object",
"// allocations.",
"return",
"false",
",",
"nil",
"\n",
"case",
"OrderBy",
",",
"GroupBy",
":",
"// do not make a bind var for order by column_position",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"return",
"true",
",",
"nil",
"\n",
"}"
] | // WalkSelect normalizes the AST in Select mode. | [
"WalkSelect",
"normalizes",
"the",
"AST",
"in",
"Select",
"mode",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/normalizer.go#L81-L96 | train |
vitessio/vitess | go/vt/sqlparser/normalizer.go | convertSQLVal | func (nz *normalizer) convertSQLVal(node *SQLVal) {
bval := nz.sqlToBindvar(node)
if bval == nil {
return
}
bvname := nz.newName()
nz.bindVars[bvname] = bval
node.Type = ValArg
node.Val = append([]byte(":"), bvname...)
} | go | func (nz *normalizer) convertSQLVal(node *SQLVal) {
bval := nz.sqlToBindvar(node)
if bval == nil {
return
}
bvname := nz.newName()
nz.bindVars[bvname] = bval
node.Type = ValArg
node.Val = append([]byte(":"), bvname...)
} | [
"func",
"(",
"nz",
"*",
"normalizer",
")",
"convertSQLVal",
"(",
"node",
"*",
"SQLVal",
")",
"{",
"bval",
":=",
"nz",
".",
"sqlToBindvar",
"(",
"node",
")",
"\n",
"if",
"bval",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"bvname",
":=",
"nz",
".",
"newName",
"(",
")",
"\n",
"nz",
".",
"bindVars",
"[",
"bvname",
"]",
"=",
"bval",
"\n\n",
"node",
".",
"Type",
"=",
"ValArg",
"\n",
"node",
".",
"Val",
"=",
"append",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
",",
"bvname",
"...",
")",
"\n",
"}"
] | // convertSQLVal converts an SQLVal without the dedup. | [
"convertSQLVal",
"converts",
"an",
"SQLVal",
"without",
"the",
"dedup",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/normalizer.go#L138-L149 | train |
vitessio/vitess | go/vt/sqlparser/normalizer.go | convertComparison | func (nz *normalizer) convertComparison(node *ComparisonExpr) {
if node.Operator != InStr && node.Operator != NotInStr {
return
}
tupleVals, ok := node.Right.(ValTuple)
if !ok {
return
}
// The RHS is a tuple of values.
// Make a list bindvar.
bvals := &querypb.BindVariable{
Type: querypb.Type_TUPLE,
}
for _, val := range tupleVals {
bval := nz.sqlToBindvar(val)
if bval == nil {
return
}
bvals.Values = append(bvals.Values, &querypb.Value{
Type: bval.Type,
Value: bval.Value,
})
}
bvname := nz.newName()
nz.bindVars[bvname] = bvals
// Modify RHS to be a list bindvar.
node.Right = ListArg(append([]byte("::"), bvname...))
} | go | func (nz *normalizer) convertComparison(node *ComparisonExpr) {
if node.Operator != InStr && node.Operator != NotInStr {
return
}
tupleVals, ok := node.Right.(ValTuple)
if !ok {
return
}
// The RHS is a tuple of values.
// Make a list bindvar.
bvals := &querypb.BindVariable{
Type: querypb.Type_TUPLE,
}
for _, val := range tupleVals {
bval := nz.sqlToBindvar(val)
if bval == nil {
return
}
bvals.Values = append(bvals.Values, &querypb.Value{
Type: bval.Type,
Value: bval.Value,
})
}
bvname := nz.newName()
nz.bindVars[bvname] = bvals
// Modify RHS to be a list bindvar.
node.Right = ListArg(append([]byte("::"), bvname...))
} | [
"func",
"(",
"nz",
"*",
"normalizer",
")",
"convertComparison",
"(",
"node",
"*",
"ComparisonExpr",
")",
"{",
"if",
"node",
".",
"Operator",
"!=",
"InStr",
"&&",
"node",
".",
"Operator",
"!=",
"NotInStr",
"{",
"return",
"\n",
"}",
"\n",
"tupleVals",
",",
"ok",
":=",
"node",
".",
"Right",
".",
"(",
"ValTuple",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"// The RHS is a tuple of values.",
"// Make a list bindvar.",
"bvals",
":=",
"&",
"querypb",
".",
"BindVariable",
"{",
"Type",
":",
"querypb",
".",
"Type_TUPLE",
",",
"}",
"\n",
"for",
"_",
",",
"val",
":=",
"range",
"tupleVals",
"{",
"bval",
":=",
"nz",
".",
"sqlToBindvar",
"(",
"val",
")",
"\n",
"if",
"bval",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"bvals",
".",
"Values",
"=",
"append",
"(",
"bvals",
".",
"Values",
",",
"&",
"querypb",
".",
"Value",
"{",
"Type",
":",
"bval",
".",
"Type",
",",
"Value",
":",
"bval",
".",
"Value",
",",
"}",
")",
"\n",
"}",
"\n",
"bvname",
":=",
"nz",
".",
"newName",
"(",
")",
"\n",
"nz",
".",
"bindVars",
"[",
"bvname",
"]",
"=",
"bvals",
"\n",
"// Modify RHS to be a list bindvar.",
"node",
".",
"Right",
"=",
"ListArg",
"(",
"append",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
",",
"bvname",
"...",
")",
")",
"\n",
"}"
] | // convertComparison attempts to convert IN clauses to
// use the list bind var construct. If it fails, it returns
// with no change made. The walk function will then continue
// and iterate on converting each individual value into separate
// bind vars. | [
"convertComparison",
"attempts",
"to",
"convert",
"IN",
"clauses",
"to",
"use",
"the",
"list",
"bind",
"var",
"construct",
".",
"If",
"it",
"fails",
"it",
"returns",
"with",
"no",
"change",
"made",
".",
"The",
"walk",
"function",
"will",
"then",
"continue",
"and",
"iterate",
"on",
"converting",
"each",
"individual",
"value",
"into",
"separate",
"bind",
"vars",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/sqlparser/normalizer.go#L156-L183 | train |
vitessio/vitess | go/mysql/auth_server_none.go | ValidateHash | func (a *AuthServerNone) ValidateHash(salt []byte, user string, authResponse []byte, remoteAddr net.Addr) (Getter, error) {
return &NoneGetter{}, nil
} | go | func (a *AuthServerNone) ValidateHash(salt []byte, user string, authResponse []byte, remoteAddr net.Addr) (Getter, error) {
return &NoneGetter{}, nil
} | [
"func",
"(",
"a",
"*",
"AuthServerNone",
")",
"ValidateHash",
"(",
"salt",
"[",
"]",
"byte",
",",
"user",
"string",
",",
"authResponse",
"[",
"]",
"byte",
",",
"remoteAddr",
"net",
".",
"Addr",
")",
"(",
"Getter",
",",
"error",
")",
"{",
"return",
"&",
"NoneGetter",
"{",
"}",
",",
"nil",
"\n",
"}"
] | // ValidateHash validates hash | [
"ValidateHash",
"validates",
"hash"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/auth_server_none.go#L44-L46 | train |
vitessio/vitess | go/mysql/auth_server_none.go | Negotiate | func (a *AuthServerNone) Negotiate(c *Conn, user string, remotAddr net.Addr) (Getter, error) {
panic("Negotiate should not be called as AuthMethod returned mysql_native_password")
} | go | func (a *AuthServerNone) Negotiate(c *Conn, user string, remotAddr net.Addr) (Getter, error) {
panic("Negotiate should not be called as AuthMethod returned mysql_native_password")
} | [
"func",
"(",
"a",
"*",
"AuthServerNone",
")",
"Negotiate",
"(",
"c",
"*",
"Conn",
",",
"user",
"string",
",",
"remotAddr",
"net",
".",
"Addr",
")",
"(",
"Getter",
",",
"error",
")",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // Negotiate is part of the AuthServer interface.
// It will never be called. | [
"Negotiate",
"is",
"part",
"of",
"the",
"AuthServer",
"interface",
".",
"It",
"will",
"never",
"be",
"called",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/auth_server_none.go#L50-L52 | train |
vitessio/vitess | go/vt/wrangler/split.go | SetSourceShards | func (wr *Wrangler) SetSourceShards(ctx context.Context, keyspace, shard string, sources []*topodatapb.TabletAlias, tables []string) error {
// Read the source tablets.
sourceTablets, err := wr.ts.GetTabletMap(ctx, sources)
if err != nil {
return err
}
// Insert their KeyRange in the SourceShards array.
// We use a linear 0-based id, that matches what worker/split_clone.go
// inserts into _vt.vreplication.
// We want to guarantee sourceShards[i] is using sources[i],
// So iterating over the sourceTablets map would be a bad idea.
sourceShards := make([]*topodatapb.Shard_SourceShard, len(sourceTablets))
for i, alias := range sources {
ti := sourceTablets[topoproto.TabletAliasString(alias)]
sourceShards[i] = &topodatapb.Shard_SourceShard{
Uid: uint32(i),
Keyspace: ti.Keyspace,
Shard: ti.Shard,
KeyRange: ti.KeyRange,
Tables: tables,
}
}
// Update the shard with the new source shards.
_, err = wr.ts.UpdateShardFields(ctx, keyspace, shard, func(si *topo.ShardInfo) error {
// If the shard already has sources, maybe it's already been restored,
// so let's be safe and abort right here.
if len(si.SourceShards) > 0 {
return fmt.Errorf("shard %v/%v already has SourceShards, not overwriting them (full record: %v)", keyspace, shard, *si.Shard)
}
si.SourceShards = sourceShards
return nil
})
return err
} | go | func (wr *Wrangler) SetSourceShards(ctx context.Context, keyspace, shard string, sources []*topodatapb.TabletAlias, tables []string) error {
// Read the source tablets.
sourceTablets, err := wr.ts.GetTabletMap(ctx, sources)
if err != nil {
return err
}
// Insert their KeyRange in the SourceShards array.
// We use a linear 0-based id, that matches what worker/split_clone.go
// inserts into _vt.vreplication.
// We want to guarantee sourceShards[i] is using sources[i],
// So iterating over the sourceTablets map would be a bad idea.
sourceShards := make([]*topodatapb.Shard_SourceShard, len(sourceTablets))
for i, alias := range sources {
ti := sourceTablets[topoproto.TabletAliasString(alias)]
sourceShards[i] = &topodatapb.Shard_SourceShard{
Uid: uint32(i),
Keyspace: ti.Keyspace,
Shard: ti.Shard,
KeyRange: ti.KeyRange,
Tables: tables,
}
}
// Update the shard with the new source shards.
_, err = wr.ts.UpdateShardFields(ctx, keyspace, shard, func(si *topo.ShardInfo) error {
// If the shard already has sources, maybe it's already been restored,
// so let's be safe and abort right here.
if len(si.SourceShards) > 0 {
return fmt.Errorf("shard %v/%v already has SourceShards, not overwriting them (full record: %v)", keyspace, shard, *si.Shard)
}
si.SourceShards = sourceShards
return nil
})
return err
} | [
"func",
"(",
"wr",
"*",
"Wrangler",
")",
"SetSourceShards",
"(",
"ctx",
"context",
".",
"Context",
",",
"keyspace",
",",
"shard",
"string",
",",
"sources",
"[",
"]",
"*",
"topodatapb",
".",
"TabletAlias",
",",
"tables",
"[",
"]",
"string",
")",
"error",
"{",
"// Read the source tablets.",
"sourceTablets",
",",
"err",
":=",
"wr",
".",
"ts",
".",
"GetTabletMap",
"(",
"ctx",
",",
"sources",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Insert their KeyRange in the SourceShards array.",
"// We use a linear 0-based id, that matches what worker/split_clone.go",
"// inserts into _vt.vreplication.",
"// We want to guarantee sourceShards[i] is using sources[i],",
"// So iterating over the sourceTablets map would be a bad idea.",
"sourceShards",
":=",
"make",
"(",
"[",
"]",
"*",
"topodatapb",
".",
"Shard_SourceShard",
",",
"len",
"(",
"sourceTablets",
")",
")",
"\n",
"for",
"i",
",",
"alias",
":=",
"range",
"sources",
"{",
"ti",
":=",
"sourceTablets",
"[",
"topoproto",
".",
"TabletAliasString",
"(",
"alias",
")",
"]",
"\n",
"sourceShards",
"[",
"i",
"]",
"=",
"&",
"topodatapb",
".",
"Shard_SourceShard",
"{",
"Uid",
":",
"uint32",
"(",
"i",
")",
",",
"Keyspace",
":",
"ti",
".",
"Keyspace",
",",
"Shard",
":",
"ti",
".",
"Shard",
",",
"KeyRange",
":",
"ti",
".",
"KeyRange",
",",
"Tables",
":",
"tables",
",",
"}",
"\n",
"}",
"\n\n",
"// Update the shard with the new source shards.",
"_",
",",
"err",
"=",
"wr",
".",
"ts",
".",
"UpdateShardFields",
"(",
"ctx",
",",
"keyspace",
",",
"shard",
",",
"func",
"(",
"si",
"*",
"topo",
".",
"ShardInfo",
")",
"error",
"{",
"// If the shard already has sources, maybe it's already been restored,",
"// so let's be safe and abort right here.",
"if",
"len",
"(",
"si",
".",
"SourceShards",
")",
">",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"keyspace",
",",
"shard",
",",
"*",
"si",
".",
"Shard",
")",
"\n",
"}",
"\n\n",
"si",
".",
"SourceShards",
"=",
"sourceShards",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // SetSourceShards is a utility function to override the SourceShards fields
// on a Shard. | [
"SetSourceShards",
"is",
"a",
"utility",
"function",
"to",
"override",
"the",
"SourceShards",
"fields",
"on",
"a",
"Shard",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/split.go#L42-L78 | train |
vitessio/vitess | go/vt/wrangler/split.go | WaitForFilteredReplication | func (wr *Wrangler) WaitForFilteredReplication(ctx context.Context, keyspace, shard string, maxDelay time.Duration) error {
shardInfo, err := wr.TopoServer().GetShard(ctx, keyspace, shard)
if err != nil {
return err
}
if len(shardInfo.SourceShards) == 0 {
return fmt.Errorf("shard %v/%v has no source shard", keyspace, shard)
}
if !shardInfo.HasMaster() {
return fmt.Errorf("shard %v/%v has no master", keyspace, shard)
}
alias := shardInfo.MasterAlias
tabletInfo, err := wr.TopoServer().GetTablet(ctx, alias)
if err != nil {
return err
}
// Always run an explicit healthcheck first to make sure we don't see any outdated values.
// This is especially true for tests and automation where there is no pause of multiple seconds
// between commands and the periodic healthcheck did not run again yet.
if err := wr.TabletManagerClient().RunHealthCheck(ctx, tabletInfo.Tablet); err != nil {
return fmt.Errorf("failed to run explicit healthcheck on tablet: %v err: %v", tabletInfo, err)
}
conn, err := tabletconn.GetDialer()(tabletInfo.Tablet, grpcclient.FailFast(false))
if err != nil {
return fmt.Errorf("cannot connect to tablet %v: %v", alias, err)
}
var lastSeenDelay time.Duration
err = conn.StreamHealth(ctx, func(shr *querypb.StreamHealthResponse) error {
stats := shr.RealtimeStats
if stats == nil {
return fmt.Errorf("health record does not include RealtimeStats message. tablet: %v health record: %v", alias, shr)
}
if stats.HealthError != "" {
return fmt.Errorf("tablet is not healthy. tablet: %v health record: %v", alias, shr)
}
if stats.BinlogPlayersCount == 0 {
return fmt.Errorf("no filtered replication running on tablet: %v health record: %v", alias, shr)
}
delaySecs := stats.SecondsBehindMasterFilteredReplication
lastSeenDelay = time.Duration(delaySecs) * time.Second
if lastSeenDelay < 0 {
return fmt.Errorf("last seen delay should never be negative. tablet: %v delay: %v", alias, lastSeenDelay)
}
if lastSeenDelay <= maxDelay {
wr.Logger().Printf("Filtered replication on tablet: %v has caught up. Last seen delay: %.1f seconds\n", alias, lastSeenDelay.Seconds())
return io.EOF
}
wr.Logger().Printf("Waiting for filtered replication to catch up on tablet: %v Last seen delay: %.1f seconds\n", alias, lastSeenDelay.Seconds())
return nil
})
if err != nil {
return fmt.Errorf("could not stream health records from tablet: %v err: %v", alias, err)
}
select {
case <-ctx.Done():
return fmt.Errorf("context was done before filtered replication did catch up. Last seen delay: %v context Error: %v", lastSeenDelay, ctx.Err())
default:
}
return nil
} | go | func (wr *Wrangler) WaitForFilteredReplication(ctx context.Context, keyspace, shard string, maxDelay time.Duration) error {
shardInfo, err := wr.TopoServer().GetShard(ctx, keyspace, shard)
if err != nil {
return err
}
if len(shardInfo.SourceShards) == 0 {
return fmt.Errorf("shard %v/%v has no source shard", keyspace, shard)
}
if !shardInfo.HasMaster() {
return fmt.Errorf("shard %v/%v has no master", keyspace, shard)
}
alias := shardInfo.MasterAlias
tabletInfo, err := wr.TopoServer().GetTablet(ctx, alias)
if err != nil {
return err
}
// Always run an explicit healthcheck first to make sure we don't see any outdated values.
// This is especially true for tests and automation where there is no pause of multiple seconds
// between commands and the periodic healthcheck did not run again yet.
if err := wr.TabletManagerClient().RunHealthCheck(ctx, tabletInfo.Tablet); err != nil {
return fmt.Errorf("failed to run explicit healthcheck on tablet: %v err: %v", tabletInfo, err)
}
conn, err := tabletconn.GetDialer()(tabletInfo.Tablet, grpcclient.FailFast(false))
if err != nil {
return fmt.Errorf("cannot connect to tablet %v: %v", alias, err)
}
var lastSeenDelay time.Duration
err = conn.StreamHealth(ctx, func(shr *querypb.StreamHealthResponse) error {
stats := shr.RealtimeStats
if stats == nil {
return fmt.Errorf("health record does not include RealtimeStats message. tablet: %v health record: %v", alias, shr)
}
if stats.HealthError != "" {
return fmt.Errorf("tablet is not healthy. tablet: %v health record: %v", alias, shr)
}
if stats.BinlogPlayersCount == 0 {
return fmt.Errorf("no filtered replication running on tablet: %v health record: %v", alias, shr)
}
delaySecs := stats.SecondsBehindMasterFilteredReplication
lastSeenDelay = time.Duration(delaySecs) * time.Second
if lastSeenDelay < 0 {
return fmt.Errorf("last seen delay should never be negative. tablet: %v delay: %v", alias, lastSeenDelay)
}
if lastSeenDelay <= maxDelay {
wr.Logger().Printf("Filtered replication on tablet: %v has caught up. Last seen delay: %.1f seconds\n", alias, lastSeenDelay.Seconds())
return io.EOF
}
wr.Logger().Printf("Waiting for filtered replication to catch up on tablet: %v Last seen delay: %.1f seconds\n", alias, lastSeenDelay.Seconds())
return nil
})
if err != nil {
return fmt.Errorf("could not stream health records from tablet: %v err: %v", alias, err)
}
select {
case <-ctx.Done():
return fmt.Errorf("context was done before filtered replication did catch up. Last seen delay: %v context Error: %v", lastSeenDelay, ctx.Err())
default:
}
return nil
} | [
"func",
"(",
"wr",
"*",
"Wrangler",
")",
"WaitForFilteredReplication",
"(",
"ctx",
"context",
".",
"Context",
",",
"keyspace",
",",
"shard",
"string",
",",
"maxDelay",
"time",
".",
"Duration",
")",
"error",
"{",
"shardInfo",
",",
"err",
":=",
"wr",
".",
"TopoServer",
"(",
")",
".",
"GetShard",
"(",
"ctx",
",",
"keyspace",
",",
"shard",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"shardInfo",
".",
"SourceShards",
")",
"==",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"keyspace",
",",
"shard",
")",
"\n",
"}",
"\n",
"if",
"!",
"shardInfo",
".",
"HasMaster",
"(",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"keyspace",
",",
"shard",
")",
"\n",
"}",
"\n",
"alias",
":=",
"shardInfo",
".",
"MasterAlias",
"\n",
"tabletInfo",
",",
"err",
":=",
"wr",
".",
"TopoServer",
"(",
")",
".",
"GetTablet",
"(",
"ctx",
",",
"alias",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Always run an explicit healthcheck first to make sure we don't see any outdated values.",
"// This is especially true for tests and automation where there is no pause of multiple seconds",
"// between commands and the periodic healthcheck did not run again yet.",
"if",
"err",
":=",
"wr",
".",
"TabletManagerClient",
"(",
")",
".",
"RunHealthCheck",
"(",
"ctx",
",",
"tabletInfo",
".",
"Tablet",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"tabletInfo",
",",
"err",
")",
"\n",
"}",
"\n\n",
"conn",
",",
"err",
":=",
"tabletconn",
".",
"GetDialer",
"(",
")",
"(",
"tabletInfo",
".",
"Tablet",
",",
"grpcclient",
".",
"FailFast",
"(",
"false",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"alias",
",",
"err",
")",
"\n",
"}",
"\n\n",
"var",
"lastSeenDelay",
"time",
".",
"Duration",
"\n",
"err",
"=",
"conn",
".",
"StreamHealth",
"(",
"ctx",
",",
"func",
"(",
"shr",
"*",
"querypb",
".",
"StreamHealthResponse",
")",
"error",
"{",
"stats",
":=",
"shr",
".",
"RealtimeStats",
"\n",
"if",
"stats",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"alias",
",",
"shr",
")",
"\n",
"}",
"\n",
"if",
"stats",
".",
"HealthError",
"!=",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"alias",
",",
"shr",
")",
"\n",
"}",
"\n",
"if",
"stats",
".",
"BinlogPlayersCount",
"==",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"alias",
",",
"shr",
")",
"\n",
"}",
"\n\n",
"delaySecs",
":=",
"stats",
".",
"SecondsBehindMasterFilteredReplication",
"\n",
"lastSeenDelay",
"=",
"time",
".",
"Duration",
"(",
"delaySecs",
")",
"*",
"time",
".",
"Second",
"\n",
"if",
"lastSeenDelay",
"<",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"alias",
",",
"lastSeenDelay",
")",
"\n",
"}",
"\n",
"if",
"lastSeenDelay",
"<=",
"maxDelay",
"{",
"wr",
".",
"Logger",
"(",
")",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"alias",
",",
"lastSeenDelay",
".",
"Seconds",
"(",
")",
")",
"\n",
"return",
"io",
".",
"EOF",
"\n",
"}",
"\n",
"wr",
".",
"Logger",
"(",
")",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"alias",
",",
"lastSeenDelay",
".",
"Seconds",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"alias",
",",
"err",
")",
"\n",
"}",
"\n\n",
"select",
"{",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"lastSeenDelay",
",",
"ctx",
".",
"Err",
"(",
")",
")",
"\n",
"default",
":",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // WaitForFilteredReplication will wait until the Filtered Replication process has finished. | [
"WaitForFilteredReplication",
"will",
"wait",
"until",
"the",
"Filtered",
"Replication",
"process",
"has",
"finished",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/split.go#L81-L145 | train |
vitessio/vitess | go/vt/vtctl/grpcvtctlclient/client.go | ExecuteVtctlCommand | func (client *gRPCVtctlClient) ExecuteVtctlCommand(ctx context.Context, args []string, actionTimeout time.Duration) (logutil.EventStream, error) {
query := &vtctldatapb.ExecuteVtctlCommandRequest{
Args: args,
ActionTimeout: int64(actionTimeout.Nanoseconds()),
}
stream, err := client.c.ExecuteVtctlCommand(ctx, query)
if err != nil {
return nil, err
}
return &eventStreamAdapter{stream}, nil
} | go | func (client *gRPCVtctlClient) ExecuteVtctlCommand(ctx context.Context, args []string, actionTimeout time.Duration) (logutil.EventStream, error) {
query := &vtctldatapb.ExecuteVtctlCommandRequest{
Args: args,
ActionTimeout: int64(actionTimeout.Nanoseconds()),
}
stream, err := client.c.ExecuteVtctlCommand(ctx, query)
if err != nil {
return nil, err
}
return &eventStreamAdapter{stream}, nil
} | [
"func",
"(",
"client",
"*",
"gRPCVtctlClient",
")",
"ExecuteVtctlCommand",
"(",
"ctx",
"context",
".",
"Context",
",",
"args",
"[",
"]",
"string",
",",
"actionTimeout",
"time",
".",
"Duration",
")",
"(",
"logutil",
".",
"EventStream",
",",
"error",
")",
"{",
"query",
":=",
"&",
"vtctldatapb",
".",
"ExecuteVtctlCommandRequest",
"{",
"Args",
":",
"args",
",",
"ActionTimeout",
":",
"int64",
"(",
"actionTimeout",
".",
"Nanoseconds",
"(",
")",
")",
",",
"}",
"\n\n",
"stream",
",",
"err",
":=",
"client",
".",
"c",
".",
"ExecuteVtctlCommand",
"(",
"ctx",
",",
"query",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"eventStreamAdapter",
"{",
"stream",
"}",
",",
"nil",
"\n",
"}"
] | // ExecuteVtctlCommand is part of the VtctlClient interface | [
"ExecuteVtctlCommand",
"is",
"part",
"of",
"the",
"VtctlClient",
"interface"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vtctl/grpcvtctlclient/client.go#L78-L89 | train |
vitessio/vitess | go/netutil/netutil.go | JoinHostPort | func JoinHostPort(host string, port int32) string {
return net.JoinHostPort(host, strconv.FormatInt(int64(port), 10))
} | go | func JoinHostPort(host string, port int32) string {
return net.JoinHostPort(host, strconv.FormatInt(int64(port), 10))
} | [
"func",
"JoinHostPort",
"(",
"host",
"string",
",",
"port",
"int32",
")",
"string",
"{",
"return",
"net",
".",
"JoinHostPort",
"(",
"host",
",",
"strconv",
".",
"FormatInt",
"(",
"int64",
"(",
"port",
")",
",",
"10",
")",
")",
"\n",
"}"
] | // JoinHostPort is an extension to net.JoinHostPort that also formats the
// integer port. | [
"JoinHostPort",
"is",
"an",
"extension",
"to",
"net",
".",
"JoinHostPort",
"that",
"also",
"formats",
"the",
"integer",
"port",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/netutil/netutil.go#L114-L116 | train |
vitessio/vitess | go/netutil/netutil.go | FullyQualifiedHostname | func FullyQualifiedHostname() (string, error) {
// The machine hostname (which is also returned by os.Hostname()) may not be
// set to the FQDN, but only the first part of it e.g. "localhost" instead of
// "localhost.localdomain".
// To get the full FQDN, we do the following:
// 1. Get the machine hostname. Example: localhost
hostname, err := os.Hostname()
if err != nil {
return "", fmt.Errorf("FullyQualifiedHostname: failed to retrieve the hostname of this machine: %v", err)
}
// 2. Look up the IP address for that hostname. Example: 127.0.0.1
ips, err := net.LookupHost(hostname)
if err != nil {
return "", fmt.Errorf("FullyQualifiedHostname: failed to lookup the IP of this machine's hostname (%v): %v", hostname, err)
}
if len(ips) == 0 {
return "", fmt.Errorf("FullyQualifiedHostname: lookup of the IP of this machine's hostname (%v) did not return any IP address", hostname)
}
// If multiple IPs are returned, we only look at the first one.
localIP := ips[0]
// 3. Reverse lookup the IP. Example: localhost.localdomain
resolvedHostnames, err := net.LookupAddr(localIP)
if err != nil {
return "", fmt.Errorf("FullyQualifiedHostname: failed to reverse lookup this machine's local IP (%v): %v", localIP, err)
}
if len(resolvedHostnames) == 0 {
return "", fmt.Errorf("FullyQualifiedHostname: reverse lookup of this machine's local IP (%v) did not return any hostnames", localIP)
}
// If multiple hostnames are found, we return only the first one.
// If multiple hostnames are listed e.g. in an entry in the /etc/hosts file,
// the current Go implementation returns them in that order.
// Example for an /etc/hosts entry:
// 127.0.0.1 localhost.localdomain localhost
// If the FQDN isn't returned by this function, check the order in the entry
// in your /etc/hosts file.
return strings.TrimRight(resolvedHostnames[0], "."), nil
} | go | func FullyQualifiedHostname() (string, error) {
// The machine hostname (which is also returned by os.Hostname()) may not be
// set to the FQDN, but only the first part of it e.g. "localhost" instead of
// "localhost.localdomain".
// To get the full FQDN, we do the following:
// 1. Get the machine hostname. Example: localhost
hostname, err := os.Hostname()
if err != nil {
return "", fmt.Errorf("FullyQualifiedHostname: failed to retrieve the hostname of this machine: %v", err)
}
// 2. Look up the IP address for that hostname. Example: 127.0.0.1
ips, err := net.LookupHost(hostname)
if err != nil {
return "", fmt.Errorf("FullyQualifiedHostname: failed to lookup the IP of this machine's hostname (%v): %v", hostname, err)
}
if len(ips) == 0 {
return "", fmt.Errorf("FullyQualifiedHostname: lookup of the IP of this machine's hostname (%v) did not return any IP address", hostname)
}
// If multiple IPs are returned, we only look at the first one.
localIP := ips[0]
// 3. Reverse lookup the IP. Example: localhost.localdomain
resolvedHostnames, err := net.LookupAddr(localIP)
if err != nil {
return "", fmt.Errorf("FullyQualifiedHostname: failed to reverse lookup this machine's local IP (%v): %v", localIP, err)
}
if len(resolvedHostnames) == 0 {
return "", fmt.Errorf("FullyQualifiedHostname: reverse lookup of this machine's local IP (%v) did not return any hostnames", localIP)
}
// If multiple hostnames are found, we return only the first one.
// If multiple hostnames are listed e.g. in an entry in the /etc/hosts file,
// the current Go implementation returns them in that order.
// Example for an /etc/hosts entry:
// 127.0.0.1 localhost.localdomain localhost
// If the FQDN isn't returned by this function, check the order in the entry
// in your /etc/hosts file.
return strings.TrimRight(resolvedHostnames[0], "."), nil
} | [
"func",
"FullyQualifiedHostname",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"// The machine hostname (which is also returned by os.Hostname()) may not be",
"// set to the FQDN, but only the first part of it e.g. \"localhost\" instead of",
"// \"localhost.localdomain\".",
"// To get the full FQDN, we do the following:",
"// 1. Get the machine hostname. Example: localhost",
"hostname",
",",
"err",
":=",
"os",
".",
"Hostname",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// 2. Look up the IP address for that hostname. Example: 127.0.0.1",
"ips",
",",
"err",
":=",
"net",
".",
"LookupHost",
"(",
"hostname",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"hostname",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"ips",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"hostname",
")",
"\n",
"}",
"\n",
"// If multiple IPs are returned, we only look at the first one.",
"localIP",
":=",
"ips",
"[",
"0",
"]",
"\n\n",
"// 3. Reverse lookup the IP. Example: localhost.localdomain",
"resolvedHostnames",
",",
"err",
":=",
"net",
".",
"LookupAddr",
"(",
"localIP",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"localIP",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"resolvedHostnames",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"localIP",
")",
"\n",
"}",
"\n",
"// If multiple hostnames are found, we return only the first one.",
"// If multiple hostnames are listed e.g. in an entry in the /etc/hosts file,",
"// the current Go implementation returns them in that order.",
"// Example for an /etc/hosts entry:",
"// 127.0.0.1\tlocalhost.localdomain localhost",
"// If the FQDN isn't returned by this function, check the order in the entry",
"// in your /etc/hosts file.",
"return",
"strings",
".",
"TrimRight",
"(",
"resolvedHostnames",
"[",
"0",
"]",
",",
"\"",
"\"",
")",
",",
"nil",
"\n",
"}"
] | // FullyQualifiedHostname returns the FQDN of the machine. | [
"FullyQualifiedHostname",
"returns",
"the",
"FQDN",
"of",
"the",
"machine",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/netutil/netutil.go#L119-L158 | train |
vitessio/vitess | go/netutil/netutil.go | FullyQualifiedHostnameOrPanic | func FullyQualifiedHostnameOrPanic() string {
hostname, err := FullyQualifiedHostname()
if err != nil {
panic(err)
}
return hostname
} | go | func FullyQualifiedHostnameOrPanic() string {
hostname, err := FullyQualifiedHostname()
if err != nil {
panic(err)
}
return hostname
} | [
"func",
"FullyQualifiedHostnameOrPanic",
"(",
")",
"string",
"{",
"hostname",
",",
"err",
":=",
"FullyQualifiedHostname",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"hostname",
"\n",
"}"
] | // FullyQualifiedHostnameOrPanic is the same as FullyQualifiedHostname
// but panics in case of an error. | [
"FullyQualifiedHostnameOrPanic",
"is",
"the",
"same",
"as",
"FullyQualifiedHostname",
"but",
"panics",
"in",
"case",
"of",
"an",
"error",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/netutil/netutil.go#L162-L168 | train |
vitessio/vitess | go/vt/vttablet/tabletconn/tablet_conn.go | RegisterDialer | func RegisterDialer(name string, dialer TabletDialer) {
if _, ok := dialers[name]; ok {
log.Fatalf("Dialer %s already exists", name)
}
dialers[name] = dialer
} | go | func RegisterDialer(name string, dialer TabletDialer) {
if _, ok := dialers[name]; ok {
log.Fatalf("Dialer %s already exists", name)
}
dialers[name] = dialer
} | [
"func",
"RegisterDialer",
"(",
"name",
"string",
",",
"dialer",
"TabletDialer",
")",
"{",
"if",
"_",
",",
"ok",
":=",
"dialers",
"[",
"name",
"]",
";",
"ok",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"dialers",
"[",
"name",
"]",
"=",
"dialer",
"\n",
"}"
] | // RegisterDialer is meant to be used by TabletDialer implementations
// to self register. | [
"RegisterDialer",
"is",
"meant",
"to",
"be",
"used",
"by",
"TabletDialer",
"implementations",
"to",
"self",
"register",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletconn/tablet_conn.go#L59-L64 | train |
vitessio/vitess | go/vt/vttablet/tabletconn/tablet_conn.go | GetDialer | func GetDialer() TabletDialer {
td, ok := dialers[*TabletProtocol]
if !ok {
log.Exitf("No dialer registered for tablet protocol %s", *TabletProtocol)
}
return td
} | go | func GetDialer() TabletDialer {
td, ok := dialers[*TabletProtocol]
if !ok {
log.Exitf("No dialer registered for tablet protocol %s", *TabletProtocol)
}
return td
} | [
"func",
"GetDialer",
"(",
")",
"TabletDialer",
"{",
"td",
",",
"ok",
":=",
"dialers",
"[",
"*",
"TabletProtocol",
"]",
"\n",
"if",
"!",
"ok",
"{",
"log",
".",
"Exitf",
"(",
"\"",
"\"",
",",
"*",
"TabletProtocol",
")",
"\n",
"}",
"\n",
"return",
"td",
"\n",
"}"
] | // GetDialer returns the dialer to use, described by the command line flag | [
"GetDialer",
"returns",
"the",
"dialer",
"to",
"use",
"described",
"by",
"the",
"command",
"line",
"flag"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/vttablet/tabletconn/tablet_conn.go#L67-L73 | train |
vitessio/vitess | go/vt/worker/instance.go | NewInstance | func NewInstance(ts *topo.Server, cell string, commandDisplayInterval time.Duration) *Instance {
wi := &Instance{topoServer: ts, cell: cell, commandDisplayInterval: commandDisplayInterval}
// Note: setAndStartWorker() also adds a MemoryLogger for the webserver.
wi.wr = wi.CreateWrangler(logutil.NewConsoleLogger())
return wi
} | go | func NewInstance(ts *topo.Server, cell string, commandDisplayInterval time.Duration) *Instance {
wi := &Instance{topoServer: ts, cell: cell, commandDisplayInterval: commandDisplayInterval}
// Note: setAndStartWorker() also adds a MemoryLogger for the webserver.
wi.wr = wi.CreateWrangler(logutil.NewConsoleLogger())
return wi
} | [
"func",
"NewInstance",
"(",
"ts",
"*",
"topo",
".",
"Server",
",",
"cell",
"string",
",",
"commandDisplayInterval",
"time",
".",
"Duration",
")",
"*",
"Instance",
"{",
"wi",
":=",
"&",
"Instance",
"{",
"topoServer",
":",
"ts",
",",
"cell",
":",
"cell",
",",
"commandDisplayInterval",
":",
"commandDisplayInterval",
"}",
"\n",
"// Note: setAndStartWorker() also adds a MemoryLogger for the webserver.",
"wi",
".",
"wr",
"=",
"wi",
".",
"CreateWrangler",
"(",
"logutil",
".",
"NewConsoleLogger",
"(",
")",
")",
"\n",
"return",
"wi",
"\n",
"}"
] | // NewInstance creates a new Instance. | [
"NewInstance",
"creates",
"a",
"new",
"Instance",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/instance.go#L68-L73 | train |
vitessio/vitess | go/vt/worker/instance.go | CreateWrangler | func (wi *Instance) CreateWrangler(logger logutil.Logger) *wrangler.Wrangler {
return wrangler.New(logger, wi.topoServer, tmclient.NewTabletManagerClient())
} | go | func (wi *Instance) CreateWrangler(logger logutil.Logger) *wrangler.Wrangler {
return wrangler.New(logger, wi.topoServer, tmclient.NewTabletManagerClient())
} | [
"func",
"(",
"wi",
"*",
"Instance",
")",
"CreateWrangler",
"(",
"logger",
"logutil",
".",
"Logger",
")",
"*",
"wrangler",
".",
"Wrangler",
"{",
"return",
"wrangler",
".",
"New",
"(",
"logger",
",",
"wi",
".",
"topoServer",
",",
"tmclient",
".",
"NewTabletManagerClient",
"(",
")",
")",
"\n",
"}"
] | // CreateWrangler creates a new wrangler using the instance specific configuration. | [
"CreateWrangler",
"creates",
"a",
"new",
"wrangler",
"using",
"the",
"instance",
"specific",
"configuration",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/instance.go#L76-L78 | train |
vitessio/vitess | go/vt/worker/instance.go | InstallSignalHandlers | func (wi *Instance) InstallSignalHandlers() {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGTERM, syscall.SIGINT)
go func() {
for s := range sigChan {
// We got a signal, notify our modules.
// Use an extra function to properly unlock using defer.
func() {
wi.currentWorkerMutex.Lock()
defer wi.currentWorkerMutex.Unlock()
if wi.currentCancelFunc != nil {
log.Infof("Trying to cancel current worker after receiving signal: %v", s)
wi.currentCancelFunc()
} else {
log.Infof("Shutting down idle worker after receiving signal: %v", s)
os.Exit(0)
}
}()
}
}()
} | go | func (wi *Instance) InstallSignalHandlers() {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGTERM, syscall.SIGINT)
go func() {
for s := range sigChan {
// We got a signal, notify our modules.
// Use an extra function to properly unlock using defer.
func() {
wi.currentWorkerMutex.Lock()
defer wi.currentWorkerMutex.Unlock()
if wi.currentCancelFunc != nil {
log.Infof("Trying to cancel current worker after receiving signal: %v", s)
wi.currentCancelFunc()
} else {
log.Infof("Shutting down idle worker after receiving signal: %v", s)
os.Exit(0)
}
}()
}
}()
} | [
"func",
"(",
"wi",
"*",
"Instance",
")",
"InstallSignalHandlers",
"(",
")",
"{",
"sigChan",
":=",
"make",
"(",
"chan",
"os",
".",
"Signal",
",",
"1",
")",
"\n",
"signal",
".",
"Notify",
"(",
"sigChan",
",",
"syscall",
".",
"SIGTERM",
",",
"syscall",
".",
"SIGINT",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"for",
"s",
":=",
"range",
"sigChan",
"{",
"// We got a signal, notify our modules.",
"// Use an extra function to properly unlock using defer.",
"func",
"(",
")",
"{",
"wi",
".",
"currentWorkerMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"wi",
".",
"currentWorkerMutex",
".",
"Unlock",
"(",
")",
"\n",
"if",
"wi",
".",
"currentCancelFunc",
"!=",
"nil",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"s",
")",
"\n",
"wi",
".",
"currentCancelFunc",
"(",
")",
"\n",
"}",
"else",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"s",
")",
"\n",
"os",
".",
"Exit",
"(",
"0",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}"
] | // InstallSignalHandlers installs signal handler which exit vtworker gracefully. | [
"InstallSignalHandlers",
"installs",
"signal",
"handler",
"which",
"exit",
"vtworker",
"gracefully",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/instance.go#L173-L193 | train |
vitessio/vitess | go/vt/worker/instance.go | Reset | func (wi *Instance) Reset() error {
wi.currentWorkerMutex.Lock()
defer wi.currentWorkerMutex.Unlock()
if wi.currentWorker == nil {
return nil
}
// check the worker is really done
if wi.currentContext == nil {
wi.currentWorker = nil
wi.currentMemoryLogger = nil
return nil
}
return vterrors.New(vtrpcpb.Code_FAILED_PRECONDITION, "worker still executing")
} | go | func (wi *Instance) Reset() error {
wi.currentWorkerMutex.Lock()
defer wi.currentWorkerMutex.Unlock()
if wi.currentWorker == nil {
return nil
}
// check the worker is really done
if wi.currentContext == nil {
wi.currentWorker = nil
wi.currentMemoryLogger = nil
return nil
}
return vterrors.New(vtrpcpb.Code_FAILED_PRECONDITION, "worker still executing")
} | [
"func",
"(",
"wi",
"*",
"Instance",
")",
"Reset",
"(",
")",
"error",
"{",
"wi",
".",
"currentWorkerMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"wi",
".",
"currentWorkerMutex",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"wi",
".",
"currentWorker",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// check the worker is really done",
"if",
"wi",
".",
"currentContext",
"==",
"nil",
"{",
"wi",
".",
"currentWorker",
"=",
"nil",
"\n",
"wi",
".",
"currentMemoryLogger",
"=",
"nil",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"vterrors",
".",
"New",
"(",
"vtrpcpb",
".",
"Code_FAILED_PRECONDITION",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // Reset resets the state of a finished worker. It returns an error if the worker is still running. | [
"Reset",
"resets",
"the",
"state",
"of",
"a",
"finished",
"worker",
".",
"It",
"returns",
"an",
"error",
"if",
"the",
"worker",
"is",
"still",
"running",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/instance.go#L196-L212 | train |
vitessio/vitess | go/vt/worker/row_differ.go | skipRow | func (rd *RowDiffer2) skipRow() {
rd.equalRowsStatsCounters.Add(rd.tableName, 1)
rd.tableStatusList.addCopiedRows(rd.tableIndex, 1)
} | go | func (rd *RowDiffer2) skipRow() {
rd.equalRowsStatsCounters.Add(rd.tableName, 1)
rd.tableStatusList.addCopiedRows(rd.tableIndex, 1)
} | [
"func",
"(",
"rd",
"*",
"RowDiffer2",
")",
"skipRow",
"(",
")",
"{",
"rd",
".",
"equalRowsStatsCounters",
".",
"Add",
"(",
"rd",
".",
"tableName",
",",
"1",
")",
"\n",
"rd",
".",
"tableStatusList",
".",
"addCopiedRows",
"(",
"rd",
".",
"tableIndex",
",",
"1",
")",
"\n",
"}"
] | // skipRow is used for the DiffType DiffEqual.
// Currently, it only updates the statistics and therefore does not require the
// row as input. | [
"skipRow",
"is",
"used",
"for",
"the",
"DiffType",
"DiffEqual",
".",
"Currently",
"it",
"only",
"updates",
"the",
"statistics",
"and",
"therefore",
"does",
"not",
"require",
"the",
"row",
"as",
"input",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/row_differ.go#L272-L275 | train |
vitessio/vitess | go/vt/worker/row_differ.go | reconcileRow | func (rd *RowDiffer2) reconcileRow(row []sqltypes.Value, typ DiffType) error {
if typ == DiffNotEqual {
panic(fmt.Sprintf("reconcileRow() called with wrong type: %v", typ))
}
destShardIndex, err := rd.router.Route(row)
if err != nil {
return vterrors.Wrapf(err, "failed to route row (%v) to correct shard", row)
}
if err := rd.aggregators[destShardIndex][typ].Add(row); err != nil {
return vterrors.Wrap(err, "failed to add row update to RowAggregator")
}
// TODO(mberlin): Add more fine granular stats here.
rd.tableStatusList.addCopiedRows(rd.tableIndex, 1)
return nil
} | go | func (rd *RowDiffer2) reconcileRow(row []sqltypes.Value, typ DiffType) error {
if typ == DiffNotEqual {
panic(fmt.Sprintf("reconcileRow() called with wrong type: %v", typ))
}
destShardIndex, err := rd.router.Route(row)
if err != nil {
return vterrors.Wrapf(err, "failed to route row (%v) to correct shard", row)
}
if err := rd.aggregators[destShardIndex][typ].Add(row); err != nil {
return vterrors.Wrap(err, "failed to add row update to RowAggregator")
}
// TODO(mberlin): Add more fine granular stats here.
rd.tableStatusList.addCopiedRows(rd.tableIndex, 1)
return nil
} | [
"func",
"(",
"rd",
"*",
"RowDiffer2",
")",
"reconcileRow",
"(",
"row",
"[",
"]",
"sqltypes",
".",
"Value",
",",
"typ",
"DiffType",
")",
"error",
"{",
"if",
"typ",
"==",
"DiffNotEqual",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"typ",
")",
")",
"\n",
"}",
"\n",
"destShardIndex",
",",
"err",
":=",
"rd",
".",
"router",
".",
"Route",
"(",
"row",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"vterrors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"row",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"rd",
".",
"aggregators",
"[",
"destShardIndex",
"]",
"[",
"typ",
"]",
".",
"Add",
"(",
"row",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"vterrors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// TODO(mberlin): Add more fine granular stats here.",
"rd",
".",
"tableStatusList",
".",
"addCopiedRows",
"(",
"rd",
".",
"tableIndex",
",",
"1",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // reconcileRow is used for the DiffType DiffMissing and DiffExtraneous. | [
"reconcileRow",
"is",
"used",
"for",
"the",
"DiffType",
"DiffMissing",
"and",
"DiffExtraneous",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/row_differ.go#L278-L293 | train |
vitessio/vitess | go/vt/worker/row_differ.go | NewRowRouter | func NewRowRouter(shardInfos []*topo.ShardInfo, keyResolver keyspaceIDResolver) RowRouter {
keyRanges := make([]*topodatapb.KeyRange, len(shardInfos))
for i, si := range shardInfos {
keyRanges[i] = si.KeyRange
}
return RowRouter{keyResolver, keyRanges}
} | go | func NewRowRouter(shardInfos []*topo.ShardInfo, keyResolver keyspaceIDResolver) RowRouter {
keyRanges := make([]*topodatapb.KeyRange, len(shardInfos))
for i, si := range shardInfos {
keyRanges[i] = si.KeyRange
}
return RowRouter{keyResolver, keyRanges}
} | [
"func",
"NewRowRouter",
"(",
"shardInfos",
"[",
"]",
"*",
"topo",
".",
"ShardInfo",
",",
"keyResolver",
"keyspaceIDResolver",
")",
"RowRouter",
"{",
"keyRanges",
":=",
"make",
"(",
"[",
"]",
"*",
"topodatapb",
".",
"KeyRange",
",",
"len",
"(",
"shardInfos",
")",
")",
"\n",
"for",
"i",
",",
"si",
":=",
"range",
"shardInfos",
"{",
"keyRanges",
"[",
"i",
"]",
"=",
"si",
".",
"KeyRange",
"\n",
"}",
"\n",
"return",
"RowRouter",
"{",
"keyResolver",
",",
"keyRanges",
"}",
"\n",
"}"
] | // NewRowRouter creates a RowRouter.
// We assume that the key ranges in shardInfo cover the full keyrange i.e.
// for any possible keyspaceID there is a shard we can route to. | [
"NewRowRouter",
"creates",
"a",
"RowRouter",
".",
"We",
"assume",
"that",
"the",
"key",
"ranges",
"in",
"shardInfo",
"cover",
"the",
"full",
"keyrange",
"i",
".",
"e",
".",
"for",
"any",
"possible",
"keyspaceID",
"there",
"is",
"a",
"shard",
"we",
"can",
"route",
"to",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/worker/row_differ.go#L343-L349 | train |
vitessio/vitess | go/vt/wrangler/schema.go | GetSchema | func (wr *Wrangler) GetSchema(ctx context.Context, tabletAlias *topodatapb.TabletAlias, tables, excludeTables []string, includeViews bool) (*tabletmanagerdatapb.SchemaDefinition, error) {
ti, err := wr.ts.GetTablet(ctx, tabletAlias)
if err != nil {
return nil, fmt.Errorf("GetTablet(%v) failed: %v", tabletAlias, err)
}
return wr.tmc.GetSchema(ctx, ti.Tablet, tables, excludeTables, includeViews)
} | go | func (wr *Wrangler) GetSchema(ctx context.Context, tabletAlias *topodatapb.TabletAlias, tables, excludeTables []string, includeViews bool) (*tabletmanagerdatapb.SchemaDefinition, error) {
ti, err := wr.ts.GetTablet(ctx, tabletAlias)
if err != nil {
return nil, fmt.Errorf("GetTablet(%v) failed: %v", tabletAlias, err)
}
return wr.tmc.GetSchema(ctx, ti.Tablet, tables, excludeTables, includeViews)
} | [
"func",
"(",
"wr",
"*",
"Wrangler",
")",
"GetSchema",
"(",
"ctx",
"context",
".",
"Context",
",",
"tabletAlias",
"*",
"topodatapb",
".",
"TabletAlias",
",",
"tables",
",",
"excludeTables",
"[",
"]",
"string",
",",
"includeViews",
"bool",
")",
"(",
"*",
"tabletmanagerdatapb",
".",
"SchemaDefinition",
",",
"error",
")",
"{",
"ti",
",",
"err",
":=",
"wr",
".",
"ts",
".",
"GetTablet",
"(",
"ctx",
",",
"tabletAlias",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"tabletAlias",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"wr",
".",
"tmc",
".",
"GetSchema",
"(",
"ctx",
",",
"ti",
".",
"Tablet",
",",
"tables",
",",
"excludeTables",
",",
"includeViews",
")",
"\n",
"}"
] | // GetSchema uses an RPC to get the schema from a remote tablet | [
"GetSchema",
"uses",
"an",
"RPC",
"to",
"get",
"the",
"schema",
"from",
"a",
"remote",
"tablet"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/schema.go#L47-L54 | train |
vitessio/vitess | go/vt/wrangler/schema.go | ReloadSchema | func (wr *Wrangler) ReloadSchema(ctx context.Context, tabletAlias *topodatapb.TabletAlias) error {
ti, err := wr.ts.GetTablet(ctx, tabletAlias)
if err != nil {
return fmt.Errorf("GetTablet(%v) failed: %v", tabletAlias, err)
}
return wr.tmc.ReloadSchema(ctx, ti.Tablet, "")
} | go | func (wr *Wrangler) ReloadSchema(ctx context.Context, tabletAlias *topodatapb.TabletAlias) error {
ti, err := wr.ts.GetTablet(ctx, tabletAlias)
if err != nil {
return fmt.Errorf("GetTablet(%v) failed: %v", tabletAlias, err)
}
return wr.tmc.ReloadSchema(ctx, ti.Tablet, "")
} | [
"func",
"(",
"wr",
"*",
"Wrangler",
")",
"ReloadSchema",
"(",
"ctx",
"context",
".",
"Context",
",",
"tabletAlias",
"*",
"topodatapb",
".",
"TabletAlias",
")",
"error",
"{",
"ti",
",",
"err",
":=",
"wr",
".",
"ts",
".",
"GetTablet",
"(",
"ctx",
",",
"tabletAlias",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"tabletAlias",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"wr",
".",
"tmc",
".",
"ReloadSchema",
"(",
"ctx",
",",
"ti",
".",
"Tablet",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // ReloadSchema forces the remote tablet to reload its schema. | [
"ReloadSchema",
"forces",
"the",
"remote",
"tablet",
"to",
"reload",
"its",
"schema",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/schema.go#L57-L64 | train |
vitessio/vitess | go/vt/wrangler/schema.go | diffSchema | func (wr *Wrangler) diffSchema(ctx context.Context, masterSchema *tabletmanagerdatapb.SchemaDefinition, masterTabletAlias, alias *topodatapb.TabletAlias, excludeTables []string, includeViews bool, wg *sync.WaitGroup, er concurrency.ErrorRecorder) {
defer wg.Done()
log.Infof("Gathering schema for %v", topoproto.TabletAliasString(alias))
slaveSchema, err := wr.GetSchema(ctx, alias, nil, excludeTables, includeViews)
if err != nil {
er.RecordError(fmt.Errorf("GetSchema(%v, nil, %v, %v) failed: %v", alias, excludeTables, includeViews, err))
return
}
log.Infof("Diffing schema for %v", topoproto.TabletAliasString(alias))
tmutils.DiffSchema(topoproto.TabletAliasString(masterTabletAlias), masterSchema, topoproto.TabletAliasString(alias), slaveSchema, er)
} | go | func (wr *Wrangler) diffSchema(ctx context.Context, masterSchema *tabletmanagerdatapb.SchemaDefinition, masterTabletAlias, alias *topodatapb.TabletAlias, excludeTables []string, includeViews bool, wg *sync.WaitGroup, er concurrency.ErrorRecorder) {
defer wg.Done()
log.Infof("Gathering schema for %v", topoproto.TabletAliasString(alias))
slaveSchema, err := wr.GetSchema(ctx, alias, nil, excludeTables, includeViews)
if err != nil {
er.RecordError(fmt.Errorf("GetSchema(%v, nil, %v, %v) failed: %v", alias, excludeTables, includeViews, err))
return
}
log.Infof("Diffing schema for %v", topoproto.TabletAliasString(alias))
tmutils.DiffSchema(topoproto.TabletAliasString(masterTabletAlias), masterSchema, topoproto.TabletAliasString(alias), slaveSchema, er)
} | [
"func",
"(",
"wr",
"*",
"Wrangler",
")",
"diffSchema",
"(",
"ctx",
"context",
".",
"Context",
",",
"masterSchema",
"*",
"tabletmanagerdatapb",
".",
"SchemaDefinition",
",",
"masterTabletAlias",
",",
"alias",
"*",
"topodatapb",
".",
"TabletAlias",
",",
"excludeTables",
"[",
"]",
"string",
",",
"includeViews",
"bool",
",",
"wg",
"*",
"sync",
".",
"WaitGroup",
",",
"er",
"concurrency",
".",
"ErrorRecorder",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"topoproto",
".",
"TabletAliasString",
"(",
"alias",
")",
")",
"\n",
"slaveSchema",
",",
"err",
":=",
"wr",
".",
"GetSchema",
"(",
"ctx",
",",
"alias",
",",
"nil",
",",
"excludeTables",
",",
"includeViews",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"er",
".",
"RecordError",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"alias",
",",
"excludeTables",
",",
"includeViews",
",",
"err",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"topoproto",
".",
"TabletAliasString",
"(",
"alias",
")",
")",
"\n",
"tmutils",
".",
"DiffSchema",
"(",
"topoproto",
".",
"TabletAliasString",
"(",
"masterTabletAlias",
")",
",",
"masterSchema",
",",
"topoproto",
".",
"TabletAliasString",
"(",
"alias",
")",
",",
"slaveSchema",
",",
"er",
")",
"\n",
"}"
] | // helper method to asynchronously diff a schema | [
"helper",
"method",
"to",
"asynchronously",
"diff",
"a",
"schema"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/schema.go#L132-L143 | train |
vitessio/vitess | go/vt/wrangler/schema.go | ValidateSchemaShard | func (wr *Wrangler) ValidateSchemaShard(ctx context.Context, keyspace, shard string, excludeTables []string, includeViews bool) error {
si, err := wr.ts.GetShard(ctx, keyspace, shard)
if err != nil {
return fmt.Errorf("GetShard(%v, %v) failed: %v", keyspace, shard, err)
}
// get schema from the master, or error
if !si.HasMaster() {
return fmt.Errorf("no master in shard %v/%v", keyspace, shard)
}
log.Infof("Gathering schema for master %v", topoproto.TabletAliasString(si.MasterAlias))
masterSchema, err := wr.GetSchema(ctx, si.MasterAlias, nil, excludeTables, includeViews)
if err != nil {
return fmt.Errorf("GetSchema(%v, nil, %v, %v) failed: %v", si.MasterAlias, excludeTables, includeViews, err)
}
// read all the aliases in the shard, that is all tablets that are
// replicating from the master
aliases, err := wr.ts.FindAllTabletAliasesInShard(ctx, keyspace, shard)
if err != nil {
return fmt.Errorf("FindAllTabletAliasesInShard(%v, %v) failed: %v", keyspace, shard, err)
}
// then diff with all slaves
er := concurrency.AllErrorRecorder{}
wg := sync.WaitGroup{}
for _, alias := range aliases {
if topoproto.TabletAliasEqual(alias, si.MasterAlias) {
continue
}
wg.Add(1)
go wr.diffSchema(ctx, masterSchema, si.MasterAlias, alias, excludeTables, includeViews, &wg, &er)
}
wg.Wait()
if er.HasErrors() {
return fmt.Errorf("schema diffs: %v", er.Error().Error())
}
return nil
} | go | func (wr *Wrangler) ValidateSchemaShard(ctx context.Context, keyspace, shard string, excludeTables []string, includeViews bool) error {
si, err := wr.ts.GetShard(ctx, keyspace, shard)
if err != nil {
return fmt.Errorf("GetShard(%v, %v) failed: %v", keyspace, shard, err)
}
// get schema from the master, or error
if !si.HasMaster() {
return fmt.Errorf("no master in shard %v/%v", keyspace, shard)
}
log.Infof("Gathering schema for master %v", topoproto.TabletAliasString(si.MasterAlias))
masterSchema, err := wr.GetSchema(ctx, si.MasterAlias, nil, excludeTables, includeViews)
if err != nil {
return fmt.Errorf("GetSchema(%v, nil, %v, %v) failed: %v", si.MasterAlias, excludeTables, includeViews, err)
}
// read all the aliases in the shard, that is all tablets that are
// replicating from the master
aliases, err := wr.ts.FindAllTabletAliasesInShard(ctx, keyspace, shard)
if err != nil {
return fmt.Errorf("FindAllTabletAliasesInShard(%v, %v) failed: %v", keyspace, shard, err)
}
// then diff with all slaves
er := concurrency.AllErrorRecorder{}
wg := sync.WaitGroup{}
for _, alias := range aliases {
if topoproto.TabletAliasEqual(alias, si.MasterAlias) {
continue
}
wg.Add(1)
go wr.diffSchema(ctx, masterSchema, si.MasterAlias, alias, excludeTables, includeViews, &wg, &er)
}
wg.Wait()
if er.HasErrors() {
return fmt.Errorf("schema diffs: %v", er.Error().Error())
}
return nil
} | [
"func",
"(",
"wr",
"*",
"Wrangler",
")",
"ValidateSchemaShard",
"(",
"ctx",
"context",
".",
"Context",
",",
"keyspace",
",",
"shard",
"string",
",",
"excludeTables",
"[",
"]",
"string",
",",
"includeViews",
"bool",
")",
"error",
"{",
"si",
",",
"err",
":=",
"wr",
".",
"ts",
".",
"GetShard",
"(",
"ctx",
",",
"keyspace",
",",
"shard",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"keyspace",
",",
"shard",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// get schema from the master, or error",
"if",
"!",
"si",
".",
"HasMaster",
"(",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"keyspace",
",",
"shard",
")",
"\n",
"}",
"\n",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"topoproto",
".",
"TabletAliasString",
"(",
"si",
".",
"MasterAlias",
")",
")",
"\n",
"masterSchema",
",",
"err",
":=",
"wr",
".",
"GetSchema",
"(",
"ctx",
",",
"si",
".",
"MasterAlias",
",",
"nil",
",",
"excludeTables",
",",
"includeViews",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"si",
".",
"MasterAlias",
",",
"excludeTables",
",",
"includeViews",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// read all the aliases in the shard, that is all tablets that are",
"// replicating from the master",
"aliases",
",",
"err",
":=",
"wr",
".",
"ts",
".",
"FindAllTabletAliasesInShard",
"(",
"ctx",
",",
"keyspace",
",",
"shard",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"keyspace",
",",
"shard",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// then diff with all slaves",
"er",
":=",
"concurrency",
".",
"AllErrorRecorder",
"{",
"}",
"\n",
"wg",
":=",
"sync",
".",
"WaitGroup",
"{",
"}",
"\n",
"for",
"_",
",",
"alias",
":=",
"range",
"aliases",
"{",
"if",
"topoproto",
".",
"TabletAliasEqual",
"(",
"alias",
",",
"si",
".",
"MasterAlias",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"wr",
".",
"diffSchema",
"(",
"ctx",
",",
"masterSchema",
",",
"si",
".",
"MasterAlias",
",",
"alias",
",",
"excludeTables",
",",
"includeViews",
",",
"&",
"wg",
",",
"&",
"er",
")",
"\n",
"}",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"if",
"er",
".",
"HasErrors",
"(",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"er",
".",
"Error",
"(",
")",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // ValidateSchemaShard will diff the schema from all the tablets in the shard. | [
"ValidateSchemaShard",
"will",
"diff",
"the",
"schema",
"from",
"all",
"the",
"tablets",
"in",
"the",
"shard",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/schema.go#L146-L185 | train |
vitessio/vitess | go/vt/wrangler/schema.go | PreflightSchema | func (wr *Wrangler) PreflightSchema(ctx context.Context, tabletAlias *topodatapb.TabletAlias, changes []string) ([]*tabletmanagerdatapb.SchemaChangeResult, error) {
ti, err := wr.ts.GetTablet(ctx, tabletAlias)
if err != nil {
return nil, fmt.Errorf("GetTablet(%v) failed: %v", tabletAlias, err)
}
return wr.tmc.PreflightSchema(ctx, ti.Tablet, changes)
} | go | func (wr *Wrangler) PreflightSchema(ctx context.Context, tabletAlias *topodatapb.TabletAlias, changes []string) ([]*tabletmanagerdatapb.SchemaChangeResult, error) {
ti, err := wr.ts.GetTablet(ctx, tabletAlias)
if err != nil {
return nil, fmt.Errorf("GetTablet(%v) failed: %v", tabletAlias, err)
}
return wr.tmc.PreflightSchema(ctx, ti.Tablet, changes)
} | [
"func",
"(",
"wr",
"*",
"Wrangler",
")",
"PreflightSchema",
"(",
"ctx",
"context",
".",
"Context",
",",
"tabletAlias",
"*",
"topodatapb",
".",
"TabletAlias",
",",
"changes",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"*",
"tabletmanagerdatapb",
".",
"SchemaChangeResult",
",",
"error",
")",
"{",
"ti",
",",
"err",
":=",
"wr",
".",
"ts",
".",
"GetTablet",
"(",
"ctx",
",",
"tabletAlias",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"tabletAlias",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"wr",
".",
"tmc",
".",
"PreflightSchema",
"(",
"ctx",
",",
"ti",
".",
"Tablet",
",",
"changes",
")",
"\n",
"}"
] | // PreflightSchema will try a schema change on the remote tablet. | [
"PreflightSchema",
"will",
"try",
"a",
"schema",
"change",
"on",
"the",
"remote",
"tablet",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/schema.go#L271-L277 | train |
vitessio/vitess | go/vt/wrangler/schema.go | CopySchemaShardFromShard | func (wr *Wrangler) CopySchemaShardFromShard(ctx context.Context, tables, excludeTables []string, includeViews bool, sourceKeyspace, sourceShard, destKeyspace, destShard string, waitSlaveTimeout time.Duration) error {
sourceShardInfo, err := wr.ts.GetShard(ctx, sourceKeyspace, sourceShard)
if err != nil {
return fmt.Errorf("GetShard(%v, %v) failed: %v", sourceKeyspace, sourceShard, err)
}
if sourceShardInfo.MasterAlias == nil {
return fmt.Errorf("no master in shard record %v/%v. Consider running 'vtctl InitShardMaster' in case of a new shard or to reparent the shard to fix the topology data, or providing a non-master tablet alias", sourceKeyspace, sourceShard)
}
return wr.CopySchemaShard(ctx, sourceShardInfo.MasterAlias, tables, excludeTables, includeViews, destKeyspace, destShard, waitSlaveTimeout)
} | go | func (wr *Wrangler) CopySchemaShardFromShard(ctx context.Context, tables, excludeTables []string, includeViews bool, sourceKeyspace, sourceShard, destKeyspace, destShard string, waitSlaveTimeout time.Duration) error {
sourceShardInfo, err := wr.ts.GetShard(ctx, sourceKeyspace, sourceShard)
if err != nil {
return fmt.Errorf("GetShard(%v, %v) failed: %v", sourceKeyspace, sourceShard, err)
}
if sourceShardInfo.MasterAlias == nil {
return fmt.Errorf("no master in shard record %v/%v. Consider running 'vtctl InitShardMaster' in case of a new shard or to reparent the shard to fix the topology data, or providing a non-master tablet alias", sourceKeyspace, sourceShard)
}
return wr.CopySchemaShard(ctx, sourceShardInfo.MasterAlias, tables, excludeTables, includeViews, destKeyspace, destShard, waitSlaveTimeout)
} | [
"func",
"(",
"wr",
"*",
"Wrangler",
")",
"CopySchemaShardFromShard",
"(",
"ctx",
"context",
".",
"Context",
",",
"tables",
",",
"excludeTables",
"[",
"]",
"string",
",",
"includeViews",
"bool",
",",
"sourceKeyspace",
",",
"sourceShard",
",",
"destKeyspace",
",",
"destShard",
"string",
",",
"waitSlaveTimeout",
"time",
".",
"Duration",
")",
"error",
"{",
"sourceShardInfo",
",",
"err",
":=",
"wr",
".",
"ts",
".",
"GetShard",
"(",
"ctx",
",",
"sourceKeyspace",
",",
"sourceShard",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"sourceKeyspace",
",",
"sourceShard",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"sourceShardInfo",
".",
"MasterAlias",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"sourceKeyspace",
",",
"sourceShard",
")",
"\n",
"}",
"\n\n",
"return",
"wr",
".",
"CopySchemaShard",
"(",
"ctx",
",",
"sourceShardInfo",
".",
"MasterAlias",
",",
"tables",
",",
"excludeTables",
",",
"includeViews",
",",
"destKeyspace",
",",
"destShard",
",",
"waitSlaveTimeout",
")",
"\n",
"}"
] | // CopySchemaShardFromShard copies the schema from a source shard to the specified destination shard.
// For both source and destination it picks the master tablet. See also CopySchemaShard. | [
"CopySchemaShardFromShard",
"copies",
"the",
"schema",
"from",
"a",
"source",
"shard",
"to",
"the",
"specified",
"destination",
"shard",
".",
"For",
"both",
"source",
"and",
"destination",
"it",
"picks",
"the",
"master",
"tablet",
".",
"See",
"also",
"CopySchemaShard",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/schema.go#L281-L291 | train |
vitessio/vitess | go/vt/wrangler/schema.go | copyShardMetadata | func (wr *Wrangler) copyShardMetadata(ctx context.Context, srcTabletAlias *topodatapb.TabletAlias, destTabletAlias *topodatapb.TabletAlias) error {
sql := "SELECT 1 FROM information_schema.tables WHERE table_schema = '_vt' AND table_name = 'shard_metadata'"
presenceResult, err := wr.ExecuteFetchAsDba(ctx, srcTabletAlias, sql, 1, false, false)
if err != nil {
return fmt.Errorf("ExecuteFetchAsDba(%v, %v, 1, false, false) failed: %v", srcTabletAlias, sql, err)
}
if len(presenceResult.Rows) == 0 {
log.Infof("_vt.shard_metadata doesn't exist on the source tablet %v, skipping its copy.", topoproto.TabletAliasString(srcTabletAlias))
return nil
}
// TODO: 100 may be too low here for row limit
sql = "SELECT db_name, name, value FROM _vt.shard_metadata"
dataProto, err := wr.ExecuteFetchAsDba(ctx, srcTabletAlias, sql, 100, false, false)
if err != nil {
return fmt.Errorf("ExecuteFetchAsDba(%v, %v, 100, false, false) failed: %v", srcTabletAlias, sql, err)
}
data := sqltypes.Proto3ToResult(dataProto)
for _, row := range data.Rows {
dbName := row[0]
name := row[1]
value := row[2]
queryBuf := bytes.Buffer{}
queryBuf.WriteString("INSERT INTO _vt.shard_metadata (db_name, name, value) VALUES (")
dbName.EncodeSQL(&queryBuf)
queryBuf.WriteByte(',')
name.EncodeSQL(&queryBuf)
queryBuf.WriteByte(',')
value.EncodeSQL(&queryBuf)
queryBuf.WriteString(") ON DUPLICATE KEY UPDATE value = ")
value.EncodeSQL(&queryBuf)
_, err := wr.ExecuteFetchAsDba(ctx, destTabletAlias, queryBuf.String(), 0, false, false)
if err != nil {
return fmt.Errorf("ExecuteFetchAsDba(%v, %v, 0, false, false) failed: %v", destTabletAlias, queryBuf.String(), err)
}
}
return nil
} | go | func (wr *Wrangler) copyShardMetadata(ctx context.Context, srcTabletAlias *topodatapb.TabletAlias, destTabletAlias *topodatapb.TabletAlias) error {
sql := "SELECT 1 FROM information_schema.tables WHERE table_schema = '_vt' AND table_name = 'shard_metadata'"
presenceResult, err := wr.ExecuteFetchAsDba(ctx, srcTabletAlias, sql, 1, false, false)
if err != nil {
return fmt.Errorf("ExecuteFetchAsDba(%v, %v, 1, false, false) failed: %v", srcTabletAlias, sql, err)
}
if len(presenceResult.Rows) == 0 {
log.Infof("_vt.shard_metadata doesn't exist on the source tablet %v, skipping its copy.", topoproto.TabletAliasString(srcTabletAlias))
return nil
}
// TODO: 100 may be too low here for row limit
sql = "SELECT db_name, name, value FROM _vt.shard_metadata"
dataProto, err := wr.ExecuteFetchAsDba(ctx, srcTabletAlias, sql, 100, false, false)
if err != nil {
return fmt.Errorf("ExecuteFetchAsDba(%v, %v, 100, false, false) failed: %v", srcTabletAlias, sql, err)
}
data := sqltypes.Proto3ToResult(dataProto)
for _, row := range data.Rows {
dbName := row[0]
name := row[1]
value := row[2]
queryBuf := bytes.Buffer{}
queryBuf.WriteString("INSERT INTO _vt.shard_metadata (db_name, name, value) VALUES (")
dbName.EncodeSQL(&queryBuf)
queryBuf.WriteByte(',')
name.EncodeSQL(&queryBuf)
queryBuf.WriteByte(',')
value.EncodeSQL(&queryBuf)
queryBuf.WriteString(") ON DUPLICATE KEY UPDATE value = ")
value.EncodeSQL(&queryBuf)
_, err := wr.ExecuteFetchAsDba(ctx, destTabletAlias, queryBuf.String(), 0, false, false)
if err != nil {
return fmt.Errorf("ExecuteFetchAsDba(%v, %v, 0, false, false) failed: %v", destTabletAlias, queryBuf.String(), err)
}
}
return nil
} | [
"func",
"(",
"wr",
"*",
"Wrangler",
")",
"copyShardMetadata",
"(",
"ctx",
"context",
".",
"Context",
",",
"srcTabletAlias",
"*",
"topodatapb",
".",
"TabletAlias",
",",
"destTabletAlias",
"*",
"topodatapb",
".",
"TabletAlias",
")",
"error",
"{",
"sql",
":=",
"\"",
"\"",
"\n",
"presenceResult",
",",
"err",
":=",
"wr",
".",
"ExecuteFetchAsDba",
"(",
"ctx",
",",
"srcTabletAlias",
",",
"sql",
",",
"1",
",",
"false",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"srcTabletAlias",
",",
"sql",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"presenceResult",
".",
"Rows",
")",
"==",
"0",
"{",
"log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"topoproto",
".",
"TabletAliasString",
"(",
"srcTabletAlias",
")",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// TODO: 100 may be too low here for row limit",
"sql",
"=",
"\"",
"\"",
"\n",
"dataProto",
",",
"err",
":=",
"wr",
".",
"ExecuteFetchAsDba",
"(",
"ctx",
",",
"srcTabletAlias",
",",
"sql",
",",
"100",
",",
"false",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"srcTabletAlias",
",",
"sql",
",",
"err",
")",
"\n",
"}",
"\n",
"data",
":=",
"sqltypes",
".",
"Proto3ToResult",
"(",
"dataProto",
")",
"\n",
"for",
"_",
",",
"row",
":=",
"range",
"data",
".",
"Rows",
"{",
"dbName",
":=",
"row",
"[",
"0",
"]",
"\n",
"name",
":=",
"row",
"[",
"1",
"]",
"\n",
"value",
":=",
"row",
"[",
"2",
"]",
"\n",
"queryBuf",
":=",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"queryBuf",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"dbName",
".",
"EncodeSQL",
"(",
"&",
"queryBuf",
")",
"\n",
"queryBuf",
".",
"WriteByte",
"(",
"','",
")",
"\n",
"name",
".",
"EncodeSQL",
"(",
"&",
"queryBuf",
")",
"\n",
"queryBuf",
".",
"WriteByte",
"(",
"','",
")",
"\n",
"value",
".",
"EncodeSQL",
"(",
"&",
"queryBuf",
")",
"\n",
"queryBuf",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"value",
".",
"EncodeSQL",
"(",
"&",
"queryBuf",
")",
"\n\n",
"_",
",",
"err",
":=",
"wr",
".",
"ExecuteFetchAsDba",
"(",
"ctx",
",",
"destTabletAlias",
",",
"queryBuf",
".",
"String",
"(",
")",
",",
"0",
",",
"false",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"destTabletAlias",
",",
"queryBuf",
".",
"String",
"(",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // copyShardMetadata copies contents of _vt.shard_metadata table from the source
// tablet to the destination tablet. It's assumed that destination tablet is a
// master and binlogging is not turned off when INSERT statements are executed. | [
"copyShardMetadata",
"copies",
"contents",
"of",
"_vt",
".",
"shard_metadata",
"table",
"from",
"the",
"source",
"tablet",
"to",
"the",
"destination",
"tablet",
".",
"It",
"s",
"assumed",
"that",
"destination",
"tablet",
"is",
"a",
"master",
"and",
"binlogging",
"is",
"not",
"turned",
"off",
"when",
"INSERT",
"statements",
"are",
"executed",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/schema.go#L371-L409 | train |
vitessio/vitess | go/vt/wrangler/schema.go | fillStringTemplate | func fillStringTemplate(tmpl string, vars interface{}) (string, error) {
myTemplate := template.Must(template.New("").Parse(tmpl))
data := new(bytes.Buffer)
if err := myTemplate.Execute(data, vars); err != nil {
return "", err
}
return data.String(), nil
} | go | func fillStringTemplate(tmpl string, vars interface{}) (string, error) {
myTemplate := template.Must(template.New("").Parse(tmpl))
data := new(bytes.Buffer)
if err := myTemplate.Execute(data, vars); err != nil {
return "", err
}
return data.String(), nil
} | [
"func",
"fillStringTemplate",
"(",
"tmpl",
"string",
",",
"vars",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"myTemplate",
":=",
"template",
".",
"Must",
"(",
"template",
".",
"New",
"(",
"\"",
"\"",
")",
".",
"Parse",
"(",
"tmpl",
")",
")",
"\n",
"data",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n",
"if",
"err",
":=",
"myTemplate",
".",
"Execute",
"(",
"data",
",",
"vars",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"data",
".",
"String",
"(",
")",
",",
"nil",
"\n",
"}"
] | // fillStringTemplate returns the string template filled | [
"fillStringTemplate",
"returns",
"the",
"string",
"template",
"filled"
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/wrangler/schema.go#L446-L453 | train |
vitessio/vitess | go/vt/dbconnpool/connection_pool.go | NewConnectionPool | func NewConnectionPool(name string, capacity int, idleTimeout time.Duration, dnsResolutionFrequency time.Duration) *ConnectionPool {
cp := &ConnectionPool{capacity: capacity, idleTimeout: idleTimeout, resolutionFrequency: dnsResolutionFrequency}
if name == "" || usedNames[name] {
return cp
}
usedNames[name] = true
stats.NewGaugeFunc(name+"Capacity", "Connection pool capacity", cp.Capacity)
stats.NewGaugeFunc(name+"Available", "Connection pool available", cp.Available)
stats.NewGaugeFunc(name+"Active", "Connection pool active", cp.Active)
stats.NewGaugeFunc(name+"InUse", "Connection pool in-use", cp.InUse)
stats.NewGaugeFunc(name+"MaxCap", "Connection pool max cap", cp.MaxCap)
stats.NewCounterFunc(name+"WaitCount", "Connection pool wait count", cp.WaitCount)
stats.NewCounterDurationFunc(name+"WaitTime", "Connection pool wait time", cp.WaitTime)
stats.NewGaugeDurationFunc(name+"IdleTimeout", "Connection pool idle timeout", cp.IdleTimeout)
stats.NewGaugeFunc(name+"IdleClosed", "Connection pool idle closed", cp.IdleClosed)
return cp
} | go | func NewConnectionPool(name string, capacity int, idleTimeout time.Duration, dnsResolutionFrequency time.Duration) *ConnectionPool {
cp := &ConnectionPool{capacity: capacity, idleTimeout: idleTimeout, resolutionFrequency: dnsResolutionFrequency}
if name == "" || usedNames[name] {
return cp
}
usedNames[name] = true
stats.NewGaugeFunc(name+"Capacity", "Connection pool capacity", cp.Capacity)
stats.NewGaugeFunc(name+"Available", "Connection pool available", cp.Available)
stats.NewGaugeFunc(name+"Active", "Connection pool active", cp.Active)
stats.NewGaugeFunc(name+"InUse", "Connection pool in-use", cp.InUse)
stats.NewGaugeFunc(name+"MaxCap", "Connection pool max cap", cp.MaxCap)
stats.NewCounterFunc(name+"WaitCount", "Connection pool wait count", cp.WaitCount)
stats.NewCounterDurationFunc(name+"WaitTime", "Connection pool wait time", cp.WaitTime)
stats.NewGaugeDurationFunc(name+"IdleTimeout", "Connection pool idle timeout", cp.IdleTimeout)
stats.NewGaugeFunc(name+"IdleClosed", "Connection pool idle closed", cp.IdleClosed)
return cp
} | [
"func",
"NewConnectionPool",
"(",
"name",
"string",
",",
"capacity",
"int",
",",
"idleTimeout",
"time",
".",
"Duration",
",",
"dnsResolutionFrequency",
"time",
".",
"Duration",
")",
"*",
"ConnectionPool",
"{",
"cp",
":=",
"&",
"ConnectionPool",
"{",
"capacity",
":",
"capacity",
",",
"idleTimeout",
":",
"idleTimeout",
",",
"resolutionFrequency",
":",
"dnsResolutionFrequency",
"}",
"\n",
"if",
"name",
"==",
"\"",
"\"",
"||",
"usedNames",
"[",
"name",
"]",
"{",
"return",
"cp",
"\n",
"}",
"\n",
"usedNames",
"[",
"name",
"]",
"=",
"true",
"\n",
"stats",
".",
"NewGaugeFunc",
"(",
"name",
"+",
"\"",
"\"",
",",
"\"",
"\"",
",",
"cp",
".",
"Capacity",
")",
"\n",
"stats",
".",
"NewGaugeFunc",
"(",
"name",
"+",
"\"",
"\"",
",",
"\"",
"\"",
",",
"cp",
".",
"Available",
")",
"\n",
"stats",
".",
"NewGaugeFunc",
"(",
"name",
"+",
"\"",
"\"",
",",
"\"",
"\"",
",",
"cp",
".",
"Active",
")",
"\n",
"stats",
".",
"NewGaugeFunc",
"(",
"name",
"+",
"\"",
"\"",
",",
"\"",
"\"",
",",
"cp",
".",
"InUse",
")",
"\n",
"stats",
".",
"NewGaugeFunc",
"(",
"name",
"+",
"\"",
"\"",
",",
"\"",
"\"",
",",
"cp",
".",
"MaxCap",
")",
"\n",
"stats",
".",
"NewCounterFunc",
"(",
"name",
"+",
"\"",
"\"",
",",
"\"",
"\"",
",",
"cp",
".",
"WaitCount",
")",
"\n",
"stats",
".",
"NewCounterDurationFunc",
"(",
"name",
"+",
"\"",
"\"",
",",
"\"",
"\"",
",",
"cp",
".",
"WaitTime",
")",
"\n",
"stats",
".",
"NewGaugeDurationFunc",
"(",
"name",
"+",
"\"",
"\"",
",",
"\"",
"\"",
",",
"cp",
".",
"IdleTimeout",
")",
"\n",
"stats",
".",
"NewGaugeFunc",
"(",
"name",
"+",
"\"",
"\"",
",",
"\"",
"\"",
",",
"cp",
".",
"IdleClosed",
")",
"\n",
"return",
"cp",
"\n",
"}"
] | // NewConnectionPool creates a new ConnectionPool. The name is used
// to publish stats only. | [
"NewConnectionPool",
"creates",
"a",
"new",
"ConnectionPool",
".",
"The",
"name",
"is",
"used",
"to",
"publish",
"stats",
"only",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/dbconnpool/connection_pool.go#L72-L88 | train |
vitessio/vitess | go/vt/dbconnpool/connection_pool.go | connect | func (cp *ConnectionPool) connect() (pools.Resource, error) {
c, err := NewDBConnection(cp.info, cp.mysqlStats)
if err != nil {
return nil, err
}
return &PooledDBConnection{
DBConnection: c,
pool: cp,
}, nil
} | go | func (cp *ConnectionPool) connect() (pools.Resource, error) {
c, err := NewDBConnection(cp.info, cp.mysqlStats)
if err != nil {
return nil, err
}
return &PooledDBConnection{
DBConnection: c,
pool: cp,
}, nil
} | [
"func",
"(",
"cp",
"*",
"ConnectionPool",
")",
"connect",
"(",
")",
"(",
"pools",
".",
"Resource",
",",
"error",
")",
"{",
"c",
",",
"err",
":=",
"NewDBConnection",
"(",
"cp",
".",
"info",
",",
"cp",
".",
"mysqlStats",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"PooledDBConnection",
"{",
"DBConnection",
":",
"c",
",",
"pool",
":",
"cp",
",",
"}",
",",
"nil",
"\n",
"}"
] | // connect is used by the resource pool to create a new Resource. | [
"connect",
"is",
"used",
"by",
"the",
"resource",
"pool",
"to",
"create",
"a",
"new",
"Resource",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/dbconnpool/connection_pool.go#L171-L180 | train |
vitessio/vitess | go/vt/dbconnpool/connection_pool.go | Get | func (cp *ConnectionPool) Get(ctx context.Context) (*PooledDBConnection, error) {
p := cp.pool()
if p == nil {
return nil, ErrConnPoolClosed
}
r, err := p.Get(ctx)
if err != nil {
return nil, err
}
// Check that the RemoteAddr is still a valid Address
if cp.resolutionFrequency > 0 &&
cp.hostIsNotIP &&
!cp.validAddress(net.ParseIP(r.(*PooledDBConnection).RemoteAddr().String())) {
err := r.(*PooledDBConnection).Reconnect()
if err != nil {
p.Put(r)
return nil, err
}
}
return r.(*PooledDBConnection), nil
} | go | func (cp *ConnectionPool) Get(ctx context.Context) (*PooledDBConnection, error) {
p := cp.pool()
if p == nil {
return nil, ErrConnPoolClosed
}
r, err := p.Get(ctx)
if err != nil {
return nil, err
}
// Check that the RemoteAddr is still a valid Address
if cp.resolutionFrequency > 0 &&
cp.hostIsNotIP &&
!cp.validAddress(net.ParseIP(r.(*PooledDBConnection).RemoteAddr().String())) {
err := r.(*PooledDBConnection).Reconnect()
if err != nil {
p.Put(r)
return nil, err
}
}
return r.(*PooledDBConnection), nil
} | [
"func",
"(",
"cp",
"*",
"ConnectionPool",
")",
"Get",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"*",
"PooledDBConnection",
",",
"error",
")",
"{",
"p",
":=",
"cp",
".",
"pool",
"(",
")",
"\n",
"if",
"p",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrConnPoolClosed",
"\n",
"}",
"\n",
"r",
",",
"err",
":=",
"p",
".",
"Get",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Check that the RemoteAddr is still a valid Address",
"if",
"cp",
".",
"resolutionFrequency",
">",
"0",
"&&",
"cp",
".",
"hostIsNotIP",
"&&",
"!",
"cp",
".",
"validAddress",
"(",
"net",
".",
"ParseIP",
"(",
"r",
".",
"(",
"*",
"PooledDBConnection",
")",
".",
"RemoteAddr",
"(",
")",
".",
"String",
"(",
")",
")",
")",
"{",
"err",
":=",
"r",
".",
"(",
"*",
"PooledDBConnection",
")",
".",
"Reconnect",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"p",
".",
"Put",
"(",
"r",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"r",
".",
"(",
"*",
"PooledDBConnection",
")",
",",
"nil",
"\n",
"}"
] | // Get returns a connection.
// You must call Recycle on the PooledDBConnection once done. | [
"Get",
"returns",
"a",
"connection",
".",
"You",
"must",
"call",
"Recycle",
"on",
"the",
"PooledDBConnection",
"once",
"done",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/dbconnpool/connection_pool.go#L206-L227 | train |
vitessio/vitess | go/vt/dbconnpool/connection_pool.go | SetCapacity | func (cp *ConnectionPool) SetCapacity(capacity int) (err error) {
cp.mu.Lock()
defer cp.mu.Unlock()
if cp.connections != nil {
err = cp.connections.SetCapacity(capacity)
if err != nil {
return err
}
}
cp.capacity = capacity
return nil
} | go | func (cp *ConnectionPool) SetCapacity(capacity int) (err error) {
cp.mu.Lock()
defer cp.mu.Unlock()
if cp.connections != nil {
err = cp.connections.SetCapacity(capacity)
if err != nil {
return err
}
}
cp.capacity = capacity
return nil
} | [
"func",
"(",
"cp",
"*",
"ConnectionPool",
")",
"SetCapacity",
"(",
"capacity",
"int",
")",
"(",
"err",
"error",
")",
"{",
"cp",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"cp",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"cp",
".",
"connections",
"!=",
"nil",
"{",
"err",
"=",
"cp",
".",
"connections",
".",
"SetCapacity",
"(",
"capacity",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"cp",
".",
"capacity",
"=",
"capacity",
"\n",
"return",
"nil",
"\n",
"}"
] | // SetCapacity alters the size of the pool at runtime. | [
"SetCapacity",
"alters",
"the",
"size",
"of",
"the",
"pool",
"at",
"runtime",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/dbconnpool/connection_pool.go#L246-L257 | train |
vitessio/vitess | go/vt/dbconnpool/connection_pool.go | StatsJSON | func (cp *ConnectionPool) StatsJSON() string {
p := cp.pool()
if p == nil {
return "{}"
}
return p.StatsJSON()
} | go | func (cp *ConnectionPool) StatsJSON() string {
p := cp.pool()
if p == nil {
return "{}"
}
return p.StatsJSON()
} | [
"func",
"(",
"cp",
"*",
"ConnectionPool",
")",
"StatsJSON",
"(",
")",
"string",
"{",
"p",
":=",
"cp",
".",
"pool",
"(",
")",
"\n",
"if",
"p",
"==",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"p",
".",
"StatsJSON",
"(",
")",
"\n",
"}"
] | // StatsJSON returns the pool stats as a JSOn object. | [
"StatsJSON",
"returns",
"the",
"pool",
"stats",
"as",
"a",
"JSOn",
"object",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/vt/dbconnpool/connection_pool.go#L270-L276 | train |
vitessio/vitess | go/mysql/constants.go | IsConnErr | func IsConnErr(err error) bool {
if sqlErr, ok := err.(*SQLError); ok {
num := sqlErr.Number()
return (num >= CRUnknownError && num <= CRNamedPipeStateError) || num == ERQueryInterrupted
}
return false
} | go | func IsConnErr(err error) bool {
if sqlErr, ok := err.(*SQLError); ok {
num := sqlErr.Number()
return (num >= CRUnknownError && num <= CRNamedPipeStateError) || num == ERQueryInterrupted
}
return false
} | [
"func",
"IsConnErr",
"(",
"err",
"error",
")",
"bool",
"{",
"if",
"sqlErr",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"SQLError",
")",
";",
"ok",
"{",
"num",
":=",
"sqlErr",
".",
"Number",
"(",
")",
"\n",
"return",
"(",
"num",
">=",
"CRUnknownError",
"&&",
"num",
"<=",
"CRNamedPipeStateError",
")",
"||",
"num",
"==",
"ERQueryInterrupted",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // IsConnErr returns true if the error is a connection error. | [
"IsConnErr",
"returns",
"true",
"if",
"the",
"error",
"is",
"a",
"connection",
"error",
"."
] | d568817542a413611801aa17a1c213aa95592182 | https://github.com/vitessio/vitess/blob/d568817542a413611801aa17a1c213aa95592182/go/mysql/constants.go#L548-L554 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.