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
list | docstring
stringlengths 6
2.61k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 85
252
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
pilosa/pilosa
|
ctl/import.go
|
bufferValues
|
func (cmd *ImportCommand) bufferValues(ctx context.Context, useColumnKeys bool, path string) error {
a := make([]pilosa.FieldValue, 0, cmd.BufferSize)
var r *csv.Reader
if path != "-" {
// Open file for reading.
f, err := os.Open(path)
if err != nil {
return errors.Wrap(err, "opening file")
}
defer f.Close()
// Read rows as bits.
r = csv.NewReader(f)
} else {
r = csv.NewReader(cmd.Stdin)
}
r.FieldsPerRecord = -1
rnum := 0
for {
rnum++
// Read CSV row.
record, err := r.Read()
if err == io.EOF {
break
} else if err != nil {
return errors.Wrap(err, "reading")
}
// Ignore blank rows.
if record[0] == "" {
continue
} else if len(record) < 2 {
return fmt.Errorf("bad column count on row %d: col=%d", rnum, len(record))
}
var val pilosa.FieldValue
// Parse column id.
if useColumnKeys {
val.ColumnKey = record[0]
} else {
if val.ColumnID, err = strconv.ParseUint(record[0], 10, 64); err != nil {
return fmt.Errorf("invalid column id on row %d: %q", rnum, record[0])
}
}
// Parse FieldValue.
value, err := strconv.ParseInt(record[1], 10, 64)
if err != nil {
return fmt.Errorf("invalid value on row %d: %q", rnum, record[1])
}
val.Value = value
a = append(a, val)
// If we've reached the buffer size then import FieldValues.
if len(a) == cmd.BufferSize {
if err := cmd.importValues(ctx, useColumnKeys, a); err != nil {
return err
}
a = a[:0]
}
}
// If there are still values in the buffer then flush them.
return cmd.importValues(ctx, useColumnKeys, a)
}
|
go
|
func (cmd *ImportCommand) bufferValues(ctx context.Context, useColumnKeys bool, path string) error {
a := make([]pilosa.FieldValue, 0, cmd.BufferSize)
var r *csv.Reader
if path != "-" {
// Open file for reading.
f, err := os.Open(path)
if err != nil {
return errors.Wrap(err, "opening file")
}
defer f.Close()
// Read rows as bits.
r = csv.NewReader(f)
} else {
r = csv.NewReader(cmd.Stdin)
}
r.FieldsPerRecord = -1
rnum := 0
for {
rnum++
// Read CSV row.
record, err := r.Read()
if err == io.EOF {
break
} else if err != nil {
return errors.Wrap(err, "reading")
}
// Ignore blank rows.
if record[0] == "" {
continue
} else if len(record) < 2 {
return fmt.Errorf("bad column count on row %d: col=%d", rnum, len(record))
}
var val pilosa.FieldValue
// Parse column id.
if useColumnKeys {
val.ColumnKey = record[0]
} else {
if val.ColumnID, err = strconv.ParseUint(record[0], 10, 64); err != nil {
return fmt.Errorf("invalid column id on row %d: %q", rnum, record[0])
}
}
// Parse FieldValue.
value, err := strconv.ParseInt(record[1], 10, 64)
if err != nil {
return fmt.Errorf("invalid value on row %d: %q", rnum, record[1])
}
val.Value = value
a = append(a, val)
// If we've reached the buffer size then import FieldValues.
if len(a) == cmd.BufferSize {
if err := cmd.importValues(ctx, useColumnKeys, a); err != nil {
return err
}
a = a[:0]
}
}
// If there are still values in the buffer then flush them.
return cmd.importValues(ctx, useColumnKeys, a)
}
|
[
"func",
"(",
"cmd",
"*",
"ImportCommand",
")",
"bufferValues",
"(",
"ctx",
"context",
".",
"Context",
",",
"useColumnKeys",
"bool",
",",
"path",
"string",
")",
"error",
"{",
"a",
":=",
"make",
"(",
"[",
"]",
"pilosa",
".",
"FieldValue",
",",
"0",
",",
"cmd",
".",
"BufferSize",
")",
"\n\n",
"var",
"r",
"*",
"csv",
".",
"Reader",
"\n\n",
"if",
"path",
"!=",
"\"",
"\"",
"{",
"// Open file for reading.",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"// Read rows as bits.",
"r",
"=",
"csv",
".",
"NewReader",
"(",
"f",
")",
"\n",
"}",
"else",
"{",
"r",
"=",
"csv",
".",
"NewReader",
"(",
"cmd",
".",
"Stdin",
")",
"\n",
"}",
"\n\n",
"r",
".",
"FieldsPerRecord",
"=",
"-",
"1",
"\n",
"rnum",
":=",
"0",
"\n",
"for",
"{",
"rnum",
"++",
"\n\n",
"// Read CSV row.",
"record",
",",
"err",
":=",
"r",
".",
"Read",
"(",
")",
"\n",
"if",
"err",
"==",
"io",
".",
"EOF",
"{",
"break",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Ignore blank rows.",
"if",
"record",
"[",
"0",
"]",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"else",
"if",
"len",
"(",
"record",
")",
"<",
"2",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"rnum",
",",
"len",
"(",
"record",
")",
")",
"\n",
"}",
"\n\n",
"var",
"val",
"pilosa",
".",
"FieldValue",
"\n\n",
"// Parse column id.",
"if",
"useColumnKeys",
"{",
"val",
".",
"ColumnKey",
"=",
"record",
"[",
"0",
"]",
"\n",
"}",
"else",
"{",
"if",
"val",
".",
"ColumnID",
",",
"err",
"=",
"strconv",
".",
"ParseUint",
"(",
"record",
"[",
"0",
"]",
",",
"10",
",",
"64",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"rnum",
",",
"record",
"[",
"0",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Parse FieldValue.",
"value",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"record",
"[",
"1",
"]",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"rnum",
",",
"record",
"[",
"1",
"]",
")",
"\n",
"}",
"\n",
"val",
".",
"Value",
"=",
"value",
"\n\n",
"a",
"=",
"append",
"(",
"a",
",",
"val",
")",
"\n\n",
"// If we've reached the buffer size then import FieldValues.",
"if",
"len",
"(",
"a",
")",
"==",
"cmd",
".",
"BufferSize",
"{",
"if",
"err",
":=",
"cmd",
".",
"importValues",
"(",
"ctx",
",",
"useColumnKeys",
",",
"a",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"a",
"=",
"a",
"[",
":",
"0",
"]",
"\n",
"}",
"\n",
"}",
"\n\n",
"// If there are still values in the buffer then flush them.",
"return",
"cmd",
".",
"importValues",
"(",
"ctx",
",",
"useColumnKeys",
",",
"a",
")",
"\n",
"}"
] |
// bufferValues buffers slices of FieldValues to be imported as a batch.
|
[
"bufferValues",
"buffers",
"slices",
"of",
"FieldValues",
"to",
"be",
"imported",
"as",
"a",
"batch",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/ctl/import.go#L289-L359
|
train
|
pilosa/pilosa
|
ctl/import.go
|
importValues
|
func (cmd *ImportCommand) importValues(ctx context.Context, useColumnKeys bool, vals []pilosa.FieldValue) error {
logger := log.New(cmd.Stderr, "", log.LstdFlags)
// If keys are used, all values are sent to the primary translate store (i.e. coordinator).
if useColumnKeys {
logger.Printf("importing keyed values: n=%d", len(vals))
if err := cmd.client.ImportValueK(ctx, cmd.Index, cmd.Field, vals); err != nil {
return errors.Wrap(err, "importing keys")
}
return nil
}
// Group vals by shard.
logger.Printf("grouping %d vals", len(vals))
valsByShard := http.FieldValues(vals).GroupByShard()
// Parse path into FieldValues.
for shard, vals := range valsByShard {
if cmd.Sort {
sort.Sort(http.FieldValues(vals))
}
logger.Printf("importing shard: %d, n=%d", shard, len(vals))
if err := cmd.client.ImportValue(ctx, cmd.Index, cmd.Field, shard, vals, pilosa.OptImportOptionsClear(cmd.Clear)); err != nil {
return errors.Wrap(err, "importing values")
}
}
return nil
}
|
go
|
func (cmd *ImportCommand) importValues(ctx context.Context, useColumnKeys bool, vals []pilosa.FieldValue) error {
logger := log.New(cmd.Stderr, "", log.LstdFlags)
// If keys are used, all values are sent to the primary translate store (i.e. coordinator).
if useColumnKeys {
logger.Printf("importing keyed values: n=%d", len(vals))
if err := cmd.client.ImportValueK(ctx, cmd.Index, cmd.Field, vals); err != nil {
return errors.Wrap(err, "importing keys")
}
return nil
}
// Group vals by shard.
logger.Printf("grouping %d vals", len(vals))
valsByShard := http.FieldValues(vals).GroupByShard()
// Parse path into FieldValues.
for shard, vals := range valsByShard {
if cmd.Sort {
sort.Sort(http.FieldValues(vals))
}
logger.Printf("importing shard: %d, n=%d", shard, len(vals))
if err := cmd.client.ImportValue(ctx, cmd.Index, cmd.Field, shard, vals, pilosa.OptImportOptionsClear(cmd.Clear)); err != nil {
return errors.Wrap(err, "importing values")
}
}
return nil
}
|
[
"func",
"(",
"cmd",
"*",
"ImportCommand",
")",
"importValues",
"(",
"ctx",
"context",
".",
"Context",
",",
"useColumnKeys",
"bool",
",",
"vals",
"[",
"]",
"pilosa",
".",
"FieldValue",
")",
"error",
"{",
"logger",
":=",
"log",
".",
"New",
"(",
"cmd",
".",
"Stderr",
",",
"\"",
"\"",
",",
"log",
".",
"LstdFlags",
")",
"\n\n",
"// If keys are used, all values are sent to the primary translate store (i.e. coordinator).",
"if",
"useColumnKeys",
"{",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"len",
"(",
"vals",
")",
")",
"\n",
"if",
"err",
":=",
"cmd",
".",
"client",
".",
"ImportValueK",
"(",
"ctx",
",",
"cmd",
".",
"Index",
",",
"cmd",
".",
"Field",
",",
"vals",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Group vals by shard.",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"len",
"(",
"vals",
")",
")",
"\n",
"valsByShard",
":=",
"http",
".",
"FieldValues",
"(",
"vals",
")",
".",
"GroupByShard",
"(",
")",
"\n\n",
"// Parse path into FieldValues.",
"for",
"shard",
",",
"vals",
":=",
"range",
"valsByShard",
"{",
"if",
"cmd",
".",
"Sort",
"{",
"sort",
".",
"Sort",
"(",
"http",
".",
"FieldValues",
"(",
"vals",
")",
")",
"\n",
"}",
"\n\n",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"shard",
",",
"len",
"(",
"vals",
")",
")",
"\n",
"if",
"err",
":=",
"cmd",
".",
"client",
".",
"ImportValue",
"(",
"ctx",
",",
"cmd",
".",
"Index",
",",
"cmd",
".",
"Field",
",",
"shard",
",",
"vals",
",",
"pilosa",
".",
"OptImportOptionsClear",
"(",
"cmd",
".",
"Clear",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// importValues sends batches of FieldValues to the server.
|
[
"importValues",
"sends",
"batches",
"of",
"FieldValues",
"to",
"the",
"server",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/ctl/import.go#L362-L391
|
train
|
pilosa/pilosa
|
pql/ast.go
|
endCall
|
func (q *Query) endCall() *Call {
elem := q.callStack[len(q.callStack)-1]
q.callStack[len(q.callStack)-1] = nil
q.callStack = q.callStack[:len(q.callStack)-1]
return elem.call
}
|
go
|
func (q *Query) endCall() *Call {
elem := q.callStack[len(q.callStack)-1]
q.callStack[len(q.callStack)-1] = nil
q.callStack = q.callStack[:len(q.callStack)-1]
return elem.call
}
|
[
"func",
"(",
"q",
"*",
"Query",
")",
"endCall",
"(",
")",
"*",
"Call",
"{",
"elem",
":=",
"q",
".",
"callStack",
"[",
"len",
"(",
"q",
".",
"callStack",
")",
"-",
"1",
"]",
"\n",
"q",
".",
"callStack",
"[",
"len",
"(",
"q",
".",
"callStack",
")",
"-",
"1",
"]",
"=",
"nil",
"\n",
"q",
".",
"callStack",
"=",
"q",
".",
"callStack",
"[",
":",
"len",
"(",
"q",
".",
"callStack",
")",
"-",
"1",
"]",
"\n",
"return",
"elem",
".",
"call",
"\n",
"}"
] |
// endCall removes the last element from the call stack and returns the call.
|
[
"endCall",
"removes",
"the",
"last",
"element",
"from",
"the",
"call",
"stack",
"and",
"returns",
"the",
"call",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pql/ast.go#L46-L51
|
train
|
pilosa/pilosa
|
pql/ast.go
|
WriteCallN
|
func (q *Query) WriteCallN() int {
var n int
for _, call := range q.Calls {
switch call.Name {
case "Set", "Clear", "SetRowAttrs", "SetColumnAttrs":
n++
}
}
return n
}
|
go
|
func (q *Query) WriteCallN() int {
var n int
for _, call := range q.Calls {
switch call.Name {
case "Set", "Clear", "SetRowAttrs", "SetColumnAttrs":
n++
}
}
return n
}
|
[
"func",
"(",
"q",
"*",
"Query",
")",
"WriteCallN",
"(",
")",
"int",
"{",
"var",
"n",
"int",
"\n",
"for",
"_",
",",
"call",
":=",
"range",
"q",
".",
"Calls",
"{",
"switch",
"call",
".",
"Name",
"{",
"case",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
":",
"n",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"n",
"\n",
"}"
] |
// WriteCallN returns the number of mutating calls.
|
[
"WriteCallN",
"returns",
"the",
"number",
"of",
"mutating",
"calls",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pql/ast.go#L235-L244
|
train
|
pilosa/pilosa
|
pql/ast.go
|
String
|
func (q *Query) String() string {
a := make([]string, len(q.Calls))
for i, call := range q.Calls {
a[i] = call.String()
}
return strings.Join(a, "\n")
}
|
go
|
func (q *Query) String() string {
a := make([]string, len(q.Calls))
for i, call := range q.Calls {
a[i] = call.String()
}
return strings.Join(a, "\n")
}
|
[
"func",
"(",
"q",
"*",
"Query",
")",
"String",
"(",
")",
"string",
"{",
"a",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"q",
".",
"Calls",
")",
")",
"\n",
"for",
"i",
",",
"call",
":=",
"range",
"q",
".",
"Calls",
"{",
"a",
"[",
"i",
"]",
"=",
"call",
".",
"String",
"(",
")",
"\n",
"}",
"\n",
"return",
"strings",
".",
"Join",
"(",
"a",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"}"
] |
// String returns a string representation of the query.
|
[
"String",
"returns",
"a",
"string",
"representation",
"of",
"the",
"query",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pql/ast.go#L247-L253
|
train
|
pilosa/pilosa
|
pql/ast.go
|
UintArg
|
func (c *Call) UintArg(key string) (uint64, bool, error) {
val, ok := c.Args[key]
if !ok {
return 0, false, nil
}
switch tval := val.(type) {
case int64:
if tval < 0 {
return 0, true, fmt.Errorf("value for '%s' must be positive, but got %v", key, tval)
}
return uint64(tval), true, nil
case uint64:
return tval, true, nil
default:
return 0, true, fmt.Errorf("could not convert %v of type %T to uint64 in Call.UintArg", tval, tval)
}
}
|
go
|
func (c *Call) UintArg(key string) (uint64, bool, error) {
val, ok := c.Args[key]
if !ok {
return 0, false, nil
}
switch tval := val.(type) {
case int64:
if tval < 0 {
return 0, true, fmt.Errorf("value for '%s' must be positive, but got %v", key, tval)
}
return uint64(tval), true, nil
case uint64:
return tval, true, nil
default:
return 0, true, fmt.Errorf("could not convert %v of type %T to uint64 in Call.UintArg", tval, tval)
}
}
|
[
"func",
"(",
"c",
"*",
"Call",
")",
"UintArg",
"(",
"key",
"string",
")",
"(",
"uint64",
",",
"bool",
",",
"error",
")",
"{",
"val",
",",
"ok",
":=",
"c",
".",
"Args",
"[",
"key",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"0",
",",
"false",
",",
"nil",
"\n",
"}",
"\n",
"switch",
"tval",
":=",
"val",
".",
"(",
"type",
")",
"{",
"case",
"int64",
":",
"if",
"tval",
"<",
"0",
"{",
"return",
"0",
",",
"true",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"key",
",",
"tval",
")",
"\n",
"}",
"\n",
"return",
"uint64",
"(",
"tval",
")",
",",
"true",
",",
"nil",
"\n",
"case",
"uint64",
":",
"return",
"tval",
",",
"true",
",",
"nil",
"\n",
"default",
":",
"return",
"0",
",",
"true",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"tval",
",",
"tval",
")",
"\n",
"}",
"\n",
"}"
] |
// UintArg is for reading the value at key from call.Args as a uint64. If the
// key is not in Call.Args, the value of the returned bool will be false, and
// the error will be nil. The value is assumed to be a uint64 or an int64 and
// then cast to a uint64. An error is returned if the value is not an int64 or
// uint64.
|
[
"UintArg",
"is",
"for",
"reading",
"the",
"value",
"at",
"key",
"from",
"call",
".",
"Args",
"as",
"a",
"uint64",
".",
"If",
"the",
"key",
"is",
"not",
"in",
"Call",
".",
"Args",
"the",
"value",
"of",
"the",
"returned",
"bool",
"will",
"be",
"false",
"and",
"the",
"error",
"will",
"be",
"nil",
".",
"The",
"value",
"is",
"assumed",
"to",
"be",
"a",
"uint64",
"or",
"an",
"int64",
"and",
"then",
"cast",
"to",
"a",
"uint64",
".",
"An",
"error",
"is",
"returned",
"if",
"the",
"value",
"is",
"not",
"an",
"int64",
"or",
"uint64",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pql/ast.go#L315-L331
|
train
|
pilosa/pilosa
|
pql/ast.go
|
CallArg
|
func (c *Call) CallArg(key string) (*Call, bool, error) {
val, ok := c.Args[key]
if !ok {
return nil, false, nil
}
switch tval := val.(type) {
case *Call:
return tval, true, nil
default:
return nil, true, fmt.Errorf("could not convert %v of type %T to Call in Call.CallArg", tval, tval)
}
}
|
go
|
func (c *Call) CallArg(key string) (*Call, bool, error) {
val, ok := c.Args[key]
if !ok {
return nil, false, nil
}
switch tval := val.(type) {
case *Call:
return tval, true, nil
default:
return nil, true, fmt.Errorf("could not convert %v of type %T to Call in Call.CallArg", tval, tval)
}
}
|
[
"func",
"(",
"c",
"*",
"Call",
")",
"CallArg",
"(",
"key",
"string",
")",
"(",
"*",
"Call",
",",
"bool",
",",
"error",
")",
"{",
"val",
",",
"ok",
":=",
"c",
".",
"Args",
"[",
"key",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"false",
",",
"nil",
"\n",
"}",
"\n",
"switch",
"tval",
":=",
"val",
".",
"(",
"type",
")",
"{",
"case",
"*",
"Call",
":",
"return",
"tval",
",",
"true",
",",
"nil",
"\n",
"default",
":",
"return",
"nil",
",",
"true",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"tval",
",",
"tval",
")",
"\n",
"}",
"\n",
"}"
] |
// CallArg is for reading the value at key from call.Args as a Call. If the
// key is not in Call.Args, the value of the returned value will be nil, and
// the error will be nil. An error is returned if the value is not a Call.
|
[
"CallArg",
"is",
"for",
"reading",
"the",
"value",
"at",
"key",
"from",
"call",
".",
"Args",
"as",
"a",
"Call",
".",
"If",
"the",
"key",
"is",
"not",
"in",
"Call",
".",
"Args",
"the",
"value",
"of",
"the",
"returned",
"value",
"will",
"be",
"nil",
"and",
"the",
"error",
"will",
"be",
"nil",
".",
"An",
"error",
"is",
"returned",
"if",
"the",
"value",
"is",
"not",
"a",
"Call",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pql/ast.go#L380-L391
|
train
|
pilosa/pilosa
|
pql/ast.go
|
keys
|
func (c *Call) keys() []string {
a := make([]string, 0, len(c.Args))
for k := range c.Args {
a = append(a, k)
}
sort.Strings(a)
return a
}
|
go
|
func (c *Call) keys() []string {
a := make([]string, 0, len(c.Args))
for k := range c.Args {
a = append(a, k)
}
sort.Strings(a)
return a
}
|
[
"func",
"(",
"c",
"*",
"Call",
")",
"keys",
"(",
")",
"[",
"]",
"string",
"{",
"a",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"c",
".",
"Args",
")",
")",
"\n",
"for",
"k",
":=",
"range",
"c",
".",
"Args",
"{",
"a",
"=",
"append",
"(",
"a",
",",
"k",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"a",
")",
"\n",
"return",
"a",
"\n",
"}"
] |
// keys returns a list of argument keys in sorted order.
|
[
"keys",
"returns",
"a",
"list",
"of",
"argument",
"keys",
"in",
"sorted",
"order",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pql/ast.go#L394-L401
|
train
|
pilosa/pilosa
|
pql/ast.go
|
String
|
func (c *Call) String() string {
var buf bytes.Buffer
// Write name.
if c.Name != "" {
buf.WriteString(c.Name)
} else {
buf.WriteString("!UNNAMED")
}
// Write opening.
buf.WriteByte('(')
// Write child list.
for i, child := range c.Children {
if i > 0 {
buf.WriteString(", ")
}
buf.WriteString(child.String())
}
// Separate children and args, if necessary.
if len(c.Children) > 0 && len(c.Args) > 0 {
buf.WriteString(", ")
}
// Write arguments in key order.
for i, key := range c.keys() {
if i > 0 {
buf.WriteString(", ")
}
// If the Arg value is a Condition, then don't include
// the equal sign in the string representation.
switch v := c.Args[key].(type) {
case *Condition:
fmt.Fprintf(&buf, "%v %s", key, v.String())
default:
fmt.Fprintf(&buf, "%v=%s", key, formatValue(v))
}
}
// Write closing.
buf.WriteByte(')')
return buf.String()
}
|
go
|
func (c *Call) String() string {
var buf bytes.Buffer
// Write name.
if c.Name != "" {
buf.WriteString(c.Name)
} else {
buf.WriteString("!UNNAMED")
}
// Write opening.
buf.WriteByte('(')
// Write child list.
for i, child := range c.Children {
if i > 0 {
buf.WriteString(", ")
}
buf.WriteString(child.String())
}
// Separate children and args, if necessary.
if len(c.Children) > 0 && len(c.Args) > 0 {
buf.WriteString(", ")
}
// Write arguments in key order.
for i, key := range c.keys() {
if i > 0 {
buf.WriteString(", ")
}
// If the Arg value is a Condition, then don't include
// the equal sign in the string representation.
switch v := c.Args[key].(type) {
case *Condition:
fmt.Fprintf(&buf, "%v %s", key, v.String())
default:
fmt.Fprintf(&buf, "%v=%s", key, formatValue(v))
}
}
// Write closing.
buf.WriteByte(')')
return buf.String()
}
|
[
"func",
"(",
"c",
"*",
"Call",
")",
"String",
"(",
")",
"string",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n\n",
"// Write name.",
"if",
"c",
".",
"Name",
"!=",
"\"",
"\"",
"{",
"buf",
".",
"WriteString",
"(",
"c",
".",
"Name",
")",
"\n",
"}",
"else",
"{",
"buf",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Write opening.",
"buf",
".",
"WriteByte",
"(",
"'('",
")",
"\n\n",
"// Write child list.",
"for",
"i",
",",
"child",
":=",
"range",
"c",
".",
"Children",
"{",
"if",
"i",
">",
"0",
"{",
"buf",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"buf",
".",
"WriteString",
"(",
"child",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n\n",
"// Separate children and args, if necessary.",
"if",
"len",
"(",
"c",
".",
"Children",
")",
">",
"0",
"&&",
"len",
"(",
"c",
".",
"Args",
")",
">",
"0",
"{",
"buf",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Write arguments in key order.",
"for",
"i",
",",
"key",
":=",
"range",
"c",
".",
"keys",
"(",
")",
"{",
"if",
"i",
">",
"0",
"{",
"buf",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// If the Arg value is a Condition, then don't include",
"// the equal sign in the string representation.",
"switch",
"v",
":=",
"c",
".",
"Args",
"[",
"key",
"]",
".",
"(",
"type",
")",
"{",
"case",
"*",
"Condition",
":",
"fmt",
".",
"Fprintf",
"(",
"&",
"buf",
",",
"\"",
"\"",
",",
"key",
",",
"v",
".",
"String",
"(",
")",
")",
"\n",
"default",
":",
"fmt",
".",
"Fprintf",
"(",
"&",
"buf",
",",
"\"",
"\"",
",",
"key",
",",
"formatValue",
"(",
"v",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Write closing.",
"buf",
".",
"WriteByte",
"(",
"')'",
")",
"\n\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] |
// String returns the string representation of the call.
|
[
"String",
"returns",
"the",
"string",
"representation",
"of",
"the",
"call",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pql/ast.go#L423-L468
|
train
|
pilosa/pilosa
|
pql/ast.go
|
HasConditionArg
|
func (c *Call) HasConditionArg() bool {
for _, v := range c.Args {
if _, ok := v.(*Condition); ok {
return true
}
}
return false
}
|
go
|
func (c *Call) HasConditionArg() bool {
for _, v := range c.Args {
if _, ok := v.(*Condition); ok {
return true
}
}
return false
}
|
[
"func",
"(",
"c",
"*",
"Call",
")",
"HasConditionArg",
"(",
")",
"bool",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"c",
".",
"Args",
"{",
"if",
"_",
",",
"ok",
":=",
"v",
".",
"(",
"*",
"Condition",
")",
";",
"ok",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// HasConditionArg returns true if any arg is a conditional.
|
[
"HasConditionArg",
"returns",
"true",
"if",
"any",
"arg",
"is",
"a",
"conditional",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pql/ast.go#L471-L478
|
train
|
pilosa/pilosa
|
pql/ast.go
|
String
|
func (cond *Condition) String() string {
return fmt.Sprintf("%s %s", cond.Op.String(), formatValue(cond.Value))
}
|
go
|
func (cond *Condition) String() string {
return fmt.Sprintf("%s %s", cond.Op.String(), formatValue(cond.Value))
}
|
[
"func",
"(",
"cond",
"*",
"Condition",
")",
"String",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"cond",
".",
"Op",
".",
"String",
"(",
")",
",",
"formatValue",
"(",
"cond",
".",
"Value",
")",
")",
"\n",
"}"
] |
// String returns the string representation of the condition.
|
[
"String",
"returns",
"the",
"string",
"representation",
"of",
"the",
"condition",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pql/ast.go#L488-L490
|
train
|
pilosa/pilosa
|
pql/ast.go
|
CopyArgs
|
func CopyArgs(m map[string]interface{}) map[string]interface{} {
other := make(map[string]interface{}, len(m))
for k, v := range m {
other[k] = v
}
return other
}
|
go
|
func CopyArgs(m map[string]interface{}) map[string]interface{} {
other := make(map[string]interface{}, len(m))
for k, v := range m {
other[k] = v
}
return other
}
|
[
"func",
"CopyArgs",
"(",
"m",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"other",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"len",
"(",
"m",
")",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"m",
"{",
"other",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"return",
"other",
"\n",
"}"
] |
// CopyArgs returns a copy of m.
|
[
"CopyArgs",
"returns",
"a",
"copy",
"of",
"m",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pql/ast.go#L535-L541
|
train
|
pilosa/pilosa
|
handler.go
|
MarshalJSON
|
func (resp *QueryResponse) MarshalJSON() ([]byte, error) {
if resp.Err != nil {
return json.Marshal(struct {
Err string `json:"error"`
}{Err: resp.Err.Error()})
}
return json.Marshal(struct {
Results []interface{} `json:"results"`
ColumnAttrSets []*ColumnAttrSet `json:"columnAttrs,omitempty"`
}{
Results: resp.Results,
ColumnAttrSets: resp.ColumnAttrSets,
})
}
|
go
|
func (resp *QueryResponse) MarshalJSON() ([]byte, error) {
if resp.Err != nil {
return json.Marshal(struct {
Err string `json:"error"`
}{Err: resp.Err.Error()})
}
return json.Marshal(struct {
Results []interface{} `json:"results"`
ColumnAttrSets []*ColumnAttrSet `json:"columnAttrs,omitempty"`
}{
Results: resp.Results,
ColumnAttrSets: resp.ColumnAttrSets,
})
}
|
[
"func",
"(",
"resp",
"*",
"QueryResponse",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"resp",
".",
"Err",
"!=",
"nil",
"{",
"return",
"json",
".",
"Marshal",
"(",
"struct",
"{",
"Err",
"string",
"`json:\"error\"`",
"\n",
"}",
"{",
"Err",
":",
"resp",
".",
"Err",
".",
"Error",
"(",
")",
"}",
")",
"\n",
"}",
"\n\n",
"return",
"json",
".",
"Marshal",
"(",
"struct",
"{",
"Results",
"[",
"]",
"interface",
"{",
"}",
"`json:\"results\"`",
"\n",
"ColumnAttrSets",
"[",
"]",
"*",
"ColumnAttrSet",
"`json:\"columnAttrs,omitempty\"`",
"\n",
"}",
"{",
"Results",
":",
"resp",
".",
"Results",
",",
"ColumnAttrSets",
":",
"resp",
".",
"ColumnAttrSets",
",",
"}",
")",
"\n",
"}"
] |
// MarshalJSON marshals QueryResponse into a JSON-encoded byte slice
|
[
"MarshalJSON",
"marshals",
"QueryResponse",
"into",
"a",
"JSON",
"-",
"encoded",
"byte",
"slice"
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/handler.go#L61-L75
|
train
|
pilosa/pilosa
|
pql/parser.go
|
ParseString
|
func ParseString(s string) (*Query, error) {
return NewParser(strings.NewReader(s)).Parse()
}
|
go
|
func ParseString(s string) (*Query, error) {
return NewParser(strings.NewReader(s)).Parse()
}
|
[
"func",
"ParseString",
"(",
"s",
"string",
")",
"(",
"*",
"Query",
",",
"error",
")",
"{",
"return",
"NewParser",
"(",
"strings",
".",
"NewReader",
"(",
"s",
")",
")",
".",
"Parse",
"(",
")",
"\n",
"}"
] |
// ParseString parses s into a query.
|
[
"ParseString",
"parses",
"s",
"into",
"a",
"query",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pql/parser.go#L48-L50
|
train
|
pilosa/pilosa
|
pql/parser.go
|
Parse
|
func (p *parser) Parse() (*Query, error) {
buf, err := ioutil.ReadAll(p.r)
if err != nil {
return nil, errors.Wrap(err, "reading buffer to parse")
}
p.PQL = PQL{
Buffer: string(buf),
}
p.Init()
err = p.PQL.Parse()
if err != nil {
return nil, errors.Wrap(err, "parsing")
}
// Handle specific panics from the parser and return them as errors.
var v interface{}
func() {
defer func() { v = recover() }()
p.Execute()
}()
if v != nil {
if strings.HasPrefix(v.(string), duplicateArgErrorMessage) {
return nil, fmt.Errorf("%s", v)
} else {
panic(v)
}
}
return &p.Query, nil
}
|
go
|
func (p *parser) Parse() (*Query, error) {
buf, err := ioutil.ReadAll(p.r)
if err != nil {
return nil, errors.Wrap(err, "reading buffer to parse")
}
p.PQL = PQL{
Buffer: string(buf),
}
p.Init()
err = p.PQL.Parse()
if err != nil {
return nil, errors.Wrap(err, "parsing")
}
// Handle specific panics from the parser and return them as errors.
var v interface{}
func() {
defer func() { v = recover() }()
p.Execute()
}()
if v != nil {
if strings.HasPrefix(v.(string), duplicateArgErrorMessage) {
return nil, fmt.Errorf("%s", v)
} else {
panic(v)
}
}
return &p.Query, nil
}
|
[
"func",
"(",
"p",
"*",
"parser",
")",
"Parse",
"(",
")",
"(",
"*",
"Query",
",",
"error",
")",
"{",
"buf",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"p",
".",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"p",
".",
"PQL",
"=",
"PQL",
"{",
"Buffer",
":",
"string",
"(",
"buf",
")",
",",
"}",
"\n",
"p",
".",
"Init",
"(",
")",
"\n",
"err",
"=",
"p",
".",
"PQL",
".",
"Parse",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Handle specific panics from the parser and return them as errors.",
"var",
"v",
"interface",
"{",
"}",
"\n",
"func",
"(",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"v",
"=",
"recover",
"(",
")",
"}",
"(",
")",
"\n",
"p",
".",
"Execute",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"if",
"v",
"!=",
"nil",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"v",
".",
"(",
"string",
")",
",",
"duplicateArgErrorMessage",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"v",
")",
"\n",
"}",
"else",
"{",
"panic",
"(",
"v",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"&",
"p",
".",
"Query",
",",
"nil",
"\n",
"}"
] |
// Parse parses the next node in the query.
|
[
"Parse",
"parses",
"the",
"next",
"node",
"in",
"the",
"query",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pql/parser.go#L53-L82
|
train
|
pilosa/pilosa
|
http/handler.go
|
OptHandlerCloseTimeout
|
func OptHandlerCloseTimeout(d time.Duration) handlerOption {
return func(h *Handler) error {
h.closeTimeout = d
return nil
}
}
|
go
|
func OptHandlerCloseTimeout(d time.Duration) handlerOption {
return func(h *Handler) error {
h.closeTimeout = d
return nil
}
}
|
[
"func",
"OptHandlerCloseTimeout",
"(",
"d",
"time",
".",
"Duration",
")",
"handlerOption",
"{",
"return",
"func",
"(",
"h",
"*",
"Handler",
")",
"error",
"{",
"h",
".",
"closeTimeout",
"=",
"d",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] |
// OptHandlerCloseTimeout controls how long to wait for the http Server to
// shutdown cleanly before forcibly destroying it. Default is 30 seconds.
|
[
"OptHandlerCloseTimeout",
"controls",
"how",
"long",
"to",
"wait",
"for",
"the",
"http",
"Server",
"to",
"shutdown",
"cleanly",
"before",
"forcibly",
"destroying",
"it",
".",
"Default",
"is",
"30",
"seconds",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L114-L119
|
train
|
pilosa/pilosa
|
http/handler.go
|
NewHandler
|
func NewHandler(opts ...handlerOption) (*Handler, error) {
handler := &Handler{
logger: logger.NopLogger,
closeTimeout: time.Second * 30,
}
handler.Handler = newRouter(handler)
handler.populateValidators()
for _, opt := range opts {
err := opt(handler)
if err != nil {
return nil, errors.Wrap(err, "applying option")
}
}
if handler.api == nil {
return nil, errors.New("must pass OptHandlerAPI")
}
if handler.ln == nil {
return nil, errors.New("must pass OptHandlerListener")
}
handler.server = &http.Server{Handler: handler}
return handler, nil
}
|
go
|
func NewHandler(opts ...handlerOption) (*Handler, error) {
handler := &Handler{
logger: logger.NopLogger,
closeTimeout: time.Second * 30,
}
handler.Handler = newRouter(handler)
handler.populateValidators()
for _, opt := range opts {
err := opt(handler)
if err != nil {
return nil, errors.Wrap(err, "applying option")
}
}
if handler.api == nil {
return nil, errors.New("must pass OptHandlerAPI")
}
if handler.ln == nil {
return nil, errors.New("must pass OptHandlerListener")
}
handler.server = &http.Server{Handler: handler}
return handler, nil
}
|
[
"func",
"NewHandler",
"(",
"opts",
"...",
"handlerOption",
")",
"(",
"*",
"Handler",
",",
"error",
")",
"{",
"handler",
":=",
"&",
"Handler",
"{",
"logger",
":",
"logger",
".",
"NopLogger",
",",
"closeTimeout",
":",
"time",
".",
"Second",
"*",
"30",
",",
"}",
"\n",
"handler",
".",
"Handler",
"=",
"newRouter",
"(",
"handler",
")",
"\n",
"handler",
".",
"populateValidators",
"(",
")",
"\n\n",
"for",
"_",
",",
"opt",
":=",
"range",
"opts",
"{",
"err",
":=",
"opt",
"(",
"handler",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"handler",
".",
"api",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"handler",
".",
"ln",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"handler",
".",
"server",
"=",
"&",
"http",
".",
"Server",
"{",
"Handler",
":",
"handler",
"}",
"\n\n",
"return",
"handler",
",",
"nil",
"\n",
"}"
] |
// NewHandler returns a new instance of Handler with a default logger.
|
[
"NewHandler",
"returns",
"a",
"new",
"instance",
"of",
"Handler",
"with",
"a",
"default",
"logger",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L122-L148
|
train
|
pilosa/pilosa
|
http/handler.go
|
Close
|
func (h *Handler) Close() error {
deadlineCtx, cancelFunc := context.WithDeadline(context.Background(), time.Now().Add(h.closeTimeout))
defer cancelFunc()
err := h.server.Shutdown(deadlineCtx)
if err != nil {
err = h.server.Close()
}
return errors.Wrap(err, "shutdown/close http server")
}
|
go
|
func (h *Handler) Close() error {
deadlineCtx, cancelFunc := context.WithDeadline(context.Background(), time.Now().Add(h.closeTimeout))
defer cancelFunc()
err := h.server.Shutdown(deadlineCtx)
if err != nil {
err = h.server.Close()
}
return errors.Wrap(err, "shutdown/close http server")
}
|
[
"func",
"(",
"h",
"*",
"Handler",
")",
"Close",
"(",
")",
"error",
"{",
"deadlineCtx",
",",
"cancelFunc",
":=",
"context",
".",
"WithDeadline",
"(",
"context",
".",
"Background",
"(",
")",
",",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"h",
".",
"closeTimeout",
")",
")",
"\n",
"defer",
"cancelFunc",
"(",
")",
"\n",
"err",
":=",
"h",
".",
"server",
".",
"Shutdown",
"(",
"deadlineCtx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"h",
".",
"server",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}"
] |
// Close tries to cleanly shutdown the HTTP server, and failing that, after a
// timeout, calls Server.Close.
|
[
"Close",
"tries",
"to",
"cleanly",
"shutdown",
"the",
"HTTP",
"server",
"and",
"failing",
"that",
"after",
"a",
"timeout",
"calls",
"Server",
".",
"Close",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L161-L169
|
train
|
pilosa/pilosa
|
http/handler.go
|
ServeHTTP
|
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
w.WriteHeader(http.StatusInternalServerError)
stack := debug.Stack()
msg := "PANIC: %s\n%s"
h.logger.Printf(msg, err, stack)
fmt.Fprintf(w, msg, err, stack)
}
}()
t := time.Now()
h.Handler.ServeHTTP(w, r)
dif := time.Since(t)
// Calculate per request StatsD metrics when the handler is fully configured.
statsTags := make([]string, 0, 3)
longQueryTime := h.api.LongQueryTime()
if longQueryTime > 0 && dif > longQueryTime {
h.logger.Printf("%s %s %v", r.Method, r.URL.String(), dif)
statsTags = append(statsTags, "slow_query")
}
pathParts := strings.Split(r.URL.Path, "/")
endpointName := strings.Join(pathParts, "_")
if externalPrefixFlag[pathParts[1]] {
statsTags = append(statsTags, "external")
}
// useragent tag identifies internal/external endpoints
statsTags = append(statsTags, "useragent:"+r.UserAgent())
stats := h.api.StatsWithTags(statsTags)
if stats != nil {
stats.Histogram("http."+endpointName, float64(dif), 0.1)
}
}
|
go
|
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
w.WriteHeader(http.StatusInternalServerError)
stack := debug.Stack()
msg := "PANIC: %s\n%s"
h.logger.Printf(msg, err, stack)
fmt.Fprintf(w, msg, err, stack)
}
}()
t := time.Now()
h.Handler.ServeHTTP(w, r)
dif := time.Since(t)
// Calculate per request StatsD metrics when the handler is fully configured.
statsTags := make([]string, 0, 3)
longQueryTime := h.api.LongQueryTime()
if longQueryTime > 0 && dif > longQueryTime {
h.logger.Printf("%s %s %v", r.Method, r.URL.String(), dif)
statsTags = append(statsTags, "slow_query")
}
pathParts := strings.Split(r.URL.Path, "/")
endpointName := strings.Join(pathParts, "_")
if externalPrefixFlag[pathParts[1]] {
statsTags = append(statsTags, "external")
}
// useragent tag identifies internal/external endpoints
statsTags = append(statsTags, "useragent:"+r.UserAgent())
stats := h.api.StatsWithTags(statsTags)
if stats != nil {
stats.Histogram("http."+endpointName, float64(dif), 0.1)
}
}
|
[
"func",
"(",
"h",
"*",
"Handler",
")",
"ServeHTTP",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
":=",
"recover",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"stack",
":=",
"debug",
".",
"Stack",
"(",
")",
"\n",
"msg",
":=",
"\"",
"\\n",
"\"",
"\n",
"h",
".",
"logger",
".",
"Printf",
"(",
"msg",
",",
"err",
",",
"stack",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"msg",
",",
"err",
",",
"stack",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"t",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"h",
".",
"Handler",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"dif",
":=",
"time",
".",
"Since",
"(",
"t",
")",
"\n\n",
"// Calculate per request StatsD metrics when the handler is fully configured.",
"statsTags",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"3",
")",
"\n\n",
"longQueryTime",
":=",
"h",
".",
"api",
".",
"LongQueryTime",
"(",
")",
"\n",
"if",
"longQueryTime",
">",
"0",
"&&",
"dif",
">",
"longQueryTime",
"{",
"h",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"r",
".",
"Method",
",",
"r",
".",
"URL",
".",
"String",
"(",
")",
",",
"dif",
")",
"\n",
"statsTags",
"=",
"append",
"(",
"statsTags",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"pathParts",
":=",
"strings",
".",
"Split",
"(",
"r",
".",
"URL",
".",
"Path",
",",
"\"",
"\"",
")",
"\n",
"endpointName",
":=",
"strings",
".",
"Join",
"(",
"pathParts",
",",
"\"",
"\"",
")",
"\n\n",
"if",
"externalPrefixFlag",
"[",
"pathParts",
"[",
"1",
"]",
"]",
"{",
"statsTags",
"=",
"append",
"(",
"statsTags",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// useragent tag identifies internal/external endpoints",
"statsTags",
"=",
"append",
"(",
"statsTags",
",",
"\"",
"\"",
"+",
"r",
".",
"UserAgent",
"(",
")",
")",
"\n",
"stats",
":=",
"h",
".",
"api",
".",
"StatsWithTags",
"(",
"statsTags",
")",
"\n",
"if",
"stats",
"!=",
"nil",
"{",
"stats",
".",
"Histogram",
"(",
"\"",
"\"",
"+",
"endpointName",
",",
"float64",
"(",
"dif",
")",
",",
"0.1",
")",
"\n",
"}",
"\n",
"}"
] |
// ServeHTTP handles an HTTP request.
|
[
"ServeHTTP",
"handles",
"an",
"HTTP",
"request",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L284-L321
|
train
|
pilosa/pilosa
|
http/handler.go
|
check
|
func (r *successResponse) check(err error) (statusCode int) {
if err == nil {
r.Success = true
return 0
}
cause := errors.Cause(err)
// Determine HTTP status code based on the error type.
switch cause.(type) {
case pilosa.BadRequestError:
statusCode = http.StatusBadRequest
case pilosa.ConflictError:
statusCode = http.StatusConflict
case pilosa.NotFoundError:
statusCode = http.StatusNotFound
default:
statusCode = http.StatusInternalServerError
}
r.Success = false
r.Error = &Error{Message: err.Error()}
return statusCode
}
|
go
|
func (r *successResponse) check(err error) (statusCode int) {
if err == nil {
r.Success = true
return 0
}
cause := errors.Cause(err)
// Determine HTTP status code based on the error type.
switch cause.(type) {
case pilosa.BadRequestError:
statusCode = http.StatusBadRequest
case pilosa.ConflictError:
statusCode = http.StatusConflict
case pilosa.NotFoundError:
statusCode = http.StatusNotFound
default:
statusCode = http.StatusInternalServerError
}
r.Success = false
r.Error = &Error{Message: err.Error()}
return statusCode
}
|
[
"func",
"(",
"r",
"*",
"successResponse",
")",
"check",
"(",
"err",
"error",
")",
"(",
"statusCode",
"int",
")",
"{",
"if",
"err",
"==",
"nil",
"{",
"r",
".",
"Success",
"=",
"true",
"\n",
"return",
"0",
"\n",
"}",
"\n\n",
"cause",
":=",
"errors",
".",
"Cause",
"(",
"err",
")",
"\n\n",
"// Determine HTTP status code based on the error type.",
"switch",
"cause",
".",
"(",
"type",
")",
"{",
"case",
"pilosa",
".",
"BadRequestError",
":",
"statusCode",
"=",
"http",
".",
"StatusBadRequest",
"\n",
"case",
"pilosa",
".",
"ConflictError",
":",
"statusCode",
"=",
"http",
".",
"StatusConflict",
"\n",
"case",
"pilosa",
".",
"NotFoundError",
":",
"statusCode",
"=",
"http",
".",
"StatusNotFound",
"\n",
"default",
":",
"statusCode",
"=",
"http",
".",
"StatusInternalServerError",
"\n",
"}",
"\n\n",
"r",
".",
"Success",
"=",
"false",
"\n",
"r",
".",
"Error",
"=",
"&",
"Error",
"{",
"Message",
":",
"err",
".",
"Error",
"(",
")",
"}",
"\n\n",
"return",
"statusCode",
"\n",
"}"
] |
// check determines success or failure based on the error.
// It also returns the corresponding http status code.
|
[
"check",
"determines",
"success",
"or",
"failure",
"based",
"on",
"the",
"error",
".",
"It",
"also",
"returns",
"the",
"corresponding",
"http",
"status",
"code",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L332-L356
|
train
|
pilosa/pilosa
|
http/handler.go
|
write
|
func (r *successResponse) write(w http.ResponseWriter, err error) {
// Apply the error and get the status code.
statusCode := r.check(err)
// Marshal the json response.
msg, err := json.Marshal(r)
if err != nil {
http.Error(w, string(msg), http.StatusInternalServerError)
return
}
// Write the response.
if statusCode == 0 {
_, err := w.Write(msg)
if err != nil {
r.h.logger.Printf("error writing response: %v", err)
http.Error(w, string(msg), http.StatusInternalServerError)
return
}
_, err = w.Write([]byte("\n"))
if err != nil {
r.h.logger.Printf("error writing newline after response: %v", err)
http.Error(w, string(msg), http.StatusInternalServerError)
return
}
} else {
http.Error(w, string(msg), statusCode)
}
}
|
go
|
func (r *successResponse) write(w http.ResponseWriter, err error) {
// Apply the error and get the status code.
statusCode := r.check(err)
// Marshal the json response.
msg, err := json.Marshal(r)
if err != nil {
http.Error(w, string(msg), http.StatusInternalServerError)
return
}
// Write the response.
if statusCode == 0 {
_, err := w.Write(msg)
if err != nil {
r.h.logger.Printf("error writing response: %v", err)
http.Error(w, string(msg), http.StatusInternalServerError)
return
}
_, err = w.Write([]byte("\n"))
if err != nil {
r.h.logger.Printf("error writing newline after response: %v", err)
http.Error(w, string(msg), http.StatusInternalServerError)
return
}
} else {
http.Error(w, string(msg), statusCode)
}
}
|
[
"func",
"(",
"r",
"*",
"successResponse",
")",
"write",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"err",
"error",
")",
"{",
"// Apply the error and get the status code.",
"statusCode",
":=",
"r",
".",
"check",
"(",
"err",
")",
"\n\n",
"// Marshal the json response.",
"msg",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"string",
"(",
"msg",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Write the response.",
"if",
"statusCode",
"==",
"0",
"{",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"msg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"r",
".",
"h",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"string",
"(",
"msg",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\\n",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"r",
".",
"h",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"string",
"(",
"msg",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"else",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"string",
"(",
"msg",
")",
",",
"statusCode",
")",
"\n",
"}",
"\n",
"}"
] |
// write sends a response to the http.ResponseWriter based on the success
// status and the error.
|
[
"write",
"sends",
"a",
"response",
"to",
"the",
"http",
".",
"ResponseWriter",
"based",
"on",
"the",
"success",
"status",
"and",
"the",
"error",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L360-L388
|
train
|
pilosa/pilosa
|
http/handler.go
|
UnmarshalJSON
|
func (p *postIndexRequest) UnmarshalJSON(b []byte) error {
// m is an overflow map used to capture additional, unexpected keys.
m := make(map[string]interface{})
if err := json.Unmarshal(b, &m); err != nil {
return errors.Wrap(err, "unmarshalling unexpected values")
}
validIndexOptions := getValidOptions(pilosa.IndexOptions{})
err := validateOptions(m, validIndexOptions)
if err != nil {
return err
}
// Unmarshal expected values.
_p := _postIndexRequest{
Options: pilosa.IndexOptions{
Keys: false,
TrackExistence: true,
},
}
if err := json.Unmarshal(b, &_p); err != nil {
return errors.Wrap(err, "unmarshalling expected values")
}
p.Options = _p.Options
return nil
}
|
go
|
func (p *postIndexRequest) UnmarshalJSON(b []byte) error {
// m is an overflow map used to capture additional, unexpected keys.
m := make(map[string]interface{})
if err := json.Unmarshal(b, &m); err != nil {
return errors.Wrap(err, "unmarshalling unexpected values")
}
validIndexOptions := getValidOptions(pilosa.IndexOptions{})
err := validateOptions(m, validIndexOptions)
if err != nil {
return err
}
// Unmarshal expected values.
_p := _postIndexRequest{
Options: pilosa.IndexOptions{
Keys: false,
TrackExistence: true,
},
}
if err := json.Unmarshal(b, &_p); err != nil {
return errors.Wrap(err, "unmarshalling expected values")
}
p.Options = _p.Options
return nil
}
|
[
"func",
"(",
"p",
"*",
"postIndexRequest",
")",
"UnmarshalJSON",
"(",
"b",
"[",
"]",
"byte",
")",
"error",
"{",
"// m is an overflow map used to capture additional, unexpected keys.",
"m",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"b",
",",
"&",
"m",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"validIndexOptions",
":=",
"getValidOptions",
"(",
"pilosa",
".",
"IndexOptions",
"{",
"}",
")",
"\n",
"err",
":=",
"validateOptions",
"(",
"m",
",",
"validIndexOptions",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// Unmarshal expected values.",
"_p",
":=",
"_postIndexRequest",
"{",
"Options",
":",
"pilosa",
".",
"IndexOptions",
"{",
"Keys",
":",
"false",
",",
"TrackExistence",
":",
"true",
",",
"}",
",",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"b",
",",
"&",
"_p",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"p",
".",
"Options",
"=",
"_p",
".",
"Options",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Custom Unmarshal JSON to validate request body when creating a new index.
|
[
"Custom",
"Unmarshal",
"JSON",
"to",
"validate",
"request",
"body",
"when",
"creating",
"a",
"new",
"index",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L576-L603
|
train
|
pilosa/pilosa
|
http/handler.go
|
validateOptions
|
func validateOptions(data map[string]interface{}, validIndexOptions []string) error {
for k, v := range data {
switch k {
case "options":
options, ok := v.(map[string]interface{})
if !ok {
return errors.New("options is not map[string]interface{}")
}
for kk, vv := range options {
if !foundItem(validIndexOptions, kk) {
return fmt.Errorf("unknown key: %v:%v", kk, vv)
}
}
default:
return fmt.Errorf("unknown key: %v:%v", k, v)
}
}
return nil
}
|
go
|
func validateOptions(data map[string]interface{}, validIndexOptions []string) error {
for k, v := range data {
switch k {
case "options":
options, ok := v.(map[string]interface{})
if !ok {
return errors.New("options is not map[string]interface{}")
}
for kk, vv := range options {
if !foundItem(validIndexOptions, kk) {
return fmt.Errorf("unknown key: %v:%v", kk, vv)
}
}
default:
return fmt.Errorf("unknown key: %v:%v", k, v)
}
}
return nil
}
|
[
"func",
"validateOptions",
"(",
"data",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"validIndexOptions",
"[",
"]",
"string",
")",
"error",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"data",
"{",
"switch",
"k",
"{",
"case",
"\"",
"\"",
":",
"options",
",",
"ok",
":=",
"v",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"kk",
",",
"vv",
":=",
"range",
"options",
"{",
"if",
"!",
"foundItem",
"(",
"validIndexOptions",
",",
"kk",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"kk",
",",
"vv",
")",
"\n",
"}",
"\n",
"}",
"\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"k",
",",
"v",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Raise errors for any unknown key
|
[
"Raise",
"errors",
"for",
"any",
"unknown",
"key"
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L617-L635
|
train
|
pilosa/pilosa
|
http/handler.go
|
readQueryRequest
|
func (h *Handler) readQueryRequest(r *http.Request) (*pilosa.QueryRequest, error) {
switch r.Header.Get("Content-Type") {
case "application/x-protobuf":
return h.readProtobufQueryRequest(r)
default:
return h.readURLQueryRequest(r)
}
}
|
go
|
func (h *Handler) readQueryRequest(r *http.Request) (*pilosa.QueryRequest, error) {
switch r.Header.Get("Content-Type") {
case "application/x-protobuf":
return h.readProtobufQueryRequest(r)
default:
return h.readURLQueryRequest(r)
}
}
|
[
"func",
"(",
"h",
"*",
"Handler",
")",
"readQueryRequest",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"pilosa",
".",
"QueryRequest",
",",
"error",
")",
"{",
"switch",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"{",
"case",
"\"",
"\"",
":",
"return",
"h",
".",
"readProtobufQueryRequest",
"(",
"r",
")",
"\n",
"default",
":",
"return",
"h",
".",
"readURLQueryRequest",
"(",
"r",
")",
"\n",
"}",
"\n",
"}"
] |
// readQueryRequest parses an query parameters from r.
|
[
"readQueryRequest",
"parses",
"an",
"query",
"parameters",
"from",
"r",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L955-L962
|
train
|
pilosa/pilosa
|
http/handler.go
|
readProtobufQueryRequest
|
func (h *Handler) readProtobufQueryRequest(r *http.Request) (*pilosa.QueryRequest, error) {
// Slurp the body.
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, errors.Wrap(err, "reading")
}
qreq := &pilosa.QueryRequest{}
err = h.api.Serializer.Unmarshal(body, qreq)
if err != nil {
return nil, errors.Wrap(err, "unmarshalling query request")
}
return qreq, nil
}
|
go
|
func (h *Handler) readProtobufQueryRequest(r *http.Request) (*pilosa.QueryRequest, error) {
// Slurp the body.
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, errors.Wrap(err, "reading")
}
qreq := &pilosa.QueryRequest{}
err = h.api.Serializer.Unmarshal(body, qreq)
if err != nil {
return nil, errors.Wrap(err, "unmarshalling query request")
}
return qreq, nil
}
|
[
"func",
"(",
"h",
"*",
"Handler",
")",
"readProtobufQueryRequest",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"pilosa",
".",
"QueryRequest",
",",
"error",
")",
"{",
"// Slurp the body.",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"qreq",
":=",
"&",
"pilosa",
".",
"QueryRequest",
"{",
"}",
"\n",
"err",
"=",
"h",
".",
"api",
".",
"Serializer",
".",
"Unmarshal",
"(",
"body",
",",
"qreq",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"qreq",
",",
"nil",
"\n",
"}"
] |
// readProtobufQueryRequest parses query parameters in protobuf from r.
|
[
"readProtobufQueryRequest",
"parses",
"query",
"parameters",
"in",
"protobuf",
"from",
"r",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L965-L978
|
train
|
pilosa/pilosa
|
http/handler.go
|
readURLQueryRequest
|
func (h *Handler) readURLQueryRequest(r *http.Request) (*pilosa.QueryRequest, error) {
q := r.URL.Query()
// Parse query string.
buf, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, errors.Wrap(err, "reading")
}
query := string(buf)
// Parse list of shards.
shards, err := parseUint64Slice(q.Get("shards"))
if err != nil {
return nil, errors.New("invalid shard argument")
}
return &pilosa.QueryRequest{
Query: query,
Shards: shards,
ColumnAttrs: q.Get("columnAttrs") == "true",
ExcludeRowAttrs: q.Get("excludeRowAttrs") == "true",
ExcludeColumns: q.Get("excludeColumns") == "true",
}, nil
}
|
go
|
func (h *Handler) readURLQueryRequest(r *http.Request) (*pilosa.QueryRequest, error) {
q := r.URL.Query()
// Parse query string.
buf, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, errors.Wrap(err, "reading")
}
query := string(buf)
// Parse list of shards.
shards, err := parseUint64Slice(q.Get("shards"))
if err != nil {
return nil, errors.New("invalid shard argument")
}
return &pilosa.QueryRequest{
Query: query,
Shards: shards,
ColumnAttrs: q.Get("columnAttrs") == "true",
ExcludeRowAttrs: q.Get("excludeRowAttrs") == "true",
ExcludeColumns: q.Get("excludeColumns") == "true",
}, nil
}
|
[
"func",
"(",
"h",
"*",
"Handler",
")",
"readURLQueryRequest",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"pilosa",
".",
"QueryRequest",
",",
"error",
")",
"{",
"q",
":=",
"r",
".",
"URL",
".",
"Query",
"(",
")",
"\n\n",
"// Parse query string.",
"buf",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"query",
":=",
"string",
"(",
"buf",
")",
"\n\n",
"// Parse list of shards.",
"shards",
",",
"err",
":=",
"parseUint64Slice",
"(",
"q",
".",
"Get",
"(",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"pilosa",
".",
"QueryRequest",
"{",
"Query",
":",
"query",
",",
"Shards",
":",
"shards",
",",
"ColumnAttrs",
":",
"q",
".",
"Get",
"(",
"\"",
"\"",
")",
"==",
"\"",
"\"",
",",
"ExcludeRowAttrs",
":",
"q",
".",
"Get",
"(",
"\"",
"\"",
")",
"==",
"\"",
"\"",
",",
"ExcludeColumns",
":",
"q",
".",
"Get",
"(",
"\"",
"\"",
")",
"==",
"\"",
"\"",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// readURLQueryRequest parses query parameters from URL parameters from r.
|
[
"readURLQueryRequest",
"parses",
"query",
"parameters",
"from",
"URL",
"parameters",
"from",
"r",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L981-L1004
|
train
|
pilosa/pilosa
|
http/handler.go
|
writeQueryResponse
|
func (h *Handler) writeQueryResponse(w http.ResponseWriter, r *http.Request, resp *pilosa.QueryResponse) error {
if !validHeaderAcceptJSON(r.Header) {
w.Header().Set("Content-Type", "application/protobuf")
return h.writeProtobufQueryResponse(w, resp)
}
w.Header().Set("Content-Type", "application/json")
return h.writeJSONQueryResponse(w, resp)
}
|
go
|
func (h *Handler) writeQueryResponse(w http.ResponseWriter, r *http.Request, resp *pilosa.QueryResponse) error {
if !validHeaderAcceptJSON(r.Header) {
w.Header().Set("Content-Type", "application/protobuf")
return h.writeProtobufQueryResponse(w, resp)
}
w.Header().Set("Content-Type", "application/json")
return h.writeJSONQueryResponse(w, resp)
}
|
[
"func",
"(",
"h",
"*",
"Handler",
")",
"writeQueryResponse",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"resp",
"*",
"pilosa",
".",
"QueryResponse",
")",
"error",
"{",
"if",
"!",
"validHeaderAcceptJSON",
"(",
"r",
".",
"Header",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"h",
".",
"writeProtobufQueryResponse",
"(",
"w",
",",
"resp",
")",
"\n",
"}",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"h",
".",
"writeJSONQueryResponse",
"(",
"w",
",",
"resp",
")",
"\n",
"}"
] |
// writeQueryResponse writes the response from the executor to w.
|
[
"writeQueryResponse",
"writes",
"the",
"response",
"from",
"the",
"executor",
"to",
"w",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L1007-L1014
|
train
|
pilosa/pilosa
|
http/handler.go
|
writeProtobufQueryResponse
|
func (h *Handler) writeProtobufQueryResponse(w io.Writer, resp *pilosa.QueryResponse) error {
if buf, err := h.api.Serializer.Marshal(resp); err != nil {
return errors.Wrap(err, "marshalling")
} else if _, err := w.Write(buf); err != nil {
return errors.Wrap(err, "writing")
}
return nil
}
|
go
|
func (h *Handler) writeProtobufQueryResponse(w io.Writer, resp *pilosa.QueryResponse) error {
if buf, err := h.api.Serializer.Marshal(resp); err != nil {
return errors.Wrap(err, "marshalling")
} else if _, err := w.Write(buf); err != nil {
return errors.Wrap(err, "writing")
}
return nil
}
|
[
"func",
"(",
"h",
"*",
"Handler",
")",
"writeProtobufQueryResponse",
"(",
"w",
"io",
".",
"Writer",
",",
"resp",
"*",
"pilosa",
".",
"QueryResponse",
")",
"error",
"{",
"if",
"buf",
",",
"err",
":=",
"h",
".",
"api",
".",
"Serializer",
".",
"Marshal",
"(",
"resp",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"if",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"buf",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// writeProtobufQueryResponse writes the response from the executor to w as protobuf.
|
[
"writeProtobufQueryResponse",
"writes",
"the",
"response",
"from",
"the",
"executor",
"to",
"w",
"as",
"protobuf",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L1017-L1024
|
train
|
pilosa/pilosa
|
http/handler.go
|
writeJSONQueryResponse
|
func (h *Handler) writeJSONQueryResponse(w io.Writer, resp *pilosa.QueryResponse) error {
return json.NewEncoder(w).Encode(resp)
}
|
go
|
func (h *Handler) writeJSONQueryResponse(w io.Writer, resp *pilosa.QueryResponse) error {
return json.NewEncoder(w).Encode(resp)
}
|
[
"func",
"(",
"h",
"*",
"Handler",
")",
"writeJSONQueryResponse",
"(",
"w",
"io",
".",
"Writer",
",",
"resp",
"*",
"pilosa",
".",
"QueryResponse",
")",
"error",
"{",
"return",
"json",
".",
"NewEncoder",
"(",
"w",
")",
".",
"Encode",
"(",
"resp",
")",
"\n",
"}"
] |
// writeJSONQueryResponse writes the response from the executor to w as JSON.
|
[
"writeJSONQueryResponse",
"writes",
"the",
"response",
"from",
"the",
"executor",
"to",
"w",
"as",
"JSON",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L1027-L1029
|
train
|
pilosa/pilosa
|
http/handler.go
|
parseUint64Slice
|
func parseUint64Slice(s string) ([]uint64, error) {
var a []uint64
for _, str := range strings.Split(s, ",") {
// Ignore blanks.
if str == "" {
continue
}
// Parse number.
num, err := strconv.ParseUint(str, 10, 64)
if err != nil {
return nil, errors.Wrap(err, "parsing int")
}
a = append(a, num)
}
return a, nil
}
|
go
|
func parseUint64Slice(s string) ([]uint64, error) {
var a []uint64
for _, str := range strings.Split(s, ",") {
// Ignore blanks.
if str == "" {
continue
}
// Parse number.
num, err := strconv.ParseUint(str, 10, 64)
if err != nil {
return nil, errors.Wrap(err, "parsing int")
}
a = append(a, num)
}
return a, nil
}
|
[
"func",
"parseUint64Slice",
"(",
"s",
"string",
")",
"(",
"[",
"]",
"uint64",
",",
"error",
")",
"{",
"var",
"a",
"[",
"]",
"uint64",
"\n",
"for",
"_",
",",
"str",
":=",
"range",
"strings",
".",
"Split",
"(",
"s",
",",
"\"",
"\"",
")",
"{",
"// Ignore blanks.",
"if",
"str",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n\n",
"// Parse number.",
"num",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"str",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"a",
"=",
"append",
"(",
"a",
",",
"num",
")",
"\n",
"}",
"\n",
"return",
"a",
",",
"nil",
"\n",
"}"
] |
// parseUint64Slice returns a slice of uint64s from a comma-delimited string.
|
[
"parseUint64Slice",
"returns",
"a",
"slice",
"of",
"uint64s",
"from",
"a",
"comma",
"-",
"delimited",
"string",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/handler.go#L1312-L1328
|
train
|
pilosa/pilosa
|
http/translator.go
|
TranslateColumnsToUint64
|
func (s *translateStore) TranslateColumnsToUint64(index string, values []string) ([]uint64, error) {
return nil, pilosa.ErrNotImplemented
}
|
go
|
func (s *translateStore) TranslateColumnsToUint64(index string, values []string) ([]uint64, error) {
return nil, pilosa.ErrNotImplemented
}
|
[
"func",
"(",
"s",
"*",
"translateStore",
")",
"TranslateColumnsToUint64",
"(",
"index",
"string",
",",
"values",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"uint64",
",",
"error",
")",
"{",
"return",
"nil",
",",
"pilosa",
".",
"ErrNotImplemented",
"\n",
"}"
] |
// TranslateColumnsToUint64 is not currently implemented.
|
[
"TranslateColumnsToUint64",
"is",
"not",
"currently",
"implemented",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/translator.go#L64-L66
|
train
|
pilosa/pilosa
|
http/translator.go
|
TranslateColumnToString
|
func (s *translateStore) TranslateColumnToString(index string, values uint64) (string, error) {
return "", pilosa.ErrNotImplemented
}
|
go
|
func (s *translateStore) TranslateColumnToString(index string, values uint64) (string, error) {
return "", pilosa.ErrNotImplemented
}
|
[
"func",
"(",
"s",
"*",
"translateStore",
")",
"TranslateColumnToString",
"(",
"index",
"string",
",",
"values",
"uint64",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"\"",
"\"",
",",
"pilosa",
".",
"ErrNotImplemented",
"\n",
"}"
] |
// TranslateColumnToString is not currently implemented.
|
[
"TranslateColumnToString",
"is",
"not",
"currently",
"implemented",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/translator.go#L69-L71
|
train
|
pilosa/pilosa
|
http/translator.go
|
TranslateRowsToUint64
|
func (s *translateStore) TranslateRowsToUint64(index, frame string, values []string) ([]uint64, error) {
return nil, pilosa.ErrNotImplemented
}
|
go
|
func (s *translateStore) TranslateRowsToUint64(index, frame string, values []string) ([]uint64, error) {
return nil, pilosa.ErrNotImplemented
}
|
[
"func",
"(",
"s",
"*",
"translateStore",
")",
"TranslateRowsToUint64",
"(",
"index",
",",
"frame",
"string",
",",
"values",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"uint64",
",",
"error",
")",
"{",
"return",
"nil",
",",
"pilosa",
".",
"ErrNotImplemented",
"\n",
"}"
] |
// TranslateRowsToUint64 is not currently implemented.
|
[
"TranslateRowsToUint64",
"is",
"not",
"currently",
"implemented",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/translator.go#L74-L76
|
train
|
pilosa/pilosa
|
http/translator.go
|
TranslateRowToString
|
func (s *translateStore) TranslateRowToString(index, frame string, values uint64) (string, error) {
return "", pilosa.ErrNotImplemented
}
|
go
|
func (s *translateStore) TranslateRowToString(index, frame string, values uint64) (string, error) {
return "", pilosa.ErrNotImplemented
}
|
[
"func",
"(",
"s",
"*",
"translateStore",
")",
"TranslateRowToString",
"(",
"index",
",",
"frame",
"string",
",",
"values",
"uint64",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"\"",
"\"",
",",
"pilosa",
".",
"ErrNotImplemented",
"\n",
"}"
] |
// TranslateRowToString is not currently implemented.
|
[
"TranslateRowToString",
"is",
"not",
"currently",
"implemented",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/translator.go#L79-L81
|
train
|
pilosa/pilosa
|
http/translator.go
|
Reader
|
func (s *translateStore) Reader(ctx context.Context, off int64) (io.ReadCloser, error) {
// Generate remote URL.
u, err := url.Parse(s.node.URI.String())
if err != nil {
return nil, err
}
u.Path = "/internal/translate/data"
u.RawQuery = (url.Values{
"offset": {strconv.FormatInt(off, 10)},
}).Encode()
// Connect a stream to the remote server.
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
// Connect a stream to the remote server.
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("http: cannot connect to translate store endpoint: %s", err)
}
// Handle error codes or return body as stream.
switch resp.StatusCode {
case http.StatusOK:
return resp.Body, nil
case http.StatusNotImplemented:
resp.Body.Close()
return nil, pilosa.ErrNotImplemented
default:
body, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
return nil, fmt.Errorf("http: invalid translate store endpoint status: code=%d url=%s body=%q", resp.StatusCode, u.String(), bytes.TrimSpace(body))
}
}
|
go
|
func (s *translateStore) Reader(ctx context.Context, off int64) (io.ReadCloser, error) {
// Generate remote URL.
u, err := url.Parse(s.node.URI.String())
if err != nil {
return nil, err
}
u.Path = "/internal/translate/data"
u.RawQuery = (url.Values{
"offset": {strconv.FormatInt(off, 10)},
}).Encode()
// Connect a stream to the remote server.
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
// Connect a stream to the remote server.
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("http: cannot connect to translate store endpoint: %s", err)
}
// Handle error codes or return body as stream.
switch resp.StatusCode {
case http.StatusOK:
return resp.Body, nil
case http.StatusNotImplemented:
resp.Body.Close()
return nil, pilosa.ErrNotImplemented
default:
body, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
return nil, fmt.Errorf("http: invalid translate store endpoint status: code=%d url=%s body=%q", resp.StatusCode, u.String(), bytes.TrimSpace(body))
}
}
|
[
"func",
"(",
"s",
"*",
"translateStore",
")",
"Reader",
"(",
"ctx",
"context",
".",
"Context",
",",
"off",
"int64",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"// Generate remote URL.",
"u",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"s",
".",
"node",
".",
"URI",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"u",
".",
"Path",
"=",
"\"",
"\"",
"\n",
"u",
".",
"RawQuery",
"=",
"(",
"url",
".",
"Values",
"{",
"\"",
"\"",
":",
"{",
"strconv",
".",
"FormatInt",
"(",
"off",
",",
"10",
")",
"}",
",",
"}",
")",
".",
"Encode",
"(",
")",
"\n\n",
"// Connect a stream to the remote server.",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"u",
".",
"String",
"(",
")",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"req",
"=",
"req",
".",
"WithContext",
"(",
"ctx",
")",
"\n\n",
"// Connect a stream to the remote server.",
"resp",
",",
"err",
":=",
"http",
".",
"DefaultClient",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Handle error codes or return body as stream.",
"switch",
"resp",
".",
"StatusCode",
"{",
"case",
"http",
".",
"StatusOK",
":",
"return",
"resp",
".",
"Body",
",",
"nil",
"\n",
"case",
"http",
".",
"StatusNotImplemented",
":",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"pilosa",
".",
"ErrNotImplemented",
"\n",
"default",
":",
"body",
",",
"_",
":=",
"ioutil",
".",
"ReadAll",
"(",
"resp",
".",
"Body",
")",
"\n",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"resp",
".",
"StatusCode",
",",
"u",
".",
"String",
"(",
")",
",",
"bytes",
".",
"TrimSpace",
"(",
"body",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// Reader returns a reader that can stream data from a remote store.
|
[
"Reader",
"returns",
"a",
"reader",
"that",
"can",
"stream",
"data",
"from",
"a",
"remote",
"store",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/http/translator.go#L84-L120
|
train
|
pilosa/pilosa
|
gossip/gossip.go
|
Open
|
func (g *memberSet) Open() (err error) {
g.mu.Lock()
g.memberlist, err = memberlist.Create(g.config.memberlistConfig)
g.mu.Unlock()
if err != nil {
return errors.Wrap(err, "creating memberlist")
}
g.broadcasts = &memberlist.TransmitLimitedQueue{
NumNodes: func() int {
g.mu.RLock()
defer g.mu.RUnlock()
return g.memberlist.NumMembers()
},
RetransmitMult: 3,
}
var uris = make([]*pilosa.URI, len(g.config.gossipSeeds))
for i, addr := range g.config.gossipSeeds {
uris[i], err = pilosa.NewURIFromAddress(addr)
if err != nil {
return fmt.Errorf("new uri from address: %s", err)
}
}
var nodes = make([]*pilosa.Node, len(uris))
for i, uri := range uris {
nodes[i] = &pilosa.Node{URI: *uri}
}
g.mu.RLock()
err = g.joinWithRetry(pilosa.URIs(pilosa.Nodes(nodes).URIs()).HostPortStrings())
g.mu.RUnlock()
if err != nil {
return errors.Wrap(err, "joinWithRetry")
}
return nil
}
|
go
|
func (g *memberSet) Open() (err error) {
g.mu.Lock()
g.memberlist, err = memberlist.Create(g.config.memberlistConfig)
g.mu.Unlock()
if err != nil {
return errors.Wrap(err, "creating memberlist")
}
g.broadcasts = &memberlist.TransmitLimitedQueue{
NumNodes: func() int {
g.mu.RLock()
defer g.mu.RUnlock()
return g.memberlist.NumMembers()
},
RetransmitMult: 3,
}
var uris = make([]*pilosa.URI, len(g.config.gossipSeeds))
for i, addr := range g.config.gossipSeeds {
uris[i], err = pilosa.NewURIFromAddress(addr)
if err != nil {
return fmt.Errorf("new uri from address: %s", err)
}
}
var nodes = make([]*pilosa.Node, len(uris))
for i, uri := range uris {
nodes[i] = &pilosa.Node{URI: *uri}
}
g.mu.RLock()
err = g.joinWithRetry(pilosa.URIs(pilosa.Nodes(nodes).URIs()).HostPortStrings())
g.mu.RUnlock()
if err != nil {
return errors.Wrap(err, "joinWithRetry")
}
return nil
}
|
[
"func",
"(",
"g",
"*",
"memberSet",
")",
"Open",
"(",
")",
"(",
"err",
"error",
")",
"{",
"g",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"g",
".",
"memberlist",
",",
"err",
"=",
"memberlist",
".",
"Create",
"(",
"g",
".",
"config",
".",
"memberlistConfig",
")",
"\n",
"g",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"g",
".",
"broadcasts",
"=",
"&",
"memberlist",
".",
"TransmitLimitedQueue",
"{",
"NumNodes",
":",
"func",
"(",
")",
"int",
"{",
"g",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"g",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"g",
".",
"memberlist",
".",
"NumMembers",
"(",
")",
"\n",
"}",
",",
"RetransmitMult",
":",
"3",
",",
"}",
"\n\n",
"var",
"uris",
"=",
"make",
"(",
"[",
"]",
"*",
"pilosa",
".",
"URI",
",",
"len",
"(",
"g",
".",
"config",
".",
"gossipSeeds",
")",
")",
"\n",
"for",
"i",
",",
"addr",
":=",
"range",
"g",
".",
"config",
".",
"gossipSeeds",
"{",
"uris",
"[",
"i",
"]",
",",
"err",
"=",
"pilosa",
".",
"NewURIFromAddress",
"(",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"var",
"nodes",
"=",
"make",
"(",
"[",
"]",
"*",
"pilosa",
".",
"Node",
",",
"len",
"(",
"uris",
")",
")",
"\n",
"for",
"i",
",",
"uri",
":=",
"range",
"uris",
"{",
"nodes",
"[",
"i",
"]",
"=",
"&",
"pilosa",
".",
"Node",
"{",
"URI",
":",
"*",
"uri",
"}",
"\n",
"}",
"\n\n",
"g",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"err",
"=",
"g",
".",
"joinWithRetry",
"(",
"pilosa",
".",
"URIs",
"(",
"pilosa",
".",
"Nodes",
"(",
"nodes",
")",
".",
"URIs",
"(",
")",
")",
".",
"HostPortStrings",
"(",
")",
")",
"\n",
"g",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Open implements the MemberSet interface to start network activity.
|
[
"Open",
"implements",
"the",
"MemberSet",
"interface",
"to",
"start",
"network",
"activity",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L65-L102
|
train
|
pilosa/pilosa
|
gossip/gossip.go
|
joinWithRetry
|
func (g *memberSet) joinWithRetry(hosts []string) error {
err := retry(60, 2*time.Second, func() error {
_, err := g.memberlist.Join(hosts)
return err
})
return err
}
|
go
|
func (g *memberSet) joinWithRetry(hosts []string) error {
err := retry(60, 2*time.Second, func() error {
_, err := g.memberlist.Join(hosts)
return err
})
return err
}
|
[
"func",
"(",
"g",
"*",
"memberSet",
")",
"joinWithRetry",
"(",
"hosts",
"[",
"]",
"string",
")",
"error",
"{",
"err",
":=",
"retry",
"(",
"60",
",",
"2",
"*",
"time",
".",
"Second",
",",
"func",
"(",
")",
"error",
"{",
"_",
",",
"err",
":=",
"g",
".",
"memberlist",
".",
"Join",
"(",
"hosts",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// joinWithRetry wraps the standard memberlist Join function in a retry.
|
[
"joinWithRetry",
"wraps",
"the",
"standard",
"memberlist",
"Join",
"function",
"in",
"a",
"retry",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L116-L122
|
train
|
pilosa/pilosa
|
gossip/gossip.go
|
retry
|
func retry(attempts int, sleep time.Duration, fn func() error) (err error) { // nolint: unparam
for i := 0; ; i++ {
err = fn()
if err == nil {
return
}
if i >= (attempts - 1) {
break
}
time.Sleep(sleep)
log.Println("retrying after error:", err)
}
return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
}
|
go
|
func retry(attempts int, sleep time.Duration, fn func() error) (err error) { // nolint: unparam
for i := 0; ; i++ {
err = fn()
if err == nil {
return
}
if i >= (attempts - 1) {
break
}
time.Sleep(sleep)
log.Println("retrying after error:", err)
}
return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
}
|
[
"func",
"retry",
"(",
"attempts",
"int",
",",
"sleep",
"time",
".",
"Duration",
",",
"fn",
"func",
"(",
")",
"error",
")",
"(",
"err",
"error",
")",
"{",
"// nolint: unparam",
"for",
"i",
":=",
"0",
";",
";",
"i",
"++",
"{",
"err",
"=",
"fn",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"i",
">=",
"(",
"attempts",
"-",
"1",
")",
"{",
"break",
"\n",
"}",
"\n",
"time",
".",
"Sleep",
"(",
"sleep",
")",
"\n",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"attempts",
",",
"err",
")",
"\n",
"}"
] |
// retry periodically retries function fn a specified number of attempts.
|
[
"retry",
"periodically",
"retries",
"function",
"fn",
"a",
"specified",
"number",
"of",
"attempts",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L125-L138
|
train
|
pilosa/pilosa
|
gossip/gossip.go
|
WithTransport
|
func WithTransport(transport *Transport) memberSetOption {
return func(g *memberSet) error {
g.transport = transport
return nil
}
}
|
go
|
func WithTransport(transport *Transport) memberSetOption {
return func(g *memberSet) error {
g.transport = transport
return nil
}
}
|
[
"func",
"WithTransport",
"(",
"transport",
"*",
"Transport",
")",
"memberSetOption",
"{",
"return",
"func",
"(",
"g",
"*",
"memberSet",
")",
"error",
"{",
"g",
".",
"transport",
"=",
"transport",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] |
// WithTransport is a functional option for providing a transport to NewMemberSet.
|
[
"WithTransport",
"is",
"a",
"functional",
"option",
"for",
"providing",
"a",
"transport",
"to",
"NewMemberSet",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L151-L156
|
train
|
pilosa/pilosa
|
gossip/gossip.go
|
WithLogOutput
|
func WithLogOutput(o io.Writer) memberSetOption {
return func(g *memberSet) error {
g.logOutput = o
return nil
}
}
|
go
|
func WithLogOutput(o io.Writer) memberSetOption {
return func(g *memberSet) error {
g.logOutput = o
return nil
}
}
|
[
"func",
"WithLogOutput",
"(",
"o",
"io",
".",
"Writer",
")",
"memberSetOption",
"{",
"return",
"func",
"(",
"g",
"*",
"memberSet",
")",
"error",
"{",
"g",
".",
"logOutput",
"=",
"o",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] |
// WithLogOutput allows one to pass a Writer which will in turn be passed to
// memberlist for use in logging.
|
[
"WithLogOutput",
"allows",
"one",
"to",
"pass",
"a",
"Writer",
"which",
"will",
"in",
"turn",
"be",
"passed",
"to",
"memberlist",
"for",
"use",
"in",
"logging",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L172-L177
|
train
|
pilosa/pilosa
|
gossip/gossip.go
|
WithPilosaLogger
|
func WithPilosaLogger(l logger.Logger) memberSetOption {
return func(g *memberSet) error {
g.Logger = l
return nil
}
}
|
go
|
func WithPilosaLogger(l logger.Logger) memberSetOption {
return func(g *memberSet) error {
g.Logger = l
return nil
}
}
|
[
"func",
"WithPilosaLogger",
"(",
"l",
"logger",
".",
"Logger",
")",
"memberSetOption",
"{",
"return",
"func",
"(",
"g",
"*",
"memberSet",
")",
"error",
"{",
"g",
".",
"Logger",
"=",
"l",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] |
// WithPilosaLogger allows one to configure a memberSet with a logger of their
// choice which satisfies the pilosa logger interface.
|
[
"WithPilosaLogger",
"allows",
"one",
"to",
"configure",
"a",
"memberSet",
"with",
"a",
"logger",
"of",
"their",
"choice",
"which",
"satisfies",
"the",
"pilosa",
"logger",
"interface",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L181-L186
|
train
|
pilosa/pilosa
|
gossip/gossip.go
|
NodeMeta
|
func (g *memberSet) NodeMeta(limit int) []byte {
buf, err := g.papi.Serializer.Marshal(g.papi.Node())
if err != nil {
g.Logger.Printf("marshal message error: %s", err)
return []byte{}
}
return buf
}
|
go
|
func (g *memberSet) NodeMeta(limit int) []byte {
buf, err := g.papi.Serializer.Marshal(g.papi.Node())
if err != nil {
g.Logger.Printf("marshal message error: %s", err)
return []byte{}
}
return buf
}
|
[
"func",
"(",
"g",
"*",
"memberSet",
")",
"NodeMeta",
"(",
"limit",
"int",
")",
"[",
"]",
"byte",
"{",
"buf",
",",
"err",
":=",
"g",
".",
"papi",
".",
"Serializer",
".",
"Marshal",
"(",
"g",
".",
"papi",
".",
"Node",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"g",
".",
"Logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"[",
"]",
"byte",
"{",
"}",
"\n",
"}",
"\n",
"return",
"buf",
"\n",
"}"
] |
// NodeMeta implementation of the memberlist.Delegate interface.
|
[
"NodeMeta",
"implementation",
"of",
"the",
"memberlist",
".",
"Delegate",
"interface",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L295-L302
|
train
|
pilosa/pilosa
|
gossip/gossip.go
|
NotifyMsg
|
func (g *memberSet) NotifyMsg(b []byte) {
err := g.papi.ClusterMessage(context.Background(), bytes.NewBuffer(b))
if err != nil {
g.Logger.Printf("cluster message error: %s", err)
}
}
|
go
|
func (g *memberSet) NotifyMsg(b []byte) {
err := g.papi.ClusterMessage(context.Background(), bytes.NewBuffer(b))
if err != nil {
g.Logger.Printf("cluster message error: %s", err)
}
}
|
[
"func",
"(",
"g",
"*",
"memberSet",
")",
"NotifyMsg",
"(",
"b",
"[",
"]",
"byte",
")",
"{",
"err",
":=",
"g",
".",
"papi",
".",
"ClusterMessage",
"(",
"context",
".",
"Background",
"(",
")",
",",
"bytes",
".",
"NewBuffer",
"(",
"b",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"g",
".",
"Logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] |
// NotifyMsg implementation of the memberlist.Delegate interface
// called when a user-data message is received.
|
[
"NotifyMsg",
"implementation",
"of",
"the",
"memberlist",
".",
"Delegate",
"interface",
"called",
"when",
"a",
"user",
"-",
"data",
"message",
"is",
"received",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L306-L311
|
train
|
pilosa/pilosa
|
gossip/gossip.go
|
GetBroadcasts
|
func (g *memberSet) GetBroadcasts(overhead, limit int) [][]byte {
return g.broadcasts.GetBroadcasts(overhead, limit)
}
|
go
|
func (g *memberSet) GetBroadcasts(overhead, limit int) [][]byte {
return g.broadcasts.GetBroadcasts(overhead, limit)
}
|
[
"func",
"(",
"g",
"*",
"memberSet",
")",
"GetBroadcasts",
"(",
"overhead",
",",
"limit",
"int",
")",
"[",
"]",
"[",
"]",
"byte",
"{",
"return",
"g",
".",
"broadcasts",
".",
"GetBroadcasts",
"(",
"overhead",
",",
"limit",
")",
"\n",
"}"
] |
// GetBroadcasts implementation of the memberlist.Delegate interface
// called when user data messages can be broadcast.
|
[
"GetBroadcasts",
"implementation",
"of",
"the",
"memberlist",
".",
"Delegate",
"interface",
"called",
"when",
"user",
"data",
"messages",
"can",
"be",
"broadcast",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L315-L317
|
train
|
pilosa/pilosa
|
gossip/gossip.go
|
LocalState
|
func (g *memberSet) LocalState(join bool) []byte {
m := &pilosa.NodeStatus{
Node: g.papi.Node(),
Schema: &pilosa.Schema{Indexes: g.papi.Schema(context.Background())},
}
for _, idx := range m.Schema.Indexes {
is := &pilosa.IndexStatus{Name: idx.Name}
for _, f := range idx.Fields {
availableShards := roaring.NewBitmap()
if field, _ := g.papi.Field(context.Background(), idx.Name, f.Name); field != nil {
availableShards = field.AvailableShards()
}
is.Fields = append(is.Fields, &pilosa.FieldStatus{
Name: f.Name,
AvailableShards: availableShards,
})
}
m.Indexes = append(m.Indexes, is)
}
// Marshal nodestate data to bytes.
buf, err := pilosa.MarshalInternalMessage(m, g.papi.Serializer)
if err != nil {
g.Logger.Printf("error marshalling nodestate data, err=%s", err)
return []byte{}
}
return buf
}
|
go
|
func (g *memberSet) LocalState(join bool) []byte {
m := &pilosa.NodeStatus{
Node: g.papi.Node(),
Schema: &pilosa.Schema{Indexes: g.papi.Schema(context.Background())},
}
for _, idx := range m.Schema.Indexes {
is := &pilosa.IndexStatus{Name: idx.Name}
for _, f := range idx.Fields {
availableShards := roaring.NewBitmap()
if field, _ := g.papi.Field(context.Background(), idx.Name, f.Name); field != nil {
availableShards = field.AvailableShards()
}
is.Fields = append(is.Fields, &pilosa.FieldStatus{
Name: f.Name,
AvailableShards: availableShards,
})
}
m.Indexes = append(m.Indexes, is)
}
// Marshal nodestate data to bytes.
buf, err := pilosa.MarshalInternalMessage(m, g.papi.Serializer)
if err != nil {
g.Logger.Printf("error marshalling nodestate data, err=%s", err)
return []byte{}
}
return buf
}
|
[
"func",
"(",
"g",
"*",
"memberSet",
")",
"LocalState",
"(",
"join",
"bool",
")",
"[",
"]",
"byte",
"{",
"m",
":=",
"&",
"pilosa",
".",
"NodeStatus",
"{",
"Node",
":",
"g",
".",
"papi",
".",
"Node",
"(",
")",
",",
"Schema",
":",
"&",
"pilosa",
".",
"Schema",
"{",
"Indexes",
":",
"g",
".",
"papi",
".",
"Schema",
"(",
"context",
".",
"Background",
"(",
")",
")",
"}",
",",
"}",
"\n",
"for",
"_",
",",
"idx",
":=",
"range",
"m",
".",
"Schema",
".",
"Indexes",
"{",
"is",
":=",
"&",
"pilosa",
".",
"IndexStatus",
"{",
"Name",
":",
"idx",
".",
"Name",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"idx",
".",
"Fields",
"{",
"availableShards",
":=",
"roaring",
".",
"NewBitmap",
"(",
")",
"\n",
"if",
"field",
",",
"_",
":=",
"g",
".",
"papi",
".",
"Field",
"(",
"context",
".",
"Background",
"(",
")",
",",
"idx",
".",
"Name",
",",
"f",
".",
"Name",
")",
";",
"field",
"!=",
"nil",
"{",
"availableShards",
"=",
"field",
".",
"AvailableShards",
"(",
")",
"\n",
"}",
"\n",
"is",
".",
"Fields",
"=",
"append",
"(",
"is",
".",
"Fields",
",",
"&",
"pilosa",
".",
"FieldStatus",
"{",
"Name",
":",
"f",
".",
"Name",
",",
"AvailableShards",
":",
"availableShards",
",",
"}",
")",
"\n",
"}",
"\n",
"m",
".",
"Indexes",
"=",
"append",
"(",
"m",
".",
"Indexes",
",",
"is",
")",
"\n",
"}",
"\n\n",
"// Marshal nodestate data to bytes.",
"buf",
",",
"err",
":=",
"pilosa",
".",
"MarshalInternalMessage",
"(",
"m",
",",
"g",
".",
"papi",
".",
"Serializer",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"g",
".",
"Logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"[",
"]",
"byte",
"{",
"}",
"\n",
"}",
"\n",
"return",
"buf",
"\n",
"}"
] |
// LocalState implementation of the memberlist.Delegate interface
// sends this Node's state data.
|
[
"LocalState",
"implementation",
"of",
"the",
"memberlist",
".",
"Delegate",
"interface",
"sends",
"this",
"Node",
"s",
"state",
"data",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L321-L348
|
train
|
pilosa/pilosa
|
gossip/gossip.go
|
MergeRemoteState
|
func (g *memberSet) MergeRemoteState(buf []byte, join bool) {
err := g.papi.ClusterMessage(context.Background(), bytes.NewBuffer(buf))
if err != nil {
g.Logger.Printf("merge state error: %s", err)
}
}
|
go
|
func (g *memberSet) MergeRemoteState(buf []byte, join bool) {
err := g.papi.ClusterMessage(context.Background(), bytes.NewBuffer(buf))
if err != nil {
g.Logger.Printf("merge state error: %s", err)
}
}
|
[
"func",
"(",
"g",
"*",
"memberSet",
")",
"MergeRemoteState",
"(",
"buf",
"[",
"]",
"byte",
",",
"join",
"bool",
")",
"{",
"err",
":=",
"g",
".",
"papi",
".",
"ClusterMessage",
"(",
"context",
".",
"Background",
"(",
")",
",",
"bytes",
".",
"NewBuffer",
"(",
"buf",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"g",
".",
"Logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] |
// MergeRemoteState implementation of the memberlist.Delegate interface
// receive and process the remote side's LocalState.
|
[
"MergeRemoteState",
"implementation",
"of",
"the",
"memberlist",
".",
"Delegate",
"interface",
"receive",
"and",
"process",
"the",
"remote",
"side",
"s",
"LocalState",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L352-L357
|
train
|
pilosa/pilosa
|
gossip/gossip.go
|
newEventReceiver
|
func newEventReceiver(logger logger.Logger, papi *pilosa.API) *eventReceiver {
ger := &eventReceiver{
ch: make(chan memberlist.NodeEvent, 1),
logger: logger,
papi: papi,
}
go ger.listen()
return ger
}
|
go
|
func newEventReceiver(logger logger.Logger, papi *pilosa.API) *eventReceiver {
ger := &eventReceiver{
ch: make(chan memberlist.NodeEvent, 1),
logger: logger,
papi: papi,
}
go ger.listen()
return ger
}
|
[
"func",
"newEventReceiver",
"(",
"logger",
"logger",
".",
"Logger",
",",
"papi",
"*",
"pilosa",
".",
"API",
")",
"*",
"eventReceiver",
"{",
"ger",
":=",
"&",
"eventReceiver",
"{",
"ch",
":",
"make",
"(",
"chan",
"memberlist",
".",
"NodeEvent",
",",
"1",
")",
",",
"logger",
":",
"logger",
",",
"papi",
":",
"papi",
",",
"}",
"\n",
"go",
"ger",
".",
"listen",
"(",
")",
"\n",
"return",
"ger",
"\n",
"}"
] |
// newEventReceiver returns a new instance of GossipEventReceiver.
|
[
"newEventReceiver",
"returns",
"a",
"new",
"instance",
"of",
"GossipEventReceiver",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L372-L380
|
train
|
pilosa/pilosa
|
gossip/gossip.go
|
newTransport
|
func newTransport(conf *memberlist.Config) (*memberlist.NetTransport, error) {
nc := &memberlist.NetTransportConfig{
BindAddrs: []string{conf.BindAddr},
BindPort: conf.BindPort,
Logger: conf.Logger,
}
// See comment below for details about the retry in here.
makeNetRetry := func(limit int) (*memberlist.NetTransport, error) {
var err error
for try := 0; try < limit; try++ {
var nt *memberlist.NetTransport
if nt, err = memberlist.NewNetTransport(nc); err == nil {
return nt, nil
}
if strings.Contains(err.Error(), "address already in use") {
conf.Logger.Printf("[DEBUG] Got bind error: %v", err)
continue
}
}
return nil, fmt.Errorf("failed to obtain an address: %v", err)
}
// The dynamic bind port operation is inherently racy because
// even though we are using the kernel to find a port for us, we
// are attempting to bind multiple protocols (and potentially
// multiple addresses) with the same port number. We build in a
// few retries here since this often gets transient errors in
// busy unit tests.
limit := 1
if conf.BindPort == 0 {
limit = 10
}
nt, err := makeNetRetry(limit)
if err != nil {
return nil, errors.Wrap(err, "could not set up network transport")
}
return nt, nil
}
|
go
|
func newTransport(conf *memberlist.Config) (*memberlist.NetTransport, error) {
nc := &memberlist.NetTransportConfig{
BindAddrs: []string{conf.BindAddr},
BindPort: conf.BindPort,
Logger: conf.Logger,
}
// See comment below for details about the retry in here.
makeNetRetry := func(limit int) (*memberlist.NetTransport, error) {
var err error
for try := 0; try < limit; try++ {
var nt *memberlist.NetTransport
if nt, err = memberlist.NewNetTransport(nc); err == nil {
return nt, nil
}
if strings.Contains(err.Error(), "address already in use") {
conf.Logger.Printf("[DEBUG] Got bind error: %v", err)
continue
}
}
return nil, fmt.Errorf("failed to obtain an address: %v", err)
}
// The dynamic bind port operation is inherently racy because
// even though we are using the kernel to find a port for us, we
// are attempting to bind multiple protocols (and potentially
// multiple addresses) with the same port number. We build in a
// few retries here since this often gets transient errors in
// busy unit tests.
limit := 1
if conf.BindPort == 0 {
limit = 10
}
nt, err := makeNetRetry(limit)
if err != nil {
return nil, errors.Wrap(err, "could not set up network transport")
}
return nt, nil
}
|
[
"func",
"newTransport",
"(",
"conf",
"*",
"memberlist",
".",
"Config",
")",
"(",
"*",
"memberlist",
".",
"NetTransport",
",",
"error",
")",
"{",
"nc",
":=",
"&",
"memberlist",
".",
"NetTransportConfig",
"{",
"BindAddrs",
":",
"[",
"]",
"string",
"{",
"conf",
".",
"BindAddr",
"}",
",",
"BindPort",
":",
"conf",
".",
"BindPort",
",",
"Logger",
":",
"conf",
".",
"Logger",
",",
"}",
"\n\n",
"// See comment below for details about the retry in here.",
"makeNetRetry",
":=",
"func",
"(",
"limit",
"int",
")",
"(",
"*",
"memberlist",
".",
"NetTransport",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"for",
"try",
":=",
"0",
";",
"try",
"<",
"limit",
";",
"try",
"++",
"{",
"var",
"nt",
"*",
"memberlist",
".",
"NetTransport",
"\n",
"if",
"nt",
",",
"err",
"=",
"memberlist",
".",
"NewNetTransport",
"(",
"nc",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"nt",
",",
"nil",
"\n",
"}",
"\n",
"if",
"strings",
".",
"Contains",
"(",
"err",
".",
"Error",
"(",
")",
",",
"\"",
"\"",
")",
"{",
"conf",
".",
"Logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// The dynamic bind port operation is inherently racy because",
"// even though we are using the kernel to find a port for us, we",
"// are attempting to bind multiple protocols (and potentially",
"// multiple addresses) with the same port number. We build in a",
"// few retries here since this often gets transient errors in",
"// busy unit tests.",
"limit",
":=",
"1",
"\n",
"if",
"conf",
".",
"BindPort",
"==",
"0",
"{",
"limit",
"=",
"10",
"\n",
"}",
"\n\n",
"nt",
",",
"err",
":=",
"makeNetRetry",
"(",
"limit",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nt",
",",
"nil",
"\n",
"}"
] |
// newTransport returns a NetTransport based on the memberlist configuration.
// It will dynamically bind to a port if conf.BindPort is 0.
|
[
"newTransport",
"returns",
"a",
"NetTransport",
"based",
"on",
"the",
"memberlist",
"configuration",
".",
"It",
"will",
"dynamically",
"bind",
"to",
"a",
"port",
"if",
"conf",
".",
"BindPort",
"is",
"0",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/gossip/gossip.go#L481-L522
|
train
|
pilosa/pilosa
|
pilosa.go
|
MarshalJSON
|
func (cas ColumnAttrSet) MarshalJSON() ([]byte, error) {
if cas.Key != "" {
return json.Marshal(struct {
Key string `json:"key,omitempty"`
Attrs map[string]interface{} `json:"attrs,omitempty"`
}{
Key: cas.Key,
Attrs: cas.Attrs,
})
}
return json.Marshal(struct {
ID uint64 `json:"id"`
Attrs map[string]interface{} `json:"attrs,omitempty"`
}{
ID: cas.ID,
Attrs: cas.Attrs,
})
}
|
go
|
func (cas ColumnAttrSet) MarshalJSON() ([]byte, error) {
if cas.Key != "" {
return json.Marshal(struct {
Key string `json:"key,omitempty"`
Attrs map[string]interface{} `json:"attrs,omitempty"`
}{
Key: cas.Key,
Attrs: cas.Attrs,
})
}
return json.Marshal(struct {
ID uint64 `json:"id"`
Attrs map[string]interface{} `json:"attrs,omitempty"`
}{
ID: cas.ID,
Attrs: cas.Attrs,
})
}
|
[
"func",
"(",
"cas",
"ColumnAttrSet",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"cas",
".",
"Key",
"!=",
"\"",
"\"",
"{",
"return",
"json",
".",
"Marshal",
"(",
"struct",
"{",
"Key",
"string",
"`json:\"key,omitempty\"`",
"\n",
"Attrs",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"`json:\"attrs,omitempty\"`",
"\n",
"}",
"{",
"Key",
":",
"cas",
".",
"Key",
",",
"Attrs",
":",
"cas",
".",
"Attrs",
",",
"}",
")",
"\n",
"}",
"\n",
"return",
"json",
".",
"Marshal",
"(",
"struct",
"{",
"ID",
"uint64",
"`json:\"id\"`",
"\n",
"Attrs",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"`json:\"attrs,omitempty\"`",
"\n",
"}",
"{",
"ID",
":",
"cas",
".",
"ID",
",",
"Attrs",
":",
"cas",
".",
"Attrs",
",",
"}",
")",
"\n",
"}"
] |
// MarshalJSON marshals the ColumnAttrSet to JSON such that
// either a Key or an ID is included.
|
[
"MarshalJSON",
"marshals",
"the",
"ColumnAttrSet",
"to",
"JSON",
"such",
"that",
"either",
"a",
"Key",
"or",
"an",
"ID",
"is",
"included",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pilosa.go#L133-L150
|
train
|
pilosa/pilosa
|
pilosa.go
|
validateName
|
func validateName(name string) error {
if !nameRegexp.Match([]byte(name)) {
return errors.Wrapf(ErrName, "'%s'", name)
}
return nil
}
|
go
|
func validateName(name string) error {
if !nameRegexp.Match([]byte(name)) {
return errors.Wrapf(ErrName, "'%s'", name)
}
return nil
}
|
[
"func",
"validateName",
"(",
"name",
"string",
")",
"error",
"{",
"if",
"!",
"nameRegexp",
".",
"Match",
"(",
"[",
"]",
"byte",
"(",
"name",
")",
")",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"ErrName",
",",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// validateName ensures that the name is a valid format.
|
[
"validateName",
"ensures",
"that",
"the",
"name",
"is",
"a",
"valid",
"format",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pilosa.go#L156-L161
|
train
|
pilosa/pilosa
|
pilosa.go
|
AddressWithDefaults
|
func AddressWithDefaults(addr string) (*URI, error) {
if addr == "" {
return defaultURI(), nil
}
return NewURIFromAddress(addr)
}
|
go
|
func AddressWithDefaults(addr string) (*URI, error) {
if addr == "" {
return defaultURI(), nil
}
return NewURIFromAddress(addr)
}
|
[
"func",
"AddressWithDefaults",
"(",
"addr",
"string",
")",
"(",
"*",
"URI",
",",
"error",
")",
"{",
"if",
"addr",
"==",
"\"",
"\"",
"{",
"return",
"defaultURI",
"(",
")",
",",
"nil",
"\n",
"}",
"\n",
"return",
"NewURIFromAddress",
"(",
"addr",
")",
"\n",
"}"
] |
// AddressWithDefaults converts addr into a valid address,
// using defaults when necessary.
|
[
"AddressWithDefaults",
"converts",
"addr",
"into",
"a",
"valid",
"address",
"using",
"defaults",
"when",
"necessary",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/pilosa.go#L189-L194
|
train
|
pilosa/pilosa
|
lru/lru.go
|
clear
|
func (c *Cache) clear() { // nolint: staticcheck,unused
if c.OnEvicted != nil {
for _, e := range c.cache {
kv := e.Value.(*entry)
c.OnEvicted(kv.key, kv.value)
}
}
c.ll = nil
c.cache = nil
}
|
go
|
func (c *Cache) clear() { // nolint: staticcheck,unused
if c.OnEvicted != nil {
for _, e := range c.cache {
kv := e.Value.(*entry)
c.OnEvicted(kv.key, kv.value)
}
}
c.ll = nil
c.cache = nil
}
|
[
"func",
"(",
"c",
"*",
"Cache",
")",
"clear",
"(",
")",
"{",
"// nolint: staticcheck,unused",
"if",
"c",
".",
"OnEvicted",
"!=",
"nil",
"{",
"for",
"_",
",",
"e",
":=",
"range",
"c",
".",
"cache",
"{",
"kv",
":=",
"e",
".",
"Value",
".",
"(",
"*",
"entry",
")",
"\n",
"c",
".",
"OnEvicted",
"(",
"kv",
".",
"key",
",",
"kv",
".",
"value",
")",
"\n",
"}",
"\n",
"}",
"\n",
"c",
".",
"ll",
"=",
"nil",
"\n",
"c",
".",
"cache",
"=",
"nil",
"\n",
"}"
] |
// clear purges all stored items from the cache.
|
[
"clear",
"purges",
"all",
"stored",
"items",
"from",
"the",
"cache",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/lru/lru.go#L124-L133
|
train
|
pilosa/pilosa
|
ctl/common.go
|
SetTLSConfig
|
func SetTLSConfig(flags *pflag.FlagSet, certificatePath *string, certificateKeyPath *string, skipVerify *bool) {
flags.StringVarP(certificatePath, "tls.certificate", "", "", "TLS certificate path (usually has the .crt or .pem extension")
flags.StringVarP(certificateKeyPath, "tls.key", "", "", "TLS certificate key path (usually has the .key extension")
flags.BoolVarP(skipVerify, "tls.skip-verify", "", false, "Skip TLS certificate verification (not secure)")
}
|
go
|
func SetTLSConfig(flags *pflag.FlagSet, certificatePath *string, certificateKeyPath *string, skipVerify *bool) {
flags.StringVarP(certificatePath, "tls.certificate", "", "", "TLS certificate path (usually has the .crt or .pem extension")
flags.StringVarP(certificateKeyPath, "tls.key", "", "", "TLS certificate key path (usually has the .key extension")
flags.BoolVarP(skipVerify, "tls.skip-verify", "", false, "Skip TLS certificate verification (not secure)")
}
|
[
"func",
"SetTLSConfig",
"(",
"flags",
"*",
"pflag",
".",
"FlagSet",
",",
"certificatePath",
"*",
"string",
",",
"certificateKeyPath",
"*",
"string",
",",
"skipVerify",
"*",
"bool",
")",
"{",
"flags",
".",
"StringVarP",
"(",
"certificatePath",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"flags",
".",
"StringVarP",
"(",
"certificateKeyPath",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"flags",
".",
"BoolVarP",
"(",
"skipVerify",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"false",
",",
"\"",
"\"",
")",
"\n",
"}"
] |
// SetTLSConfig creates common TLS flags
|
[
"SetTLSConfig",
"creates",
"common",
"TLS",
"flags"
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/ctl/common.go#L33-L37
|
train
|
pilosa/pilosa
|
ctl/common.go
|
commandClient
|
func commandClient(cmd CommandWithTLSSupport) (*http.InternalClient, error) {
tlsConfig := cmd.TLSConfiguration()
var TLSConfig *tls.Config
if tlsConfig.CertificatePath != "" && tlsConfig.CertificateKeyPath != "" {
cert, err := tls.LoadX509KeyPair(tlsConfig.CertificatePath, tlsConfig.CertificateKeyPath)
if err != nil {
return nil, errors.Wrap(err, "loading keypair")
}
TLSConfig = &tls.Config{
Certificates: []tls.Certificate{cert},
InsecureSkipVerify: tlsConfig.SkipVerify,
}
}
client, err := http.NewInternalClient(cmd.TLSHost(), http.GetHTTPClient(TLSConfig))
if err != nil {
return nil, errors.Wrap(err, "getting internal client")
}
return client, err
}
|
go
|
func commandClient(cmd CommandWithTLSSupport) (*http.InternalClient, error) {
tlsConfig := cmd.TLSConfiguration()
var TLSConfig *tls.Config
if tlsConfig.CertificatePath != "" && tlsConfig.CertificateKeyPath != "" {
cert, err := tls.LoadX509KeyPair(tlsConfig.CertificatePath, tlsConfig.CertificateKeyPath)
if err != nil {
return nil, errors.Wrap(err, "loading keypair")
}
TLSConfig = &tls.Config{
Certificates: []tls.Certificate{cert},
InsecureSkipVerify: tlsConfig.SkipVerify,
}
}
client, err := http.NewInternalClient(cmd.TLSHost(), http.GetHTTPClient(TLSConfig))
if err != nil {
return nil, errors.Wrap(err, "getting internal client")
}
return client, err
}
|
[
"func",
"commandClient",
"(",
"cmd",
"CommandWithTLSSupport",
")",
"(",
"*",
"http",
".",
"InternalClient",
",",
"error",
")",
"{",
"tlsConfig",
":=",
"cmd",
".",
"TLSConfiguration",
"(",
")",
"\n",
"var",
"TLSConfig",
"*",
"tls",
".",
"Config",
"\n",
"if",
"tlsConfig",
".",
"CertificatePath",
"!=",
"\"",
"\"",
"&&",
"tlsConfig",
".",
"CertificateKeyPath",
"!=",
"\"",
"\"",
"{",
"cert",
",",
"err",
":=",
"tls",
".",
"LoadX509KeyPair",
"(",
"tlsConfig",
".",
"CertificatePath",
",",
"tlsConfig",
".",
"CertificateKeyPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"TLSConfig",
"=",
"&",
"tls",
".",
"Config",
"{",
"Certificates",
":",
"[",
"]",
"tls",
".",
"Certificate",
"{",
"cert",
"}",
",",
"InsecureSkipVerify",
":",
"tlsConfig",
".",
"SkipVerify",
",",
"}",
"\n",
"}",
"\n",
"client",
",",
"err",
":=",
"http",
".",
"NewInternalClient",
"(",
"cmd",
".",
"TLSHost",
"(",
")",
",",
"http",
".",
"GetHTTPClient",
"(",
"TLSConfig",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"client",
",",
"err",
"\n",
"}"
] |
// commandClient returns a pilosa.InternalHTTPClient for the command
|
[
"commandClient",
"returns",
"a",
"pilosa",
".",
"InternalHTTPClient",
"for",
"the",
"command"
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/ctl/common.go#L40-L58
|
train
|
pilosa/pilosa
|
cache.go
|
newLRUCache
|
func newLRUCache(maxEntries uint32) *lruCache {
c := &lruCache{
cache: lru.New(int(maxEntries)),
counts: make(map[uint64]uint64),
stats: stats.NopStatsClient,
}
c.cache.OnEvicted = c.onEvicted
return c
}
|
go
|
func newLRUCache(maxEntries uint32) *lruCache {
c := &lruCache{
cache: lru.New(int(maxEntries)),
counts: make(map[uint64]uint64),
stats: stats.NopStatsClient,
}
c.cache.OnEvicted = c.onEvicted
return c
}
|
[
"func",
"newLRUCache",
"(",
"maxEntries",
"uint32",
")",
"*",
"lruCache",
"{",
"c",
":=",
"&",
"lruCache",
"{",
"cache",
":",
"lru",
".",
"New",
"(",
"int",
"(",
"maxEntries",
")",
")",
",",
"counts",
":",
"make",
"(",
"map",
"[",
"uint64",
"]",
"uint64",
")",
",",
"stats",
":",
"stats",
".",
"NopStatsClient",
",",
"}",
"\n",
"c",
".",
"cache",
".",
"OnEvicted",
"=",
"c",
".",
"onEvicted",
"\n",
"return",
"c",
"\n",
"}"
] |
// newLRUCache returns a new instance of LRUCache.
|
[
"newLRUCache",
"returns",
"a",
"new",
"instance",
"of",
"LRUCache",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L65-L73
|
train
|
pilosa/pilosa
|
cache.go
|
Top
|
func (c *lruCache) Top() []bitmapPair {
a := make([]bitmapPair, 0, len(c.counts))
for id, n := range c.counts {
a = append(a, bitmapPair{
ID: id,
Count: n,
})
}
sort.Sort(bitmapPairs(a))
return a
}
|
go
|
func (c *lruCache) Top() []bitmapPair {
a := make([]bitmapPair, 0, len(c.counts))
for id, n := range c.counts {
a = append(a, bitmapPair{
ID: id,
Count: n,
})
}
sort.Sort(bitmapPairs(a))
return a
}
|
[
"func",
"(",
"c",
"*",
"lruCache",
")",
"Top",
"(",
")",
"[",
"]",
"bitmapPair",
"{",
"a",
":=",
"make",
"(",
"[",
"]",
"bitmapPair",
",",
"0",
",",
"len",
"(",
"c",
".",
"counts",
")",
")",
"\n",
"for",
"id",
",",
"n",
":=",
"range",
"c",
".",
"counts",
"{",
"a",
"=",
"append",
"(",
"a",
",",
"bitmapPair",
"{",
"ID",
":",
"id",
",",
"Count",
":",
"n",
",",
"}",
")",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"bitmapPairs",
"(",
"a",
")",
")",
"\n",
"return",
"a",
"\n",
"}"
] |
// Top returns all counts in the cache.
|
[
"Top",
"returns",
"all",
"counts",
"in",
"the",
"cache",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L113-L123
|
train
|
pilosa/pilosa
|
cache.go
|
NewRankCache
|
func NewRankCache(maxEntries uint32) *rankCache {
return &rankCache{
maxEntries: maxEntries,
thresholdBuffer: int(thresholdFactor * float64(maxEntries)),
entries: make(map[uint64]uint64),
stats: stats.NopStatsClient,
}
}
|
go
|
func NewRankCache(maxEntries uint32) *rankCache {
return &rankCache{
maxEntries: maxEntries,
thresholdBuffer: int(thresholdFactor * float64(maxEntries)),
entries: make(map[uint64]uint64),
stats: stats.NopStatsClient,
}
}
|
[
"func",
"NewRankCache",
"(",
"maxEntries",
"uint32",
")",
"*",
"rankCache",
"{",
"return",
"&",
"rankCache",
"{",
"maxEntries",
":",
"maxEntries",
",",
"thresholdBuffer",
":",
"int",
"(",
"thresholdFactor",
"*",
"float64",
"(",
"maxEntries",
")",
")",
",",
"entries",
":",
"make",
"(",
"map",
"[",
"uint64",
"]",
"uint64",
")",
",",
"stats",
":",
"stats",
".",
"NopStatsClient",
",",
"}",
"\n",
"}"
] |
// NewRankCache returns a new instance of RankCache.
|
[
"NewRankCache",
"returns",
"a",
"new",
"instance",
"of",
"RankCache",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L158-L165
|
train
|
pilosa/pilosa
|
cache.go
|
Invalidate
|
func (c *rankCache) Invalidate() {
c.mu.Lock()
defer c.mu.Unlock()
c.invalidate()
}
|
go
|
func (c *rankCache) Invalidate() {
c.mu.Lock()
defer c.mu.Unlock()
c.invalidate()
}
|
[
"func",
"(",
"c",
"*",
"rankCache",
")",
"Invalidate",
"(",
")",
"{",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"c",
".",
"invalidate",
"(",
")",
"\n",
"}"
] |
// Invalidate recalculates the entries by rank.
|
[
"Invalidate",
"recalculates",
"the",
"entries",
"by",
"rank",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L221-L225
|
train
|
pilosa/pilosa
|
cache.go
|
Recalculate
|
func (c *rankCache) Recalculate() {
c.mu.Lock()
defer c.mu.Unlock()
c.stats.Count("cache.recalculate", 1, 1.0)
c.recalculate()
}
|
go
|
func (c *rankCache) Recalculate() {
c.mu.Lock()
defer c.mu.Unlock()
c.stats.Count("cache.recalculate", 1, 1.0)
c.recalculate()
}
|
[
"func",
"(",
"c",
"*",
"rankCache",
")",
"Recalculate",
"(",
")",
"{",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"c",
".",
"stats",
".",
"Count",
"(",
"\"",
"\"",
",",
"1",
",",
"1.0",
")",
"\n",
"c",
".",
"recalculate",
"(",
")",
"\n",
"}"
] |
// Recalculate rebuilds the cache.
|
[
"Recalculate",
"rebuilds",
"the",
"cache",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L228-L233
|
train
|
pilosa/pilosa
|
cache.go
|
WriteTo
|
func (c *rankCache) WriteTo(w io.Writer) (n int64, err error) {
panic("FIXME: TODO")
}
|
go
|
func (c *rankCache) WriteTo(w io.Writer) (n int64, err error) {
panic("FIXME: TODO")
}
|
[
"func",
"(",
"c",
"*",
"rankCache",
")",
"WriteTo",
"(",
"w",
"io",
".",
"Writer",
")",
"(",
"n",
"int64",
",",
"err",
"error",
")",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}"
] |
// WriteTo writes the cache to w.
|
[
"WriteTo",
"writes",
"the",
"cache",
"to",
"w",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L291-L293
|
train
|
pilosa/pilosa
|
cache.go
|
ReadFrom
|
func (c *rankCache) ReadFrom(r io.Reader) (n int64, err error) {
panic("FIXME: TODO")
}
|
go
|
func (c *rankCache) ReadFrom(r io.Reader) (n int64, err error) {
panic("FIXME: TODO")
}
|
[
"func",
"(",
"c",
"*",
"rankCache",
")",
"ReadFrom",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"n",
"int64",
",",
"err",
"error",
")",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}"
] |
// ReadFrom read from r into the cache.
|
[
"ReadFrom",
"read",
"from",
"r",
"into",
"the",
"cache",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L296-L298
|
train
|
pilosa/pilosa
|
cache.go
|
Pop
|
func (p *Pairs) Pop() interface{} {
old := *p
n := len(old)
x := old[n-1]
*p = old[0 : n-1]
return x
}
|
go
|
func (p *Pairs) Pop() interface{} {
old := *p
n := len(old)
x := old[n-1]
*p = old[0 : n-1]
return x
}
|
[
"func",
"(",
"p",
"*",
"Pairs",
")",
"Pop",
"(",
")",
"interface",
"{",
"}",
"{",
"old",
":=",
"*",
"p",
"\n",
"n",
":=",
"len",
"(",
"old",
")",
"\n",
"x",
":=",
"old",
"[",
"n",
"-",
"1",
"]",
"\n",
"*",
"p",
"=",
"old",
"[",
"0",
":",
"n",
"-",
"1",
"]",
"\n",
"return",
"x",
"\n",
"}"
] |
// Pop removes the minimum element from the Pair slice.
|
[
"Pop",
"removes",
"the",
"minimum",
"element",
"from",
"the",
"Pair",
"slice",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L347-L353
|
train
|
pilosa/pilosa
|
cache.go
|
Add
|
func (p Pairs) Add(other []Pair) []Pair {
// Create lookup of key/counts.
m := make(map[uint64]uint64, len(p))
for _, pair := range p {
m[pair.ID] = pair.Count
}
// Add/merge from other.
for _, pair := range other {
m[pair.ID] += pair.Count
}
// Convert back to slice.
a := make([]Pair, 0, len(m))
for k, v := range m {
a = append(a, Pair{ID: k, Count: v})
}
return a
}
|
go
|
func (p Pairs) Add(other []Pair) []Pair {
// Create lookup of key/counts.
m := make(map[uint64]uint64, len(p))
for _, pair := range p {
m[pair.ID] = pair.Count
}
// Add/merge from other.
for _, pair := range other {
m[pair.ID] += pair.Count
}
// Convert back to slice.
a := make([]Pair, 0, len(m))
for k, v := range m {
a = append(a, Pair{ID: k, Count: v})
}
return a
}
|
[
"func",
"(",
"p",
"Pairs",
")",
"Add",
"(",
"other",
"[",
"]",
"Pair",
")",
"[",
"]",
"Pair",
"{",
"// Create lookup of key/counts.",
"m",
":=",
"make",
"(",
"map",
"[",
"uint64",
"]",
"uint64",
",",
"len",
"(",
"p",
")",
")",
"\n",
"for",
"_",
",",
"pair",
":=",
"range",
"p",
"{",
"m",
"[",
"pair",
".",
"ID",
"]",
"=",
"pair",
".",
"Count",
"\n",
"}",
"\n\n",
"// Add/merge from other.",
"for",
"_",
",",
"pair",
":=",
"range",
"other",
"{",
"m",
"[",
"pair",
".",
"ID",
"]",
"+=",
"pair",
".",
"Count",
"\n",
"}",
"\n\n",
"// Convert back to slice.",
"a",
":=",
"make",
"(",
"[",
"]",
"Pair",
",",
"0",
",",
"len",
"(",
"m",
")",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"m",
"{",
"a",
"=",
"append",
"(",
"a",
",",
"Pair",
"{",
"ID",
":",
"k",
",",
"Count",
":",
"v",
"}",
")",
"\n",
"}",
"\n",
"return",
"a",
"\n",
"}"
] |
// Add merges other into p and returns a new slice.
|
[
"Add",
"merges",
"other",
"into",
"p",
"and",
"returns",
"a",
"new",
"slice",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L356-L374
|
train
|
pilosa/pilosa
|
cache.go
|
Keys
|
func (p Pairs) Keys() []uint64 {
a := make([]uint64, len(p))
for i := range p {
a[i] = p[i].ID
}
return a
}
|
go
|
func (p Pairs) Keys() []uint64 {
a := make([]uint64, len(p))
for i := range p {
a[i] = p[i].ID
}
return a
}
|
[
"func",
"(",
"p",
"Pairs",
")",
"Keys",
"(",
")",
"[",
"]",
"uint64",
"{",
"a",
":=",
"make",
"(",
"[",
"]",
"uint64",
",",
"len",
"(",
"p",
")",
")",
"\n",
"for",
"i",
":=",
"range",
"p",
"{",
"a",
"[",
"i",
"]",
"=",
"p",
"[",
"i",
"]",
".",
"ID",
"\n",
"}",
"\n",
"return",
"a",
"\n",
"}"
] |
// Keys returns a slice of all keys in p.
|
[
"Keys",
"returns",
"a",
"slice",
"of",
"all",
"keys",
"in",
"p",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L377-L383
|
train
|
pilosa/pilosa
|
cache.go
|
merge
|
func (p uint64Slice) merge(other []uint64) []uint64 {
ret := make([]uint64, 0, len(p))
i, j := 0, 0
for i < len(p) && j < len(other) {
a, b := p[i], other[j]
if a == b {
ret = append(ret, a)
i, j = i+1, j+1
} else if a < b {
ret = append(ret, a)
i++
} else {
ret = append(ret, b)
j++
}
}
if i < len(p) {
ret = append(ret, p[i:]...)
} else if j < len(other) {
ret = append(ret, other[j:]...)
}
return ret
}
|
go
|
func (p uint64Slice) merge(other []uint64) []uint64 {
ret := make([]uint64, 0, len(p))
i, j := 0, 0
for i < len(p) && j < len(other) {
a, b := p[i], other[j]
if a == b {
ret = append(ret, a)
i, j = i+1, j+1
} else if a < b {
ret = append(ret, a)
i++
} else {
ret = append(ret, b)
j++
}
}
if i < len(p) {
ret = append(ret, p[i:]...)
} else if j < len(other) {
ret = append(ret, other[j:]...)
}
return ret
}
|
[
"func",
"(",
"p",
"uint64Slice",
")",
"merge",
"(",
"other",
"[",
"]",
"uint64",
")",
"[",
"]",
"uint64",
"{",
"ret",
":=",
"make",
"(",
"[",
"]",
"uint64",
",",
"0",
",",
"len",
"(",
"p",
")",
")",
"\n\n",
"i",
",",
"j",
":=",
"0",
",",
"0",
"\n",
"for",
"i",
"<",
"len",
"(",
"p",
")",
"&&",
"j",
"<",
"len",
"(",
"other",
")",
"{",
"a",
",",
"b",
":=",
"p",
"[",
"i",
"]",
",",
"other",
"[",
"j",
"]",
"\n",
"if",
"a",
"==",
"b",
"{",
"ret",
"=",
"append",
"(",
"ret",
",",
"a",
")",
"\n",
"i",
",",
"j",
"=",
"i",
"+",
"1",
",",
"j",
"+",
"1",
"\n",
"}",
"else",
"if",
"a",
"<",
"b",
"{",
"ret",
"=",
"append",
"(",
"ret",
",",
"a",
")",
"\n",
"i",
"++",
"\n",
"}",
"else",
"{",
"ret",
"=",
"append",
"(",
"ret",
",",
"b",
")",
"\n",
"j",
"++",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"i",
"<",
"len",
"(",
"p",
")",
"{",
"ret",
"=",
"append",
"(",
"ret",
",",
"p",
"[",
"i",
":",
"]",
"...",
")",
"\n",
"}",
"else",
"if",
"j",
"<",
"len",
"(",
"other",
")",
"{",
"ret",
"=",
"append",
"(",
"ret",
",",
"other",
"[",
"j",
":",
"]",
"...",
")",
"\n",
"}",
"\n\n",
"return",
"ret",
"\n",
"}"
] |
// merge combines p and other to a unique sorted set of values.
// p and other must both have unique sets and be sorted.
|
[
"merge",
"combines",
"p",
"and",
"other",
"to",
"a",
"unique",
"sorted",
"set",
"of",
"values",
".",
"p",
"and",
"other",
"must",
"both",
"have",
"unique",
"sets",
"and",
"be",
"sorted",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L407-L432
|
train
|
pilosa/pilosa
|
cache.go
|
Fetch
|
func (s *simpleCache) Fetch(id uint64) (*Row, bool) {
m, ok := s.cache[id]
return m, ok
}
|
go
|
func (s *simpleCache) Fetch(id uint64) (*Row, bool) {
m, ok := s.cache[id]
return m, ok
}
|
[
"func",
"(",
"s",
"*",
"simpleCache",
")",
"Fetch",
"(",
"id",
"uint64",
")",
"(",
"*",
"Row",
",",
"bool",
")",
"{",
"m",
",",
"ok",
":=",
"s",
".",
"cache",
"[",
"id",
"]",
"\n",
"return",
"m",
",",
"ok",
"\n",
"}"
] |
// Fetch retrieves the bitmap at the id in the cache.
|
[
"Fetch",
"retrieves",
"the",
"bitmap",
"at",
"the",
"id",
"in",
"the",
"cache",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L450-L453
|
train
|
pilosa/pilosa
|
cache.go
|
Add
|
func (s *simpleCache) Add(id uint64, b *Row) {
s.cache[id] = b
}
|
go
|
func (s *simpleCache) Add(id uint64, b *Row) {
s.cache[id] = b
}
|
[
"func",
"(",
"s",
"*",
"simpleCache",
")",
"Add",
"(",
"id",
"uint64",
",",
"b",
"*",
"Row",
")",
"{",
"s",
".",
"cache",
"[",
"id",
"]",
"=",
"b",
"\n",
"}"
] |
// Add adds the bitmap to the cache, keyed on the id.
|
[
"Add",
"adds",
"the",
"bitmap",
"to",
"the",
"cache",
"keyed",
"on",
"the",
"id",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cache.go#L456-L458
|
train
|
pilosa/pilosa
|
cluster.go
|
Contains
|
func (a Nodes) Contains(n *Node) bool {
for i := range a {
if a[i] == n {
return true
}
}
return false
}
|
go
|
func (a Nodes) Contains(n *Node) bool {
for i := range a {
if a[i] == n {
return true
}
}
return false
}
|
[
"func",
"(",
"a",
"Nodes",
")",
"Contains",
"(",
"n",
"*",
"Node",
")",
"bool",
"{",
"for",
"i",
":=",
"range",
"a",
"{",
"if",
"a",
"[",
"i",
"]",
"==",
"n",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// Contains returns true if a node exists in the list.
|
[
"Contains",
"returns",
"true",
"if",
"a",
"node",
"exists",
"in",
"the",
"list",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L80-L87
|
train
|
pilosa/pilosa
|
cluster.go
|
ContainsID
|
func (a Nodes) ContainsID(id string) bool {
for _, n := range a {
if n.ID == id {
return true
}
}
return false
}
|
go
|
func (a Nodes) ContainsID(id string) bool {
for _, n := range a {
if n.ID == id {
return true
}
}
return false
}
|
[
"func",
"(",
"a",
"Nodes",
")",
"ContainsID",
"(",
"id",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"n",
":=",
"range",
"a",
"{",
"if",
"n",
".",
"ID",
"==",
"id",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// ContainsID returns true if host matches one of the node's id.
|
[
"ContainsID",
"returns",
"true",
"if",
"host",
"matches",
"one",
"of",
"the",
"node",
"s",
"id",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L90-L97
|
train
|
pilosa/pilosa
|
cluster.go
|
Filter
|
func (a Nodes) Filter(n *Node) []*Node {
other := make([]*Node, 0, len(a))
for i := range a {
if a[i] != n {
other = append(other, a[i])
}
}
return other
}
|
go
|
func (a Nodes) Filter(n *Node) []*Node {
other := make([]*Node, 0, len(a))
for i := range a {
if a[i] != n {
other = append(other, a[i])
}
}
return other
}
|
[
"func",
"(",
"a",
"Nodes",
")",
"Filter",
"(",
"n",
"*",
"Node",
")",
"[",
"]",
"*",
"Node",
"{",
"other",
":=",
"make",
"(",
"[",
"]",
"*",
"Node",
",",
"0",
",",
"len",
"(",
"a",
")",
")",
"\n",
"for",
"i",
":=",
"range",
"a",
"{",
"if",
"a",
"[",
"i",
"]",
"!=",
"n",
"{",
"other",
"=",
"append",
"(",
"other",
",",
"a",
"[",
"i",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"other",
"\n",
"}"
] |
// Filter returns a new list of nodes with node removed.
|
[
"Filter",
"returns",
"a",
"new",
"list",
"of",
"nodes",
"with",
"node",
"removed",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L100-L108
|
train
|
pilosa/pilosa
|
cluster.go
|
FilterID
|
func (a Nodes) FilterID(id string) []*Node {
other := make([]*Node, 0, len(a))
for _, node := range a {
if node.ID != id {
other = append(other, node)
}
}
return other
}
|
go
|
func (a Nodes) FilterID(id string) []*Node {
other := make([]*Node, 0, len(a))
for _, node := range a {
if node.ID != id {
other = append(other, node)
}
}
return other
}
|
[
"func",
"(",
"a",
"Nodes",
")",
"FilterID",
"(",
"id",
"string",
")",
"[",
"]",
"*",
"Node",
"{",
"other",
":=",
"make",
"(",
"[",
"]",
"*",
"Node",
",",
"0",
",",
"len",
"(",
"a",
")",
")",
"\n",
"for",
"_",
",",
"node",
":=",
"range",
"a",
"{",
"if",
"node",
".",
"ID",
"!=",
"id",
"{",
"other",
"=",
"append",
"(",
"other",
",",
"node",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"other",
"\n",
"}"
] |
// FilterID returns a new list of nodes with ID removed.
|
[
"FilterID",
"returns",
"a",
"new",
"list",
"of",
"nodes",
"with",
"ID",
"removed",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L111-L119
|
train
|
pilosa/pilosa
|
cluster.go
|
FilterURI
|
func (a Nodes) FilterURI(uri URI) []*Node {
other := make([]*Node, 0, len(a))
for _, node := range a {
if node.URI != uri {
other = append(other, node)
}
}
return other
}
|
go
|
func (a Nodes) FilterURI(uri URI) []*Node {
other := make([]*Node, 0, len(a))
for _, node := range a {
if node.URI != uri {
other = append(other, node)
}
}
return other
}
|
[
"func",
"(",
"a",
"Nodes",
")",
"FilterURI",
"(",
"uri",
"URI",
")",
"[",
"]",
"*",
"Node",
"{",
"other",
":=",
"make",
"(",
"[",
"]",
"*",
"Node",
",",
"0",
",",
"len",
"(",
"a",
")",
")",
"\n",
"for",
"_",
",",
"node",
":=",
"range",
"a",
"{",
"if",
"node",
".",
"URI",
"!=",
"uri",
"{",
"other",
"=",
"append",
"(",
"other",
",",
"node",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"other",
"\n",
"}"
] |
// FilterURI returns a new list of nodes with URI removed.
|
[
"FilterURI",
"returns",
"a",
"new",
"list",
"of",
"nodes",
"with",
"URI",
"removed",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L122-L130
|
train
|
pilosa/pilosa
|
cluster.go
|
IDs
|
func (a Nodes) IDs() []string {
ids := make([]string, len(a))
for i, n := range a {
ids[i] = n.ID
}
return ids
}
|
go
|
func (a Nodes) IDs() []string {
ids := make([]string, len(a))
for i, n := range a {
ids[i] = n.ID
}
return ids
}
|
[
"func",
"(",
"a",
"Nodes",
")",
"IDs",
"(",
")",
"[",
"]",
"string",
"{",
"ids",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"a",
")",
")",
"\n",
"for",
"i",
",",
"n",
":=",
"range",
"a",
"{",
"ids",
"[",
"i",
"]",
"=",
"n",
".",
"ID",
"\n",
"}",
"\n",
"return",
"ids",
"\n",
"}"
] |
// IDs returns a list of all node IDs.
|
[
"IDs",
"returns",
"a",
"list",
"of",
"all",
"node",
"IDs",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L133-L139
|
train
|
pilosa/pilosa
|
cluster.go
|
URIs
|
func (a Nodes) URIs() []URI {
uris := make([]URI, len(a))
for i, n := range a {
uris[i] = n.URI
}
return uris
}
|
go
|
func (a Nodes) URIs() []URI {
uris := make([]URI, len(a))
for i, n := range a {
uris[i] = n.URI
}
return uris
}
|
[
"func",
"(",
"a",
"Nodes",
")",
"URIs",
"(",
")",
"[",
"]",
"URI",
"{",
"uris",
":=",
"make",
"(",
"[",
"]",
"URI",
",",
"len",
"(",
"a",
")",
")",
"\n",
"for",
"i",
",",
"n",
":=",
"range",
"a",
"{",
"uris",
"[",
"i",
"]",
"=",
"n",
".",
"URI",
"\n",
"}",
"\n",
"return",
"uris",
"\n",
"}"
] |
// URIs returns a list of all uris.
|
[
"URIs",
"returns",
"a",
"list",
"of",
"all",
"uris",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L142-L148
|
train
|
pilosa/pilosa
|
cluster.go
|
Clone
|
func (a Nodes) Clone() []*Node {
other := make([]*Node, len(a))
copy(other, a)
return other
}
|
go
|
func (a Nodes) Clone() []*Node {
other := make([]*Node, len(a))
copy(other, a)
return other
}
|
[
"func",
"(",
"a",
"Nodes",
")",
"Clone",
"(",
")",
"[",
"]",
"*",
"Node",
"{",
"other",
":=",
"make",
"(",
"[",
"]",
"*",
"Node",
",",
"len",
"(",
"a",
")",
")",
"\n",
"copy",
"(",
"other",
",",
"a",
")",
"\n",
"return",
"other",
"\n",
"}"
] |
// Clone returns a shallow copy of nodes.
|
[
"Clone",
"returns",
"a",
"shallow",
"copy",
"of",
"nodes",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L151-L155
|
train
|
pilosa/pilosa
|
cluster.go
|
newCluster
|
func newCluster() *cluster {
return &cluster{
Hasher: &jmphasher{},
partitionN: defaultPartitionN,
ReplicaN: 1,
joiningLeavingNodes: make(chan nodeAction, 10), // buffered channel
jobs: make(map[int64]*resizeJob),
closing: make(chan struct{}),
joining: make(chan struct{}),
InternalClient: newNopInternalClient(),
logger: logger.NopLogger,
}
}
|
go
|
func newCluster() *cluster {
return &cluster{
Hasher: &jmphasher{},
partitionN: defaultPartitionN,
ReplicaN: 1,
joiningLeavingNodes: make(chan nodeAction, 10), // buffered channel
jobs: make(map[int64]*resizeJob),
closing: make(chan struct{}),
joining: make(chan struct{}),
InternalClient: newNopInternalClient(),
logger: logger.NopLogger,
}
}
|
[
"func",
"newCluster",
"(",
")",
"*",
"cluster",
"{",
"return",
"&",
"cluster",
"{",
"Hasher",
":",
"&",
"jmphasher",
"{",
"}",
",",
"partitionN",
":",
"defaultPartitionN",
",",
"ReplicaN",
":",
"1",
",",
"joiningLeavingNodes",
":",
"make",
"(",
"chan",
"nodeAction",
",",
"10",
")",
",",
"// buffered channel",
"jobs",
":",
"make",
"(",
"map",
"[",
"int64",
"]",
"*",
"resizeJob",
")",
",",
"closing",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"joining",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"InternalClient",
":",
"newNopInternalClient",
"(",
")",
",",
"logger",
":",
"logger",
".",
"NopLogger",
",",
"}",
"\n",
"}"
] |
// newCluster returns a new instance of Cluster with defaults.
|
[
"newCluster",
"returns",
"a",
"new",
"instance",
"of",
"Cluster",
"with",
"defaults",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L227-L242
|
train
|
pilosa/pilosa
|
cluster.go
|
isCoordinator
|
func (c *cluster) isCoordinator() bool {
c.mu.RLock()
defer c.mu.RUnlock()
return c.unprotectedIsCoordinator()
}
|
go
|
func (c *cluster) isCoordinator() bool {
c.mu.RLock()
defer c.mu.RUnlock()
return c.unprotectedIsCoordinator()
}
|
[
"func",
"(",
"c",
"*",
"cluster",
")",
"isCoordinator",
"(",
")",
"bool",
"{",
"c",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"c",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"c",
".",
"unprotectedIsCoordinator",
"(",
")",
"\n",
"}"
] |
// isCoordinator is true if this node is the coordinator.
|
[
"isCoordinator",
"is",
"true",
"if",
"this",
"node",
"is",
"the",
"coordinator",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L283-L287
|
train
|
pilosa/pilosa
|
cluster.go
|
setCoordinator
|
func (c *cluster) setCoordinator(n *Node) error {
c.mu.Lock()
defer c.mu.Unlock()
// Verify that the new Coordinator value matches
// this node.
if c.Node.ID != n.ID {
return fmt.Errorf("coordinator node does not match this node")
}
// Update IsCoordinator on all nodes (locally).
_ = c.unprotectedUpdateCoordinator(n)
// Send the update coordinator message to all nodes.
err := c.unprotectedSendSync(
&UpdateCoordinatorMessage{
New: n,
})
if err != nil {
return fmt.Errorf("problem sending UpdateCoordinator message: %v", err)
}
// Broadcast cluster status.
return c.unprotectedSendSync(c.unprotectedStatus())
}
|
go
|
func (c *cluster) setCoordinator(n *Node) error {
c.mu.Lock()
defer c.mu.Unlock()
// Verify that the new Coordinator value matches
// this node.
if c.Node.ID != n.ID {
return fmt.Errorf("coordinator node does not match this node")
}
// Update IsCoordinator on all nodes (locally).
_ = c.unprotectedUpdateCoordinator(n)
// Send the update coordinator message to all nodes.
err := c.unprotectedSendSync(
&UpdateCoordinatorMessage{
New: n,
})
if err != nil {
return fmt.Errorf("problem sending UpdateCoordinator message: %v", err)
}
// Broadcast cluster status.
return c.unprotectedSendSync(c.unprotectedStatus())
}
|
[
"func",
"(",
"c",
"*",
"cluster",
")",
"setCoordinator",
"(",
"n",
"*",
"Node",
")",
"error",
"{",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"// Verify that the new Coordinator value matches",
"// this node.",
"if",
"c",
".",
"Node",
".",
"ID",
"!=",
"n",
".",
"ID",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Update IsCoordinator on all nodes (locally).",
"_",
"=",
"c",
".",
"unprotectedUpdateCoordinator",
"(",
"n",
")",
"\n\n",
"// Send the update coordinator message to all nodes.",
"err",
":=",
"c",
".",
"unprotectedSendSync",
"(",
"&",
"UpdateCoordinatorMessage",
"{",
"New",
":",
"n",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Broadcast cluster status.",
"return",
"c",
".",
"unprotectedSendSync",
"(",
"c",
".",
"unprotectedStatus",
"(",
")",
")",
"\n",
"}"
] |
// setCoordinator tells the current node to become the
// Coordinator. In response to this, the current node
// will consider itself coordinator and update the other
// nodes with its version of Cluster.Status.
|
[
"setCoordinator",
"tells",
"the",
"current",
"node",
"to",
"become",
"the",
"Coordinator",
".",
"In",
"response",
"to",
"this",
"the",
"current",
"node",
"will",
"consider",
"itself",
"coordinator",
"and",
"update",
"the",
"other",
"nodes",
"with",
"its",
"version",
"of",
"Cluster",
".",
"Status",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L297-L320
|
train
|
pilosa/pilosa
|
cluster.go
|
updateCoordinator
|
func (c *cluster) updateCoordinator(n *Node) bool { // nolint: unparam
c.mu.Lock()
defer c.mu.Unlock()
return c.unprotectedUpdateCoordinator(n)
}
|
go
|
func (c *cluster) updateCoordinator(n *Node) bool { // nolint: unparam
c.mu.Lock()
defer c.mu.Unlock()
return c.unprotectedUpdateCoordinator(n)
}
|
[
"func",
"(",
"c",
"*",
"cluster",
")",
"updateCoordinator",
"(",
"n",
"*",
"Node",
")",
"bool",
"{",
"// nolint: unparam",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"c",
".",
"unprotectedUpdateCoordinator",
"(",
"n",
")",
"\n",
"}"
] |
// updateCoordinator updates this nodes Coordinator value as well as
// changing the corresponding node's IsCoordinator value
// to true, and sets all other nodes to false. Returns true if the value
// changed.
|
[
"updateCoordinator",
"updates",
"this",
"nodes",
"Coordinator",
"value",
"as",
"well",
"as",
"changing",
"the",
"corresponding",
"node",
"s",
"IsCoordinator",
"value",
"to",
"true",
"and",
"sets",
"all",
"other",
"nodes",
"to",
"false",
".",
"Returns",
"true",
"if",
"the",
"value",
"changed",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L344-L348
|
train
|
pilosa/pilosa
|
cluster.go
|
addNode
|
func (c *cluster) addNode(node *Node) error {
// If the node being added is the coordinator, set it for this node.
if node.IsCoordinator {
c.Coordinator = node.ID
}
// add to cluster
if !c.addNodeBasicSorted(node) {
return nil
}
// add to topology
if c.Topology == nil {
return fmt.Errorf("Cluster.Topology is nil")
}
if !c.Topology.addID(node.ID) {
return nil
}
c.Topology.nodeStates[node.ID] = node.State
// save topology
return c.saveTopology()
}
|
go
|
func (c *cluster) addNode(node *Node) error {
// If the node being added is the coordinator, set it for this node.
if node.IsCoordinator {
c.Coordinator = node.ID
}
// add to cluster
if !c.addNodeBasicSorted(node) {
return nil
}
// add to topology
if c.Topology == nil {
return fmt.Errorf("Cluster.Topology is nil")
}
if !c.Topology.addID(node.ID) {
return nil
}
c.Topology.nodeStates[node.ID] = node.State
// save topology
return c.saveTopology()
}
|
[
"func",
"(",
"c",
"*",
"cluster",
")",
"addNode",
"(",
"node",
"*",
"Node",
")",
"error",
"{",
"// If the node being added is the coordinator, set it for this node.",
"if",
"node",
".",
"IsCoordinator",
"{",
"c",
".",
"Coordinator",
"=",
"node",
".",
"ID",
"\n",
"}",
"\n\n",
"// add to cluster",
"if",
"!",
"c",
".",
"addNodeBasicSorted",
"(",
"node",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// add to topology",
"if",
"c",
".",
"Topology",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"!",
"c",
".",
"Topology",
".",
"addID",
"(",
"node",
".",
"ID",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"c",
".",
"Topology",
".",
"nodeStates",
"[",
"node",
".",
"ID",
"]",
"=",
"node",
".",
"State",
"\n\n",
"// save topology",
"return",
"c",
".",
"saveTopology",
"(",
")",
"\n",
"}"
] |
// addNode adds a node to the Cluster and updates and saves the
// new topology. unprotected.
|
[
"addNode",
"adds",
"a",
"node",
"to",
"the",
"Cluster",
"and",
"updates",
"and",
"saves",
"the",
"new",
"topology",
".",
"unprotected",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L368-L390
|
train
|
pilosa/pilosa
|
cluster.go
|
removeNode
|
func (c *cluster) removeNode(nodeID string) error {
// remove from cluster
c.removeNodeBasicSorted(nodeID)
// remove from topology
if c.Topology == nil {
return fmt.Errorf("Cluster.Topology is nil")
}
if !c.Topology.removeID(nodeID) {
return nil
}
// save topology
return c.saveTopology()
}
|
go
|
func (c *cluster) removeNode(nodeID string) error {
// remove from cluster
c.removeNodeBasicSorted(nodeID)
// remove from topology
if c.Topology == nil {
return fmt.Errorf("Cluster.Topology is nil")
}
if !c.Topology.removeID(nodeID) {
return nil
}
// save topology
return c.saveTopology()
}
|
[
"func",
"(",
"c",
"*",
"cluster",
")",
"removeNode",
"(",
"nodeID",
"string",
")",
"error",
"{",
"// remove from cluster",
"c",
".",
"removeNodeBasicSorted",
"(",
"nodeID",
")",
"\n\n",
"// remove from topology",
"if",
"c",
".",
"Topology",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"!",
"c",
".",
"Topology",
".",
"removeID",
"(",
"nodeID",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// save topology",
"return",
"c",
".",
"saveTopology",
"(",
")",
"\n",
"}"
] |
// removeNode removes a node from the Cluster and updates and saves the
// new topology. unprotected.
|
[
"removeNode",
"removes",
"a",
"node",
"from",
"the",
"Cluster",
"and",
"updates",
"and",
"saves",
"the",
"new",
"topology",
".",
"unprotected",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L394-L408
|
train
|
pilosa/pilosa
|
cluster.go
|
receiveNodeState
|
func (c *cluster) receiveNodeState(nodeID string, state string) error {
c.mu.Lock()
defer c.mu.Unlock()
if !c.unprotectedIsCoordinator() {
return nil
}
c.Topology.mu.Lock()
changed := false
if c.Topology.nodeStates[nodeID] != state {
changed = true
c.Topology.nodeStates[nodeID] = state
for i, n := range c.nodes {
if n.ID == nodeID {
c.nodes[i].State = state
}
}
}
c.Topology.mu.Unlock()
c.logger.Printf("received state %s (%s)", state, nodeID)
if changed {
return c.unprotectedSetStateAndBroadcast(c.determineClusterState())
}
return nil
}
|
go
|
func (c *cluster) receiveNodeState(nodeID string, state string) error {
c.mu.Lock()
defer c.mu.Unlock()
if !c.unprotectedIsCoordinator() {
return nil
}
c.Topology.mu.Lock()
changed := false
if c.Topology.nodeStates[nodeID] != state {
changed = true
c.Topology.nodeStates[nodeID] = state
for i, n := range c.nodes {
if n.ID == nodeID {
c.nodes[i].State = state
}
}
}
c.Topology.mu.Unlock()
c.logger.Printf("received state %s (%s)", state, nodeID)
if changed {
return c.unprotectedSetStateAndBroadcast(c.determineClusterState())
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"cluster",
")",
"receiveNodeState",
"(",
"nodeID",
"string",
",",
"state",
"string",
")",
"error",
"{",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"!",
"c",
".",
"unprotectedIsCoordinator",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"c",
".",
"Topology",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"changed",
":=",
"false",
"\n",
"if",
"c",
".",
"Topology",
".",
"nodeStates",
"[",
"nodeID",
"]",
"!=",
"state",
"{",
"changed",
"=",
"true",
"\n",
"c",
".",
"Topology",
".",
"nodeStates",
"[",
"nodeID",
"]",
"=",
"state",
"\n",
"for",
"i",
",",
"n",
":=",
"range",
"c",
".",
"nodes",
"{",
"if",
"n",
".",
"ID",
"==",
"nodeID",
"{",
"c",
".",
"nodes",
"[",
"i",
"]",
".",
"State",
"=",
"state",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"c",
".",
"Topology",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"c",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"state",
",",
"nodeID",
")",
"\n\n",
"if",
"changed",
"{",
"return",
"c",
".",
"unprotectedSetStateAndBroadcast",
"(",
"c",
".",
"determineClusterState",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// receiveNodeState sets node state in Topology in order for the
// Coordinator to keep track of, during startup, which nodes have
// finished opening their Holder.
|
[
"receiveNodeState",
"sets",
"node",
"state",
"in",
"Topology",
"in",
"order",
"for",
"the",
"Coordinator",
"to",
"keep",
"track",
"of",
"during",
"startup",
"which",
"nodes",
"have",
"finished",
"opening",
"their",
"Holder",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L513-L538
|
train
|
pilosa/pilosa
|
cluster.go
|
determineClusterState
|
func (c *cluster) determineClusterState() (clusterState string) {
if c.state == ClusterStateResizing {
return ClusterStateResizing
}
if c.haveTopologyAgreement() && c.allNodesReady() {
return ClusterStateNormal
}
if len(c.Topology.nodeIDs)-len(c.nodeIDs()) < c.ReplicaN && c.allNodesReady() {
return ClusterStateDegraded
}
return ClusterStateStarting
}
|
go
|
func (c *cluster) determineClusterState() (clusterState string) {
if c.state == ClusterStateResizing {
return ClusterStateResizing
}
if c.haveTopologyAgreement() && c.allNodesReady() {
return ClusterStateNormal
}
if len(c.Topology.nodeIDs)-len(c.nodeIDs()) < c.ReplicaN && c.allNodesReady() {
return ClusterStateDegraded
}
return ClusterStateStarting
}
|
[
"func",
"(",
"c",
"*",
"cluster",
")",
"determineClusterState",
"(",
")",
"(",
"clusterState",
"string",
")",
"{",
"if",
"c",
".",
"state",
"==",
"ClusterStateResizing",
"{",
"return",
"ClusterStateResizing",
"\n",
"}",
"\n",
"if",
"c",
".",
"haveTopologyAgreement",
"(",
")",
"&&",
"c",
".",
"allNodesReady",
"(",
")",
"{",
"return",
"ClusterStateNormal",
"\n",
"}",
"\n",
"if",
"len",
"(",
"c",
".",
"Topology",
".",
"nodeIDs",
")",
"-",
"len",
"(",
"c",
".",
"nodeIDs",
"(",
")",
")",
"<",
"c",
".",
"ReplicaN",
"&&",
"c",
".",
"allNodesReady",
"(",
")",
"{",
"return",
"ClusterStateDegraded",
"\n",
"}",
"\n",
"return",
"ClusterStateStarting",
"\n",
"}"
] |
// determineClusterState is unprotected.
|
[
"determineClusterState",
"is",
"unprotected",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L541-L552
|
train
|
pilosa/pilosa
|
cluster.go
|
unprotectedStatus
|
func (c *cluster) unprotectedStatus() *ClusterStatus {
return &ClusterStatus{
ClusterID: c.id,
State: c.state,
Nodes: c.nodes,
}
}
|
go
|
func (c *cluster) unprotectedStatus() *ClusterStatus {
return &ClusterStatus{
ClusterID: c.id,
State: c.state,
Nodes: c.nodes,
}
}
|
[
"func",
"(",
"c",
"*",
"cluster",
")",
"unprotectedStatus",
"(",
")",
"*",
"ClusterStatus",
"{",
"return",
"&",
"ClusterStatus",
"{",
"ClusterID",
":",
"c",
".",
"id",
",",
"State",
":",
"c",
".",
"state",
",",
"Nodes",
":",
"c",
".",
"nodes",
",",
"}",
"\n",
"}"
] |
// unprotectedStatus returns the the cluster's status including what nodes it contains, its ID, and current state.
|
[
"unprotectedStatus",
"returns",
"the",
"the",
"cluster",
"s",
"status",
"including",
"what",
"nodes",
"it",
"contains",
"its",
"ID",
"and",
"current",
"state",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L555-L561
|
train
|
pilosa/pilosa
|
cluster.go
|
unprotectedNodeByID
|
func (c *cluster) unprotectedNodeByID(id string) *Node {
for _, n := range c.nodes {
if n.ID == id {
return n
}
}
return nil
}
|
go
|
func (c *cluster) unprotectedNodeByID(id string) *Node {
for _, n := range c.nodes {
if n.ID == id {
return n
}
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"cluster",
")",
"unprotectedNodeByID",
"(",
"id",
"string",
")",
"*",
"Node",
"{",
"for",
"_",
",",
"n",
":=",
"range",
"c",
".",
"nodes",
"{",
"if",
"n",
".",
"ID",
"==",
"id",
"{",
"return",
"n",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// unprotectedNodeByID returns a node reference by ID.
|
[
"unprotectedNodeByID",
"returns",
"a",
"node",
"reference",
"by",
"ID",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L570-L577
|
train
|
pilosa/pilosa
|
cluster.go
|
nodePositionByID
|
func (c *cluster) nodePositionByID(nodeID string) int {
for i, n := range c.nodes {
if n.ID == nodeID {
return i
}
}
return -1
}
|
go
|
func (c *cluster) nodePositionByID(nodeID string) int {
for i, n := range c.nodes {
if n.ID == nodeID {
return i
}
}
return -1
}
|
[
"func",
"(",
"c",
"*",
"cluster",
")",
"nodePositionByID",
"(",
"nodeID",
"string",
")",
"int",
"{",
"for",
"i",
",",
"n",
":=",
"range",
"c",
".",
"nodes",
"{",
"if",
"n",
".",
"ID",
"==",
"nodeID",
"{",
"return",
"i",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"-",
"1",
"\n",
"}"
] |
// nodePositionByID returns the position of the node in slice c.Nodes.
|
[
"nodePositionByID",
"returns",
"the",
"position",
"of",
"the",
"node",
"in",
"slice",
"c",
".",
"Nodes",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L591-L598
|
train
|
pilosa/pilosa
|
cluster.go
|
addNodeBasicSorted
|
func (c *cluster) addNodeBasicSorted(node *Node) bool {
n := c.unprotectedNodeByID(node.ID)
if n != nil {
if n.State != node.State || n.IsCoordinator != node.IsCoordinator || n.URI != node.URI {
n.State = node.State
n.IsCoordinator = node.IsCoordinator
n.URI = node.URI
return true
}
return false
}
c.nodes = append(c.nodes, node)
// All hosts must be merged in the same order on all nodes in the cluster.
sort.Sort(byID(c.nodes))
return true
}
|
go
|
func (c *cluster) addNodeBasicSorted(node *Node) bool {
n := c.unprotectedNodeByID(node.ID)
if n != nil {
if n.State != node.State || n.IsCoordinator != node.IsCoordinator || n.URI != node.URI {
n.State = node.State
n.IsCoordinator = node.IsCoordinator
n.URI = node.URI
return true
}
return false
}
c.nodes = append(c.nodes, node)
// All hosts must be merged in the same order on all nodes in the cluster.
sort.Sort(byID(c.nodes))
return true
}
|
[
"func",
"(",
"c",
"*",
"cluster",
")",
"addNodeBasicSorted",
"(",
"node",
"*",
"Node",
")",
"bool",
"{",
"n",
":=",
"c",
".",
"unprotectedNodeByID",
"(",
"node",
".",
"ID",
")",
"\n",
"if",
"n",
"!=",
"nil",
"{",
"if",
"n",
".",
"State",
"!=",
"node",
".",
"State",
"||",
"n",
".",
"IsCoordinator",
"!=",
"node",
".",
"IsCoordinator",
"||",
"n",
".",
"URI",
"!=",
"node",
".",
"URI",
"{",
"n",
".",
"State",
"=",
"node",
".",
"State",
"\n",
"n",
".",
"IsCoordinator",
"=",
"node",
".",
"IsCoordinator",
"\n",
"n",
".",
"URI",
"=",
"node",
".",
"URI",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}",
"\n\n",
"c",
".",
"nodes",
"=",
"append",
"(",
"c",
".",
"nodes",
",",
"node",
")",
"\n\n",
"// All hosts must be merged in the same order on all nodes in the cluster.",
"sort",
".",
"Sort",
"(",
"byID",
"(",
"c",
".",
"nodes",
")",
")",
"\n\n",
"return",
"true",
"\n",
"}"
] |
// addNodeBasicSorted adds a node to the cluster, sorted by id. Returns a
// pointer to the node and true if the node was added. unprotected.
|
[
"addNodeBasicSorted",
"adds",
"a",
"node",
"to",
"the",
"cluster",
"sorted",
"by",
"id",
".",
"Returns",
"a",
"pointer",
"to",
"the",
"node",
"and",
"true",
"if",
"the",
"node",
"was",
"added",
".",
"unprotected",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L602-L620
|
train
|
pilosa/pilosa
|
cluster.go
|
Nodes
|
func (c *cluster) Nodes() []*Node {
c.mu.RLock()
defer c.mu.RUnlock()
ret := make([]*Node, len(c.nodes))
copy(ret, c.nodes)
return ret
}
|
go
|
func (c *cluster) Nodes() []*Node {
c.mu.RLock()
defer c.mu.RUnlock()
ret := make([]*Node, len(c.nodes))
copy(ret, c.nodes)
return ret
}
|
[
"func",
"(",
"c",
"*",
"cluster",
")",
"Nodes",
"(",
")",
"[",
"]",
"*",
"Node",
"{",
"c",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"c",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"ret",
":=",
"make",
"(",
"[",
"]",
"*",
"Node",
",",
"len",
"(",
"c",
".",
"nodes",
")",
")",
"\n",
"copy",
"(",
"ret",
",",
"c",
".",
"nodes",
")",
"\n",
"return",
"ret",
"\n",
"}"
] |
// Nodes returns a copy of the slice of nodes in the cluster. Safe for
// concurrent use, result may be modified.
|
[
"Nodes",
"returns",
"a",
"copy",
"of",
"the",
"slice",
"of",
"nodes",
"in",
"the",
"cluster",
".",
"Safe",
"for",
"concurrent",
"use",
"result",
"may",
"be",
"modified",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L624-L630
|
train
|
pilosa/pilosa
|
cluster.go
|
removeNodeBasicSorted
|
func (c *cluster) removeNodeBasicSorted(nodeID string) bool {
i := c.nodePositionByID(nodeID)
if i < 0 {
return false
}
copy(c.nodes[i:], c.nodes[i+1:])
c.nodes[len(c.nodes)-1] = nil
c.nodes = c.nodes[:len(c.nodes)-1]
return true
}
|
go
|
func (c *cluster) removeNodeBasicSorted(nodeID string) bool {
i := c.nodePositionByID(nodeID)
if i < 0 {
return false
}
copy(c.nodes[i:], c.nodes[i+1:])
c.nodes[len(c.nodes)-1] = nil
c.nodes = c.nodes[:len(c.nodes)-1]
return true
}
|
[
"func",
"(",
"c",
"*",
"cluster",
")",
"removeNodeBasicSorted",
"(",
"nodeID",
"string",
")",
"bool",
"{",
"i",
":=",
"c",
".",
"nodePositionByID",
"(",
"nodeID",
")",
"\n",
"if",
"i",
"<",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"copy",
"(",
"c",
".",
"nodes",
"[",
"i",
":",
"]",
",",
"c",
".",
"nodes",
"[",
"i",
"+",
"1",
":",
"]",
")",
"\n",
"c",
".",
"nodes",
"[",
"len",
"(",
"c",
".",
"nodes",
")",
"-",
"1",
"]",
"=",
"nil",
"\n",
"c",
".",
"nodes",
"=",
"c",
".",
"nodes",
"[",
":",
"len",
"(",
"c",
".",
"nodes",
")",
"-",
"1",
"]",
"\n\n",
"return",
"true",
"\n",
"}"
] |
// removeNodeBasicSorted removes a node from the cluster, maintaining the sort
// order. Returns true if the node was removed. unprotected.
|
[
"removeNodeBasicSorted",
"removes",
"a",
"node",
"from",
"the",
"cluster",
"maintaining",
"the",
"sort",
"order",
".",
"Returns",
"true",
"if",
"the",
"node",
"was",
"removed",
".",
"unprotected",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L634-L645
|
train
|
pilosa/pilosa
|
cluster.go
|
diff
|
func (c *cluster) diff(other *cluster) (action string, nodeID string, err error) {
lenFrom := len(c.nodes)
lenTo := len(other.nodes)
// Determine if a node is being added or removed.
if lenFrom == lenTo {
return "", "", errors.New("clusters are the same size")
}
if lenFrom < lenTo {
// Adding a node.
if lenTo-lenFrom > 1 {
return "", "", errors.New("adding more than one node at a time is not supported")
}
action = resizeJobActionAdd
// Determine the node ID that is being added.
for _, n := range other.nodes {
if c.unprotectedNodeByID(n.ID) == nil {
nodeID = n.ID
break
}
}
} else if lenFrom > lenTo {
// Removing a node.
if lenFrom-lenTo > 1 {
return "", "", errors.New("removing more than one node at a time is not supported")
}
action = resizeJobActionRemove
// Determine the node ID that is being removed.
for _, n := range c.nodes {
if other.unprotectedNodeByID(n.ID) == nil {
nodeID = n.ID
break
}
}
}
return action, nodeID, nil
}
|
go
|
func (c *cluster) diff(other *cluster) (action string, nodeID string, err error) {
lenFrom := len(c.nodes)
lenTo := len(other.nodes)
// Determine if a node is being added or removed.
if lenFrom == lenTo {
return "", "", errors.New("clusters are the same size")
}
if lenFrom < lenTo {
// Adding a node.
if lenTo-lenFrom > 1 {
return "", "", errors.New("adding more than one node at a time is not supported")
}
action = resizeJobActionAdd
// Determine the node ID that is being added.
for _, n := range other.nodes {
if c.unprotectedNodeByID(n.ID) == nil {
nodeID = n.ID
break
}
}
} else if lenFrom > lenTo {
// Removing a node.
if lenFrom-lenTo > 1 {
return "", "", errors.New("removing more than one node at a time is not supported")
}
action = resizeJobActionRemove
// Determine the node ID that is being removed.
for _, n := range c.nodes {
if other.unprotectedNodeByID(n.ID) == nil {
nodeID = n.ID
break
}
}
}
return action, nodeID, nil
}
|
[
"func",
"(",
"c",
"*",
"cluster",
")",
"diff",
"(",
"other",
"*",
"cluster",
")",
"(",
"action",
"string",
",",
"nodeID",
"string",
",",
"err",
"error",
")",
"{",
"lenFrom",
":=",
"len",
"(",
"c",
".",
"nodes",
")",
"\n",
"lenTo",
":=",
"len",
"(",
"other",
".",
"nodes",
")",
"\n",
"// Determine if a node is being added or removed.",
"if",
"lenFrom",
"==",
"lenTo",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"lenFrom",
"<",
"lenTo",
"{",
"// Adding a node.",
"if",
"lenTo",
"-",
"lenFrom",
">",
"1",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"action",
"=",
"resizeJobActionAdd",
"\n",
"// Determine the node ID that is being added.",
"for",
"_",
",",
"n",
":=",
"range",
"other",
".",
"nodes",
"{",
"if",
"c",
".",
"unprotectedNodeByID",
"(",
"n",
".",
"ID",
")",
"==",
"nil",
"{",
"nodeID",
"=",
"n",
".",
"ID",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"if",
"lenFrom",
">",
"lenTo",
"{",
"// Removing a node.",
"if",
"lenFrom",
"-",
"lenTo",
">",
"1",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"action",
"=",
"resizeJobActionRemove",
"\n",
"// Determine the node ID that is being removed.",
"for",
"_",
",",
"n",
":=",
"range",
"c",
".",
"nodes",
"{",
"if",
"other",
".",
"unprotectedNodeByID",
"(",
"n",
".",
"ID",
")",
"==",
"nil",
"{",
"nodeID",
"=",
"n",
".",
"ID",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"action",
",",
"nodeID",
",",
"nil",
"\n",
"}"
] |
// diff compares c with another cluster and determines if a node is being
// added or removed. An error is returned for any case other than where
// exactly one node is added or removed. unprotected.
|
[
"diff",
"compares",
"c",
"with",
"another",
"cluster",
"and",
"determines",
"if",
"a",
"node",
"is",
"being",
"added",
"or",
"removed",
".",
"An",
"error",
"is",
"returned",
"for",
"any",
"case",
"other",
"than",
"where",
"exactly",
"one",
"node",
"is",
"added",
"or",
"removed",
".",
"unprotected",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L715-L750
|
train
|
pilosa/pilosa
|
cluster.go
|
fragSources
|
func (c *cluster) fragSources(to *cluster, idx *Index) (map[string][]*ResizeSource, error) {
m := make(map[string][]*ResizeSource)
// Determine if a node is being added or removed.
action, diffNodeID, err := c.diff(to)
if err != nil {
return nil, errors.Wrap(err, "diffing")
}
// Initialize the map with all the nodes in `to`.
for _, n := range to.nodes {
m[n.ID] = nil
}
// If a node is being added, the source can be confined to the
// primary fragments (i.e. no need to use replicas as source data).
// In this case, source fragments can be based on a cluster with
// replica = 1.
// If a node is being removed, however, then it will most likely
// require that a replica fragment be the source data.
srcCluster := c
if action == resizeJobActionAdd && c.ReplicaN > 1 {
srcCluster = newCluster()
srcCluster.nodes = Nodes(c.nodes).Clone()
srcCluster.Hasher = c.Hasher
srcCluster.partitionN = c.partitionN
srcCluster.ReplicaN = 1
}
// Represents the fragment location for the from/to clusters.
fFrags := c.fragsByHost(idx)
tFrags := to.fragsByHost(idx)
// srcFrags is the frag map based on a source cluster of replica = 1.
srcFrags := srcCluster.fragsByHost(idx)
// srcNodesByFrag is the inverse representation of srcFrags.
srcNodesByFrag := make(map[frag]string)
for nodeID, frags := range srcFrags {
// If a node is being removed, don't consider it as a source.
if action == resizeJobActionRemove && nodeID == diffNodeID {
continue
}
for _, frag := range frags {
srcNodesByFrag[frag] = nodeID
}
}
// Get the frag diff for each nodeID.
diffs := make(fragsByHost)
for nodeID, frags := range tFrags {
if _, ok := fFrags[nodeID]; ok {
diffs[nodeID] = fragsDiff(frags, fFrags[nodeID])
} else {
diffs[nodeID] = frags
}
}
// Get the ResizeSource for each diff.
for nodeID, diff := range diffs {
m[nodeID] = []*ResizeSource{}
for _, frag := range diff {
// If there is no valid source node ID for a fragment,
// it likely means that the replica factor was not
// high enough for the remaining nodes to contain
// the fragment.
srcNodeID, ok := srcNodesByFrag[frag]
if !ok {
return nil, errors.New("not enough data to perform resize (replica factor may need to be increased)")
}
src := &ResizeSource{
Node: c.unprotectedNodeByID(srcNodeID),
Index: idx.Name(),
Field: frag.field,
View: frag.view,
Shard: frag.shard,
}
m[nodeID] = append(m[nodeID], src)
}
}
return m, nil
}
|
go
|
func (c *cluster) fragSources(to *cluster, idx *Index) (map[string][]*ResizeSource, error) {
m := make(map[string][]*ResizeSource)
// Determine if a node is being added or removed.
action, diffNodeID, err := c.diff(to)
if err != nil {
return nil, errors.Wrap(err, "diffing")
}
// Initialize the map with all the nodes in `to`.
for _, n := range to.nodes {
m[n.ID] = nil
}
// If a node is being added, the source can be confined to the
// primary fragments (i.e. no need to use replicas as source data).
// In this case, source fragments can be based on a cluster with
// replica = 1.
// If a node is being removed, however, then it will most likely
// require that a replica fragment be the source data.
srcCluster := c
if action == resizeJobActionAdd && c.ReplicaN > 1 {
srcCluster = newCluster()
srcCluster.nodes = Nodes(c.nodes).Clone()
srcCluster.Hasher = c.Hasher
srcCluster.partitionN = c.partitionN
srcCluster.ReplicaN = 1
}
// Represents the fragment location for the from/to clusters.
fFrags := c.fragsByHost(idx)
tFrags := to.fragsByHost(idx)
// srcFrags is the frag map based on a source cluster of replica = 1.
srcFrags := srcCluster.fragsByHost(idx)
// srcNodesByFrag is the inverse representation of srcFrags.
srcNodesByFrag := make(map[frag]string)
for nodeID, frags := range srcFrags {
// If a node is being removed, don't consider it as a source.
if action == resizeJobActionRemove && nodeID == diffNodeID {
continue
}
for _, frag := range frags {
srcNodesByFrag[frag] = nodeID
}
}
// Get the frag diff for each nodeID.
diffs := make(fragsByHost)
for nodeID, frags := range tFrags {
if _, ok := fFrags[nodeID]; ok {
diffs[nodeID] = fragsDiff(frags, fFrags[nodeID])
} else {
diffs[nodeID] = frags
}
}
// Get the ResizeSource for each diff.
for nodeID, diff := range diffs {
m[nodeID] = []*ResizeSource{}
for _, frag := range diff {
// If there is no valid source node ID for a fragment,
// it likely means that the replica factor was not
// high enough for the remaining nodes to contain
// the fragment.
srcNodeID, ok := srcNodesByFrag[frag]
if !ok {
return nil, errors.New("not enough data to perform resize (replica factor may need to be increased)")
}
src := &ResizeSource{
Node: c.unprotectedNodeByID(srcNodeID),
Index: idx.Name(),
Field: frag.field,
View: frag.view,
Shard: frag.shard,
}
m[nodeID] = append(m[nodeID], src)
}
}
return m, nil
}
|
[
"func",
"(",
"c",
"*",
"cluster",
")",
"fragSources",
"(",
"to",
"*",
"cluster",
",",
"idx",
"*",
"Index",
")",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"*",
"ResizeSource",
",",
"error",
")",
"{",
"m",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"*",
"ResizeSource",
")",
"\n\n",
"// Determine if a node is being added or removed.",
"action",
",",
"diffNodeID",
",",
"err",
":=",
"c",
".",
"diff",
"(",
"to",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Initialize the map with all the nodes in `to`.",
"for",
"_",
",",
"n",
":=",
"range",
"to",
".",
"nodes",
"{",
"m",
"[",
"n",
".",
"ID",
"]",
"=",
"nil",
"\n",
"}",
"\n\n",
"// If a node is being added, the source can be confined to the",
"// primary fragments (i.e. no need to use replicas as source data).",
"// In this case, source fragments can be based on a cluster with",
"// replica = 1.",
"// If a node is being removed, however, then it will most likely",
"// require that a replica fragment be the source data.",
"srcCluster",
":=",
"c",
"\n",
"if",
"action",
"==",
"resizeJobActionAdd",
"&&",
"c",
".",
"ReplicaN",
">",
"1",
"{",
"srcCluster",
"=",
"newCluster",
"(",
")",
"\n",
"srcCluster",
".",
"nodes",
"=",
"Nodes",
"(",
"c",
".",
"nodes",
")",
".",
"Clone",
"(",
")",
"\n",
"srcCluster",
".",
"Hasher",
"=",
"c",
".",
"Hasher",
"\n",
"srcCluster",
".",
"partitionN",
"=",
"c",
".",
"partitionN",
"\n",
"srcCluster",
".",
"ReplicaN",
"=",
"1",
"\n",
"}",
"\n\n",
"// Represents the fragment location for the from/to clusters.",
"fFrags",
":=",
"c",
".",
"fragsByHost",
"(",
"idx",
")",
"\n",
"tFrags",
":=",
"to",
".",
"fragsByHost",
"(",
"idx",
")",
"\n\n",
"// srcFrags is the frag map based on a source cluster of replica = 1.",
"srcFrags",
":=",
"srcCluster",
".",
"fragsByHost",
"(",
"idx",
")",
"\n\n",
"// srcNodesByFrag is the inverse representation of srcFrags.",
"srcNodesByFrag",
":=",
"make",
"(",
"map",
"[",
"frag",
"]",
"string",
")",
"\n",
"for",
"nodeID",
",",
"frags",
":=",
"range",
"srcFrags",
"{",
"// If a node is being removed, don't consider it as a source.",
"if",
"action",
"==",
"resizeJobActionRemove",
"&&",
"nodeID",
"==",
"diffNodeID",
"{",
"continue",
"\n",
"}",
"\n",
"for",
"_",
",",
"frag",
":=",
"range",
"frags",
"{",
"srcNodesByFrag",
"[",
"frag",
"]",
"=",
"nodeID",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Get the frag diff for each nodeID.",
"diffs",
":=",
"make",
"(",
"fragsByHost",
")",
"\n",
"for",
"nodeID",
",",
"frags",
":=",
"range",
"tFrags",
"{",
"if",
"_",
",",
"ok",
":=",
"fFrags",
"[",
"nodeID",
"]",
";",
"ok",
"{",
"diffs",
"[",
"nodeID",
"]",
"=",
"fragsDiff",
"(",
"frags",
",",
"fFrags",
"[",
"nodeID",
"]",
")",
"\n",
"}",
"else",
"{",
"diffs",
"[",
"nodeID",
"]",
"=",
"frags",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Get the ResizeSource for each diff.",
"for",
"nodeID",
",",
"diff",
":=",
"range",
"diffs",
"{",
"m",
"[",
"nodeID",
"]",
"=",
"[",
"]",
"*",
"ResizeSource",
"{",
"}",
"\n",
"for",
"_",
",",
"frag",
":=",
"range",
"diff",
"{",
"// If there is no valid source node ID for a fragment,",
"// it likely means that the replica factor was not",
"// high enough for the remaining nodes to contain",
"// the fragment.",
"srcNodeID",
",",
"ok",
":=",
"srcNodesByFrag",
"[",
"frag",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"src",
":=",
"&",
"ResizeSource",
"{",
"Node",
":",
"c",
".",
"unprotectedNodeByID",
"(",
"srcNodeID",
")",
",",
"Index",
":",
"idx",
".",
"Name",
"(",
")",
",",
"Field",
":",
"frag",
".",
"field",
",",
"View",
":",
"frag",
".",
"view",
",",
"Shard",
":",
"frag",
".",
"shard",
",",
"}",
"\n\n",
"m",
"[",
"nodeID",
"]",
"=",
"append",
"(",
"m",
"[",
"nodeID",
"]",
",",
"src",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"m",
",",
"nil",
"\n",
"}"
] |
// fragSources returns a list of ResizeSources - for each node in the `to` cluster -
// required to move from cluster `c` to cluster `to`. unprotected.
|
[
"fragSources",
"returns",
"a",
"list",
"of",
"ResizeSources",
"-",
"for",
"each",
"node",
"in",
"the",
"to",
"cluster",
"-",
"required",
"to",
"move",
"from",
"cluster",
"c",
"to",
"cluster",
"to",
".",
"unprotected",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L754-L838
|
train
|
pilosa/pilosa
|
cluster.go
|
partition
|
func (c *cluster) partition(index string, shard uint64) int {
var buf [8]byte
binary.BigEndian.PutUint64(buf[:], shard)
// Hash the bytes and mod by partition count.
h := fnv.New64a()
_, _ = h.Write([]byte(index))
_, _ = h.Write(buf[:])
return int(h.Sum64() % uint64(c.partitionN))
}
|
go
|
func (c *cluster) partition(index string, shard uint64) int {
var buf [8]byte
binary.BigEndian.PutUint64(buf[:], shard)
// Hash the bytes and mod by partition count.
h := fnv.New64a()
_, _ = h.Write([]byte(index))
_, _ = h.Write(buf[:])
return int(h.Sum64() % uint64(c.partitionN))
}
|
[
"func",
"(",
"c",
"*",
"cluster",
")",
"partition",
"(",
"index",
"string",
",",
"shard",
"uint64",
")",
"int",
"{",
"var",
"buf",
"[",
"8",
"]",
"byte",
"\n",
"binary",
".",
"BigEndian",
".",
"PutUint64",
"(",
"buf",
"[",
":",
"]",
",",
"shard",
")",
"\n\n",
"// Hash the bytes and mod by partition count.",
"h",
":=",
"fnv",
".",
"New64a",
"(",
")",
"\n",
"_",
",",
"_",
"=",
"h",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"index",
")",
")",
"\n",
"_",
",",
"_",
"=",
"h",
".",
"Write",
"(",
"buf",
"[",
":",
"]",
")",
"\n",
"return",
"int",
"(",
"h",
".",
"Sum64",
"(",
")",
"%",
"uint64",
"(",
"c",
".",
"partitionN",
")",
")",
"\n",
"}"
] |
// partition returns the partition that a shard belongs to.
|
[
"partition",
"returns",
"the",
"partition",
"that",
"a",
"shard",
"belongs",
"to",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L841-L850
|
train
|
pilosa/pilosa
|
cluster.go
|
ShardNodes
|
func (c *cluster) ShardNodes(index string, shard uint64) []*Node {
c.mu.RLock()
defer c.mu.RUnlock()
return c.shardNodes(index, shard)
}
|
go
|
func (c *cluster) ShardNodes(index string, shard uint64) []*Node {
c.mu.RLock()
defer c.mu.RUnlock()
return c.shardNodes(index, shard)
}
|
[
"func",
"(",
"c",
"*",
"cluster",
")",
"ShardNodes",
"(",
"index",
"string",
",",
"shard",
"uint64",
")",
"[",
"]",
"*",
"Node",
"{",
"c",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"c",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"c",
".",
"shardNodes",
"(",
"index",
",",
"shard",
")",
"\n",
"}"
] |
// ShardNodes returns a list of nodes that own a fragment. Safe for concurrent use.
|
[
"ShardNodes",
"returns",
"a",
"list",
"of",
"nodes",
"that",
"own",
"a",
"fragment",
".",
"Safe",
"for",
"concurrent",
"use",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L853-L857
|
train
|
pilosa/pilosa
|
cluster.go
|
shardNodes
|
func (c *cluster) shardNodes(index string, shard uint64) []*Node {
return c.partitionNodes(c.partition(index, shard))
}
|
go
|
func (c *cluster) shardNodes(index string, shard uint64) []*Node {
return c.partitionNodes(c.partition(index, shard))
}
|
[
"func",
"(",
"c",
"*",
"cluster",
")",
"shardNodes",
"(",
"index",
"string",
",",
"shard",
"uint64",
")",
"[",
"]",
"*",
"Node",
"{",
"return",
"c",
".",
"partitionNodes",
"(",
"c",
".",
"partition",
"(",
"index",
",",
"shard",
")",
")",
"\n",
"}"
] |
// shardNodes returns a list of nodes that own a fragment. unprotected
|
[
"shardNodes",
"returns",
"a",
"list",
"of",
"nodes",
"that",
"own",
"a",
"fragment",
".",
"unprotected"
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L860-L862
|
train
|
pilosa/pilosa
|
cluster.go
|
ownsShard
|
func (c *cluster) ownsShard(nodeID string, index string, shard uint64) bool {
c.mu.RLock()
defer c.mu.RUnlock()
return Nodes(c.shardNodes(index, shard)).ContainsID(nodeID)
}
|
go
|
func (c *cluster) ownsShard(nodeID string, index string, shard uint64) bool {
c.mu.RLock()
defer c.mu.RUnlock()
return Nodes(c.shardNodes(index, shard)).ContainsID(nodeID)
}
|
[
"func",
"(",
"c",
"*",
"cluster",
")",
"ownsShard",
"(",
"nodeID",
"string",
",",
"index",
"string",
",",
"shard",
"uint64",
")",
"bool",
"{",
"c",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"c",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"Nodes",
"(",
"c",
".",
"shardNodes",
"(",
"index",
",",
"shard",
")",
")",
".",
"ContainsID",
"(",
"nodeID",
")",
"\n",
"}"
] |
// ownsShard returns true if a host owns a fragment.
|
[
"ownsShard",
"returns",
"true",
"if",
"a",
"host",
"owns",
"a",
"fragment",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L865-L869
|
train
|
pilosa/pilosa
|
cluster.go
|
partitionNodes
|
func (c *cluster) partitionNodes(partitionID int) []*Node {
// Default replica count to between one and the number of nodes.
// The replica count can be zero if there are no nodes.
replicaN := c.ReplicaN
if replicaN > len(c.nodes) {
replicaN = len(c.nodes)
} else if replicaN == 0 {
replicaN = 1
}
// Determine primary owner node.
nodeIndex := c.Hasher.Hash(uint64(partitionID), len(c.nodes))
// Collect nodes around the ring.
nodes := make([]*Node, replicaN)
for i := 0; i < replicaN; i++ {
nodes[i] = c.nodes[(nodeIndex+i)%len(c.nodes)]
}
return nodes
}
|
go
|
func (c *cluster) partitionNodes(partitionID int) []*Node {
// Default replica count to between one and the number of nodes.
// The replica count can be zero if there are no nodes.
replicaN := c.ReplicaN
if replicaN > len(c.nodes) {
replicaN = len(c.nodes)
} else if replicaN == 0 {
replicaN = 1
}
// Determine primary owner node.
nodeIndex := c.Hasher.Hash(uint64(partitionID), len(c.nodes))
// Collect nodes around the ring.
nodes := make([]*Node, replicaN)
for i := 0; i < replicaN; i++ {
nodes[i] = c.nodes[(nodeIndex+i)%len(c.nodes)]
}
return nodes
}
|
[
"func",
"(",
"c",
"*",
"cluster",
")",
"partitionNodes",
"(",
"partitionID",
"int",
")",
"[",
"]",
"*",
"Node",
"{",
"// Default replica count to between one and the number of nodes.",
"// The replica count can be zero if there are no nodes.",
"replicaN",
":=",
"c",
".",
"ReplicaN",
"\n",
"if",
"replicaN",
">",
"len",
"(",
"c",
".",
"nodes",
")",
"{",
"replicaN",
"=",
"len",
"(",
"c",
".",
"nodes",
")",
"\n",
"}",
"else",
"if",
"replicaN",
"==",
"0",
"{",
"replicaN",
"=",
"1",
"\n",
"}",
"\n\n",
"// Determine primary owner node.",
"nodeIndex",
":=",
"c",
".",
"Hasher",
".",
"Hash",
"(",
"uint64",
"(",
"partitionID",
")",
",",
"len",
"(",
"c",
".",
"nodes",
")",
")",
"\n\n",
"// Collect nodes around the ring.",
"nodes",
":=",
"make",
"(",
"[",
"]",
"*",
"Node",
",",
"replicaN",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"replicaN",
";",
"i",
"++",
"{",
"nodes",
"[",
"i",
"]",
"=",
"c",
".",
"nodes",
"[",
"(",
"nodeIndex",
"+",
"i",
")",
"%",
"len",
"(",
"c",
".",
"nodes",
")",
"]",
"\n",
"}",
"\n\n",
"return",
"nodes",
"\n",
"}"
] |
// partitionNodes returns a list of nodes that own a partition. unprotected.
|
[
"partitionNodes",
"returns",
"a",
"list",
"of",
"nodes",
"that",
"own",
"a",
"partition",
".",
"unprotected",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L872-L892
|
train
|
pilosa/pilosa
|
cluster.go
|
containsShards
|
func (c *cluster) containsShards(index string, availableShards *roaring.Bitmap, node *Node) []uint64 {
var shards []uint64
availableShards.ForEach(func(i uint64) {
p := c.partition(index, i)
// Determine the nodes for partition.
nodes := c.partitionNodes(p)
for _, n := range nodes {
if n.ID == node.ID {
shards = append(shards, i)
}
}
})
return shards
}
|
go
|
func (c *cluster) containsShards(index string, availableShards *roaring.Bitmap, node *Node) []uint64 {
var shards []uint64
availableShards.ForEach(func(i uint64) {
p := c.partition(index, i)
// Determine the nodes for partition.
nodes := c.partitionNodes(p)
for _, n := range nodes {
if n.ID == node.ID {
shards = append(shards, i)
}
}
})
return shards
}
|
[
"func",
"(",
"c",
"*",
"cluster",
")",
"containsShards",
"(",
"index",
"string",
",",
"availableShards",
"*",
"roaring",
".",
"Bitmap",
",",
"node",
"*",
"Node",
")",
"[",
"]",
"uint64",
"{",
"var",
"shards",
"[",
"]",
"uint64",
"\n",
"availableShards",
".",
"ForEach",
"(",
"func",
"(",
"i",
"uint64",
")",
"{",
"p",
":=",
"c",
".",
"partition",
"(",
"index",
",",
"i",
")",
"\n",
"// Determine the nodes for partition.",
"nodes",
":=",
"c",
".",
"partitionNodes",
"(",
"p",
")",
"\n",
"for",
"_",
",",
"n",
":=",
"range",
"nodes",
"{",
"if",
"n",
".",
"ID",
"==",
"node",
".",
"ID",
"{",
"shards",
"=",
"append",
"(",
"shards",
",",
"i",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
")",
"\n",
"return",
"shards",
"\n",
"}"
] |
// containsShards is like OwnsShards, but it includes replicas.
|
[
"containsShards",
"is",
"like",
"OwnsShards",
"but",
"it",
"includes",
"replicas",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L895-L908
|
train
|
pilosa/pilosa
|
cluster.go
|
needTopologyAgreement
|
func (c *cluster) needTopologyAgreement() bool {
return (c.state == ClusterStateStarting || c.state == ClusterStateDegraded) && !stringSlicesAreEqual(c.Topology.nodeIDs, c.nodeIDs())
}
|
go
|
func (c *cluster) needTopologyAgreement() bool {
return (c.state == ClusterStateStarting || c.state == ClusterStateDegraded) && !stringSlicesAreEqual(c.Topology.nodeIDs, c.nodeIDs())
}
|
[
"func",
"(",
"c",
"*",
"cluster",
")",
"needTopologyAgreement",
"(",
")",
"bool",
"{",
"return",
"(",
"c",
".",
"state",
"==",
"ClusterStateStarting",
"||",
"c",
".",
"state",
"==",
"ClusterStateDegraded",
")",
"&&",
"!",
"stringSlicesAreEqual",
"(",
"c",
".",
"Topology",
".",
"nodeIDs",
",",
"c",
".",
"nodeIDs",
"(",
")",
")",
"\n",
"}"
] |
// needTopologyAgreement is unprotected.
|
[
"needTopologyAgreement",
"is",
"unprotected",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L1007-L1009
|
train
|
pilosa/pilosa
|
cluster.go
|
haveTopologyAgreement
|
func (c *cluster) haveTopologyAgreement() bool {
if c.Static {
return true
}
return stringSlicesAreEqual(c.Topology.nodeIDs, c.nodeIDs())
}
|
go
|
func (c *cluster) haveTopologyAgreement() bool {
if c.Static {
return true
}
return stringSlicesAreEqual(c.Topology.nodeIDs, c.nodeIDs())
}
|
[
"func",
"(",
"c",
"*",
"cluster",
")",
"haveTopologyAgreement",
"(",
")",
"bool",
"{",
"if",
"c",
".",
"Static",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"stringSlicesAreEqual",
"(",
"c",
".",
"Topology",
".",
"nodeIDs",
",",
"c",
".",
"nodeIDs",
"(",
")",
")",
"\n",
"}"
] |
// haveTopologyAgreement is unprotected.
|
[
"haveTopologyAgreement",
"is",
"unprotected",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L1012-L1017
|
train
|
pilosa/pilosa
|
cluster.go
|
allNodesReady
|
func (c *cluster) allNodesReady() (ret bool) {
if c.Static {
return true
}
for _, id := range c.nodeIDs() {
if c.Topology.nodeStates[id] != nodeStateReady {
return false
}
}
return true
}
|
go
|
func (c *cluster) allNodesReady() (ret bool) {
if c.Static {
return true
}
for _, id := range c.nodeIDs() {
if c.Topology.nodeStates[id] != nodeStateReady {
return false
}
}
return true
}
|
[
"func",
"(",
"c",
"*",
"cluster",
")",
"allNodesReady",
"(",
")",
"(",
"ret",
"bool",
")",
"{",
"if",
"c",
".",
"Static",
"{",
"return",
"true",
"\n",
"}",
"\n",
"for",
"_",
",",
"id",
":=",
"range",
"c",
".",
"nodeIDs",
"(",
")",
"{",
"if",
"c",
".",
"Topology",
".",
"nodeStates",
"[",
"id",
"]",
"!=",
"nodeStateReady",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// allNodesReady is unprotected.
|
[
"allNodesReady",
"is",
"unprotected",
"."
] |
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/cluster.go#L1020-L1030
|
train
|
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.