repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
guregu/null
bool.go
UnmarshalJSON
func (b *Bool) UnmarshalJSON(data []byte) error { var err error var v interface{} if err = json.Unmarshal(data, &v); err != nil { return err } switch x := v.(type) { case bool: b.Bool = x case map[string]interface{}: err = json.Unmarshal(data, &b.NullBool) case nil: b.Valid = false return nil default: err = fmt.Errorf("json: cannot unmarshal %v into Go value of type null.Bool", reflect.TypeOf(v).Name()) } b.Valid = err == nil return err }
go
func (b *Bool) UnmarshalJSON(data []byte) error { var err error var v interface{} if err = json.Unmarshal(data, &v); err != nil { return err } switch x := v.(type) { case bool: b.Bool = x case map[string]interface{}: err = json.Unmarshal(data, &b.NullBool) case nil: b.Valid = false return nil default: err = fmt.Errorf("json: cannot unmarshal %v into Go value of type null.Bool", reflect.TypeOf(v).Name()) } b.Valid = err == nil return err }
[ "func", "(", "b", "*", "Bool", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "var", "err", "error", "\n", "var", "v", "interface", "{", "}", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "v", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "switch", "x", ":=", "v", ".", "(", "type", ")", "{", "case", "bool", ":", "b", ".", "Bool", "=", "x", "\n", "case", "map", "[", "string", "]", "interface", "{", "}", ":", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "b", ".", "NullBool", ")", "\n", "case", "nil", ":", "b", ".", "Valid", "=", "false", "\n", "return", "nil", "\n", "default", ":", "err", "=", "fmt", ".", "Errorf", "(", "\"json: cannot unmarshal %v into Go value of type null.Bool\"", ",", "reflect", ".", "TypeOf", "(", "v", ")", ".", "Name", "(", ")", ")", "\n", "}", "\n", "b", ".", "Valid", "=", "err", "==", "nil", "\n", "return", "err", "\n", "}" ]
// UnmarshalJSON implements json.Unmarshaler. // It supports number and null input. // 0 will not be considered a null Bool. // It also supports unmarshalling a sql.NullBool.
[ "UnmarshalJSON", "implements", "json", ".", "Unmarshaler", ".", "It", "supports", "number", "and", "null", "input", ".", "0", "will", "not", "be", "considered", "a", "null", "Bool", ".", "It", "also", "supports", "unmarshalling", "a", "sql", ".", "NullBool", "." ]
80515d440932108546bcade467bb7d6968e812e2
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/bool.go#L50-L69
test
guregu/null
bool.go
UnmarshalText
func (b *Bool) UnmarshalText(text []byte) error { str := string(text) switch str { case "", "null": b.Valid = false return nil case "true": b.Bool = true case "false": b.Bool = false default: b.Valid = false return errors.New("invalid input:" + str) } b.Valid = true return nil }
go
func (b *Bool) UnmarshalText(text []byte) error { str := string(text) switch str { case "", "null": b.Valid = false return nil case "true": b.Bool = true case "false": b.Bool = false default: b.Valid = false return errors.New("invalid input:" + str) } b.Valid = true return nil }
[ "func", "(", "b", "*", "Bool", ")", "UnmarshalText", "(", "text", "[", "]", "byte", ")", "error", "{", "str", ":=", "string", "(", "text", ")", "\n", "switch", "str", "{", "case", "\"\"", ",", "\"null\"", ":", "b", ".", "Valid", "=", "false", "\n", "return", "nil", "\n", "case", "\"true\"", ":", "b", ".", "Bool", "=", "true", "\n", "case", "\"false\"", ":", "b", ".", "Bool", "=", "false", "\n", "default", ":", "b", ".", "Valid", "=", "false", "\n", "return", "errors", ".", "New", "(", "\"invalid input:\"", "+", "str", ")", "\n", "}", "\n", "b", ".", "Valid", "=", "true", "\n", "return", "nil", "\n", "}" ]
// UnmarshalText implements encoding.TextUnmarshaler. // It will unmarshal to a null Bool if the input is a blank or not an integer. // It will return an error if the input is not an integer, blank, or "null".
[ "UnmarshalText", "implements", "encoding", ".", "TextUnmarshaler", ".", "It", "will", "unmarshal", "to", "a", "null", "Bool", "if", "the", "input", "is", "a", "blank", "or", "not", "an", "integer", ".", "It", "will", "return", "an", "error", "if", "the", "input", "is", "not", "an", "integer", "blank", "or", "null", "." ]
80515d440932108546bcade467bb7d6968e812e2
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/bool.go#L74-L90
test
guregu/null
bool.go
MarshalJSON
func (b Bool) MarshalJSON() ([]byte, error) { if !b.Valid { return []byte("null"), nil } if !b.Bool { return []byte("false"), nil } return []byte("true"), nil }
go
func (b Bool) MarshalJSON() ([]byte, error) { if !b.Valid { return []byte("null"), nil } if !b.Bool { return []byte("false"), nil } return []byte("true"), nil }
[ "func", "(", "b", "Bool", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "!", "b", ".", "Valid", "{", "return", "[", "]", "byte", "(", "\"null\"", ")", ",", "nil", "\n", "}", "\n", "if", "!", "b", ".", "Bool", "{", "return", "[", "]", "byte", "(", "\"false\"", ")", ",", "nil", "\n", "}", "\n", "return", "[", "]", "byte", "(", "\"true\"", ")", ",", "nil", "\n", "}" ]
// MarshalJSON implements json.Marshaler. // It will encode null if this Bool is null.
[ "MarshalJSON", "implements", "json", ".", "Marshaler", ".", "It", "will", "encode", "null", "if", "this", "Bool", "is", "null", "." ]
80515d440932108546bcade467bb7d6968e812e2
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/bool.go#L94-L102
test
guregu/null
bool.go
SetValid
func (b *Bool) SetValid(v bool) { b.Bool = v b.Valid = true }
go
func (b *Bool) SetValid(v bool) { b.Bool = v b.Valid = true }
[ "func", "(", "b", "*", "Bool", ")", "SetValid", "(", "v", "bool", ")", "{", "b", ".", "Bool", "=", "v", "\n", "b", ".", "Valid", "=", "true", "\n", "}" ]
// SetValid changes this Bool's value and also sets it to be non-null.
[ "SetValid", "changes", "this", "Bool", "s", "value", "and", "also", "sets", "it", "to", "be", "non", "-", "null", "." ]
80515d440932108546bcade467bb7d6968e812e2
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/bool.go#L117-L120
test
guregu/null
zero/string.go
NewString
func NewString(s string, valid bool) String { return String{ NullString: sql.NullString{ String: s, Valid: valid, }, } }
go
func NewString(s string, valid bool) String { return String{ NullString: sql.NullString{ String: s, Valid: valid, }, } }
[ "func", "NewString", "(", "s", "string", ",", "valid", "bool", ")", "String", "{", "return", "String", "{", "NullString", ":", "sql", ".", "NullString", "{", "String", ":", "s", ",", "Valid", ":", "valid", ",", "}", ",", "}", "\n", "}" ]
// NewString creates a new String
[ "NewString", "creates", "a", "new", "String" ]
80515d440932108546bcade467bb7d6968e812e2
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/zero/string.go#L22-L29
test
guregu/null
zero/string.go
UnmarshalJSON
func (s *String) UnmarshalJSON(data []byte) error { var err error var v interface{} if err = json.Unmarshal(data, &v); err != nil { return err } switch x := v.(type) { case string: s.String = x case map[string]interface{}: err = json.Unmarshal(data, &s.NullString) case nil: s.Valid = false return nil default: err = fmt.Errorf("json: cannot unmarshal %v into Go value of type zero.String", reflect.TypeOf(v).Name()) } s.Valid = (err == nil) && (s.String != "") return err }
go
func (s *String) UnmarshalJSON(data []byte) error { var err error var v interface{} if err = json.Unmarshal(data, &v); err != nil { return err } switch x := v.(type) { case string: s.String = x case map[string]interface{}: err = json.Unmarshal(data, &s.NullString) case nil: s.Valid = false return nil default: err = fmt.Errorf("json: cannot unmarshal %v into Go value of type zero.String", reflect.TypeOf(v).Name()) } s.Valid = (err == nil) && (s.String != "") return err }
[ "func", "(", "s", "*", "String", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "var", "err", "error", "\n", "var", "v", "interface", "{", "}", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "v", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "switch", "x", ":=", "v", ".", "(", "type", ")", "{", "case", "string", ":", "s", ".", "String", "=", "x", "\n", "case", "map", "[", "string", "]", "interface", "{", "}", ":", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "s", ".", "NullString", ")", "\n", "case", "nil", ":", "s", ".", "Valid", "=", "false", "\n", "return", "nil", "\n", "default", ":", "err", "=", "fmt", ".", "Errorf", "(", "\"json: cannot unmarshal %v into Go value of type zero.String\"", ",", "reflect", ".", "TypeOf", "(", "v", ")", ".", "Name", "(", ")", ")", "\n", "}", "\n", "s", ".", "Valid", "=", "(", "err", "==", "nil", ")", "&&", "(", "s", ".", "String", "!=", "\"\"", ")", "\n", "return", "err", "\n", "}" ]
// UnmarshalJSON implements json.Unmarshaler. // It supports string and null input. Blank string input produces a null String. // It also supports unmarshalling a sql.NullString.
[ "UnmarshalJSON", "implements", "json", ".", "Unmarshaler", ".", "It", "supports", "string", "and", "null", "input", ".", "Blank", "string", "input", "produces", "a", "null", "String", ".", "It", "also", "supports", "unmarshalling", "a", "sql", ".", "NullString", "." ]
80515d440932108546bcade467bb7d6968e812e2
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/zero/string.go#L48-L67
test
guregu/null
zero/string.go
MarshalText
func (s String) MarshalText() ([]byte, error) { if !s.Valid { return []byte{}, nil } return []byte(s.String), nil }
go
func (s String) MarshalText() ([]byte, error) { if !s.Valid { return []byte{}, nil } return []byte(s.String), nil }
[ "func", "(", "s", "String", ")", "MarshalText", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "!", "s", ".", "Valid", "{", "return", "[", "]", "byte", "{", "}", ",", "nil", "\n", "}", "\n", "return", "[", "]", "byte", "(", "s", ".", "String", ")", ",", "nil", "\n", "}" ]
// MarshalText implements encoding.TextMarshaler. // It will encode a blank string when this String is null.
[ "MarshalText", "implements", "encoding", ".", "TextMarshaler", ".", "It", "will", "encode", "a", "blank", "string", "when", "this", "String", "is", "null", "." ]
80515d440932108546bcade467bb7d6968e812e2
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/zero/string.go#L71-L76
test
guregu/null
zero/string.go
UnmarshalText
func (s *String) UnmarshalText(text []byte) error { s.String = string(text) s.Valid = s.String != "" return nil }
go
func (s *String) UnmarshalText(text []byte) error { s.String = string(text) s.Valid = s.String != "" return nil }
[ "func", "(", "s", "*", "String", ")", "UnmarshalText", "(", "text", "[", "]", "byte", ")", "error", "{", "s", ".", "String", "=", "string", "(", "text", ")", "\n", "s", ".", "Valid", "=", "s", ".", "String", "!=", "\"\"", "\n", "return", "nil", "\n", "}" ]
// UnmarshalText implements encoding.TextUnmarshaler. // It will unmarshal to a null String if the input is a blank string.
[ "UnmarshalText", "implements", "encoding", ".", "TextUnmarshaler", ".", "It", "will", "unmarshal", "to", "a", "null", "String", "if", "the", "input", "is", "a", "blank", "string", "." ]
80515d440932108546bcade467bb7d6968e812e2
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/zero/string.go#L80-L84
test
guregu/null
zero/string.go
SetValid
func (s *String) SetValid(v string) { s.String = v s.Valid = true }
go
func (s *String) SetValid(v string) { s.String = v s.Valid = true }
[ "func", "(", "s", "*", "String", ")", "SetValid", "(", "v", "string", ")", "{", "s", ".", "String", "=", "v", "\n", "s", ".", "Valid", "=", "true", "\n", "}" ]
// SetValid changes this String's value and also sets it to be non-null.
[ "SetValid", "changes", "this", "String", "s", "value", "and", "also", "sets", "it", "to", "be", "non", "-", "null", "." ]
80515d440932108546bcade467bb7d6968e812e2
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/zero/string.go#L87-L90
test
guregu/null
string.go
StringFromPtr
func StringFromPtr(s *string) String { if s == nil { return NewString("", false) } return NewString(*s, true) }
go
func StringFromPtr(s *string) String { if s == nil { return NewString("", false) } return NewString(*s, true) }
[ "func", "StringFromPtr", "(", "s", "*", "string", ")", "String", "{", "if", "s", "==", "nil", "{", "return", "NewString", "(", "\"\"", ",", "false", ")", "\n", "}", "\n", "return", "NewString", "(", "*", "s", ",", "true", ")", "\n", "}" ]
// StringFromPtr creates a new String that be null if s is nil.
[ "StringFromPtr", "creates", "a", "new", "String", "that", "be", "null", "if", "s", "is", "nil", "." ]
80515d440932108546bcade467bb7d6968e812e2
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/string.go#L26-L31
test
guregu/null
string.go
MarshalJSON
func (s String) MarshalJSON() ([]byte, error) { if !s.Valid { return []byte("null"), nil } return json.Marshal(s.String) }
go
func (s String) MarshalJSON() ([]byte, error) { if !s.Valid { return []byte("null"), nil } return json.Marshal(s.String) }
[ "func", "(", "s", "String", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "!", "s", ".", "Valid", "{", "return", "[", "]", "byte", "(", "\"null\"", ")", ",", "nil", "\n", "}", "\n", "return", "json", ".", "Marshal", "(", "s", ".", "String", ")", "\n", "}" ]
// MarshalJSON implements json.Marshaler. // It will encode null if this String is null.
[ "MarshalJSON", "implements", "json", ".", "Marshaler", ".", "It", "will", "encode", "null", "if", "this", "String", "is", "null", "." ]
80515d440932108546bcade467bb7d6968e812e2
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/string.go#L77-L82
test
guregu/null
zero/int.go
NewInt
func NewInt(i int64, valid bool) Int { return Int{ NullInt64: sql.NullInt64{ Int64: i, Valid: valid, }, } }
go
func NewInt(i int64, valid bool) Int { return Int{ NullInt64: sql.NullInt64{ Int64: i, Valid: valid, }, } }
[ "func", "NewInt", "(", "i", "int64", ",", "valid", "bool", ")", "Int", "{", "return", "Int", "{", "NullInt64", ":", "sql", ".", "NullInt64", "{", "Int64", ":", "i", ",", "Valid", ":", "valid", ",", "}", ",", "}", "\n", "}" ]
// NewInt creates a new Int
[ "NewInt", "creates", "a", "new", "Int" ]
80515d440932108546bcade467bb7d6968e812e2
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/zero/int.go#L19-L26
test
guregu/null
zero/int.go
IntFromPtr
func IntFromPtr(i *int64) Int { if i == nil { return NewInt(0, false) } n := NewInt(*i, true) return n }
go
func IntFromPtr(i *int64) Int { if i == nil { return NewInt(0, false) } n := NewInt(*i, true) return n }
[ "func", "IntFromPtr", "(", "i", "*", "int64", ")", "Int", "{", "if", "i", "==", "nil", "{", "return", "NewInt", "(", "0", ",", "false", ")", "\n", "}", "\n", "n", ":=", "NewInt", "(", "*", "i", ",", "true", ")", "\n", "return", "n", "\n", "}" ]
// IntFromPtr creates a new Int that be null if i is nil.
[ "IntFromPtr", "creates", "a", "new", "Int", "that", "be", "null", "if", "i", "is", "nil", "." ]
80515d440932108546bcade467bb7d6968e812e2
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/zero/int.go#L34-L40
test
guregu/null
zero/int.go
UnmarshalJSON
func (i *Int) UnmarshalJSON(data []byte) error { var err error var v interface{} if err = json.Unmarshal(data, &v); err != nil { return err } switch x := v.(type) { case float64: // Unmarshal again, directly to int64, to avoid intermediate float64 err = json.Unmarshal(data, &i.Int64) case string: str := string(x) if len(str) == 0 { i.Valid = false return nil } i.Int64, err = strconv.ParseInt(str, 10, 64) case map[string]interface{}: err = json.Unmarshal(data, &i.NullInt64) case nil: i.Valid = false return nil default: err = fmt.Errorf("json: cannot unmarshal %v into Go value of type zero.Int", reflect.TypeOf(v).Name()) } i.Valid = (err == nil) && (i.Int64 != 0) return err }
go
func (i *Int) UnmarshalJSON(data []byte) error { var err error var v interface{} if err = json.Unmarshal(data, &v); err != nil { return err } switch x := v.(type) { case float64: // Unmarshal again, directly to int64, to avoid intermediate float64 err = json.Unmarshal(data, &i.Int64) case string: str := string(x) if len(str) == 0 { i.Valid = false return nil } i.Int64, err = strconv.ParseInt(str, 10, 64) case map[string]interface{}: err = json.Unmarshal(data, &i.NullInt64) case nil: i.Valid = false return nil default: err = fmt.Errorf("json: cannot unmarshal %v into Go value of type zero.Int", reflect.TypeOf(v).Name()) } i.Valid = (err == nil) && (i.Int64 != 0) return err }
[ "func", "(", "i", "*", "Int", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "var", "err", "error", "\n", "var", "v", "interface", "{", "}", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "v", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "switch", "x", ":=", "v", ".", "(", "type", ")", "{", "case", "float64", ":", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "i", ".", "Int64", ")", "\n", "case", "string", ":", "str", ":=", "string", "(", "x", ")", "\n", "if", "len", "(", "str", ")", "==", "0", "{", "i", ".", "Valid", "=", "false", "\n", "return", "nil", "\n", "}", "\n", "i", ".", "Int64", ",", "err", "=", "strconv", ".", "ParseInt", "(", "str", ",", "10", ",", "64", ")", "\n", "case", "map", "[", "string", "]", "interface", "{", "}", ":", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "i", ".", "NullInt64", ")", "\n", "case", "nil", ":", "i", ".", "Valid", "=", "false", "\n", "return", "nil", "\n", "default", ":", "err", "=", "fmt", ".", "Errorf", "(", "\"json: cannot unmarshal %v into Go value of type zero.Int\"", ",", "reflect", ".", "TypeOf", "(", "v", ")", ".", "Name", "(", ")", ")", "\n", "}", "\n", "i", ".", "Valid", "=", "(", "err", "==", "nil", ")", "&&", "(", "i", ".", "Int64", "!=", "0", ")", "\n", "return", "err", "\n", "}" ]
// UnmarshalJSON implements json.Unmarshaler. // It supports number and null input. // 0 will be considered a null Int. // It also supports unmarshalling a sql.NullInt64.
[ "UnmarshalJSON", "implements", "json", ".", "Unmarshaler", ".", "It", "supports", "number", "and", "null", "input", ".", "0", "will", "be", "considered", "a", "null", "Int", ".", "It", "also", "supports", "unmarshalling", "a", "sql", ".", "NullInt64", "." ]
80515d440932108546bcade467bb7d6968e812e2
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/zero/int.go#L46-L73
test
guregu/null
zero/int.go
MarshalText
func (i Int) MarshalText() ([]byte, error) { n := i.Int64 if !i.Valid { n = 0 } return []byte(strconv.FormatInt(n, 10)), nil }
go
func (i Int) MarshalText() ([]byte, error) { n := i.Int64 if !i.Valid { n = 0 } return []byte(strconv.FormatInt(n, 10)), nil }
[ "func", "(", "i", "Int", ")", "MarshalText", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "n", ":=", "i", ".", "Int64", "\n", "if", "!", "i", ".", "Valid", "{", "n", "=", "0", "\n", "}", "\n", "return", "[", "]", "byte", "(", "strconv", ".", "FormatInt", "(", "n", ",", "10", ")", ")", ",", "nil", "\n", "}" ]
// MarshalText implements encoding.TextMarshaler. // It will encode a zero if this Int is null.
[ "MarshalText", "implements", "encoding", ".", "TextMarshaler", ".", "It", "will", "encode", "a", "zero", "if", "this", "Int", "is", "null", "." ]
80515d440932108546bcade467bb7d6968e812e2
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/zero/int.go#L102-L108
test
guregu/null
zero/int.go
SetValid
func (i *Int) SetValid(n int64) { i.Int64 = n i.Valid = true }
go
func (i *Int) SetValid(n int64) { i.Int64 = n i.Valid = true }
[ "func", "(", "i", "*", "Int", ")", "SetValid", "(", "n", "int64", ")", "{", "i", ".", "Int64", "=", "n", "\n", "i", ".", "Valid", "=", "true", "\n", "}" ]
// SetValid changes this Int's value and also sets it to be non-null.
[ "SetValid", "changes", "this", "Int", "s", "value", "and", "also", "sets", "it", "to", "be", "non", "-", "null", "." ]
80515d440932108546bcade467bb7d6968e812e2
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/zero/int.go#L111-L114
test
guregu/null
int.go
UnmarshalText
func (i *Int) UnmarshalText(text []byte) error { str := string(text) if str == "" || str == "null" { i.Valid = false return nil } var err error i.Int64, err = strconv.ParseInt(string(text), 10, 64) i.Valid = err == nil return err }
go
func (i *Int) UnmarshalText(text []byte) error { str := string(text) if str == "" || str == "null" { i.Valid = false return nil } var err error i.Int64, err = strconv.ParseInt(string(text), 10, 64) i.Valid = err == nil return err }
[ "func", "(", "i", "*", "Int", ")", "UnmarshalText", "(", "text", "[", "]", "byte", ")", "error", "{", "str", ":=", "string", "(", "text", ")", "\n", "if", "str", "==", "\"\"", "||", "str", "==", "\"null\"", "{", "i", ".", "Valid", "=", "false", "\n", "return", "nil", "\n", "}", "\n", "var", "err", "error", "\n", "i", ".", "Int64", ",", "err", "=", "strconv", ".", "ParseInt", "(", "string", "(", "text", ")", ",", "10", ",", "64", ")", "\n", "i", ".", "Valid", "=", "err", "==", "nil", "\n", "return", "err", "\n", "}" ]
// UnmarshalText implements encoding.TextUnmarshaler. // It will unmarshal to a null Int if the input is a blank or not an integer. // It will return an error if the input is not an integer, blank, or "null".
[ "UnmarshalText", "implements", "encoding", ".", "TextUnmarshaler", ".", "It", "will", "unmarshal", "to", "a", "null", "Int", "if", "the", "input", "is", "a", "blank", "or", "not", "an", "integer", ".", "It", "will", "return", "an", "error", "if", "the", "input", "is", "not", "an", "integer", "blank", "or", "null", "." ]
80515d440932108546bcade467bb7d6968e812e2
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/int.go#L85-L95
test
guregu/null
zero/bool.go
MarshalText
func (b Bool) MarshalText() ([]byte, error) { if !b.Valid || !b.Bool { return []byte("false"), nil } return []byte("true"), nil }
go
func (b Bool) MarshalText() ([]byte, error) { if !b.Valid || !b.Bool { return []byte("false"), nil } return []byte("true"), nil }
[ "func", "(", "b", "Bool", ")", "MarshalText", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "!", "b", ".", "Valid", "||", "!", "b", ".", "Bool", "{", "return", "[", "]", "byte", "(", "\"false\"", ")", ",", "nil", "\n", "}", "\n", "return", "[", "]", "byte", "(", "\"true\"", ")", ",", "nil", "\n", "}" ]
// MarshalText implements encoding.TextMarshaler. // It will encode a zero if this Bool is null.
[ "MarshalText", "implements", "encoding", ".", "TextMarshaler", ".", "It", "will", "encode", "a", "zero", "if", "this", "Bool", "is", "null", "." ]
80515d440932108546bcade467bb7d6968e812e2
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/zero/bool.go#L97-L102
test
guregu/null
zero/float.go
SetValid
func (f *Float) SetValid(v float64) { f.Float64 = v f.Valid = true }
go
func (f *Float) SetValid(v float64) { f.Float64 = v f.Valid = true }
[ "func", "(", "f", "*", "Float", ")", "SetValid", "(", "v", "float64", ")", "{", "f", ".", "Float64", "=", "v", "\n", "f", ".", "Valid", "=", "true", "\n", "}" ]
// SetValid changes this Float's value and also sets it to be non-null.
[ "SetValid", "changes", "this", "Float", "s", "value", "and", "also", "sets", "it", "to", "be", "non", "-", "null", "." ]
80515d440932108546bcade467bb7d6968e812e2
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/zero/float.go#L116-L119
test
guregu/null
zero/time.go
MarshalJSON
func (t Time) MarshalJSON() ([]byte, error) { if !t.Valid { return (time.Time{}).MarshalJSON() } return t.Time.MarshalJSON() }
go
func (t Time) MarshalJSON() ([]byte, error) { if !t.Valid { return (time.Time{}).MarshalJSON() } return t.Time.MarshalJSON() }
[ "func", "(", "t", "Time", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "!", "t", ".", "Valid", "{", "return", "(", "time", ".", "Time", "{", "}", ")", ".", "MarshalJSON", "(", ")", "\n", "}", "\n", "return", "t", ".", "Time", ".", "MarshalJSON", "(", ")", "\n", "}" ]
// MarshalJSON implements json.Marshaler. // It will encode the zero value of time.Time // if this time is invalid.
[ "MarshalJSON", "implements", "json", ".", "Marshaler", ".", "It", "will", "encode", "the", "zero", "value", "of", "time", ".", "Time", "if", "this", "time", "is", "invalid", "." ]
80515d440932108546bcade467bb7d6968e812e2
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/zero/time.go#L69-L74
test
guregu/null
float.go
UnmarshalJSON
func (f *Float) UnmarshalJSON(data []byte) error { var err error var v interface{} if err = json.Unmarshal(data, &v); err != nil { return err } switch x := v.(type) { case float64: f.Float64 = float64(x) case string: str := string(x) if len(str) == 0 { f.Valid = false return nil } f.Float64, err = strconv.ParseFloat(str, 64) case map[string]interface{}: err = json.Unmarshal(data, &f.NullFloat64) case nil: f.Valid = false return nil default: err = fmt.Errorf("json: cannot unmarshal %v into Go value of type null.Float", reflect.TypeOf(v).Name()) } f.Valid = err == nil return err }
go
func (f *Float) UnmarshalJSON(data []byte) error { var err error var v interface{} if err = json.Unmarshal(data, &v); err != nil { return err } switch x := v.(type) { case float64: f.Float64 = float64(x) case string: str := string(x) if len(str) == 0 { f.Valid = false return nil } f.Float64, err = strconv.ParseFloat(str, 64) case map[string]interface{}: err = json.Unmarshal(data, &f.NullFloat64) case nil: f.Valid = false return nil default: err = fmt.Errorf("json: cannot unmarshal %v into Go value of type null.Float", reflect.TypeOf(v).Name()) } f.Valid = err == nil return err }
[ "func", "(", "f", "*", "Float", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "var", "err", "error", "\n", "var", "v", "interface", "{", "}", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "v", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "switch", "x", ":=", "v", ".", "(", "type", ")", "{", "case", "float64", ":", "f", ".", "Float64", "=", "float64", "(", "x", ")", "\n", "case", "string", ":", "str", ":=", "string", "(", "x", ")", "\n", "if", "len", "(", "str", ")", "==", "0", "{", "f", ".", "Valid", "=", "false", "\n", "return", "nil", "\n", "}", "\n", "f", ".", "Float64", ",", "err", "=", "strconv", ".", "ParseFloat", "(", "str", ",", "64", ")", "\n", "case", "map", "[", "string", "]", "interface", "{", "}", ":", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "f", ".", "NullFloat64", ")", "\n", "case", "nil", ":", "f", ".", "Valid", "=", "false", "\n", "return", "nil", "\n", "default", ":", "err", "=", "fmt", ".", "Errorf", "(", "\"json: cannot unmarshal %v into Go value of type null.Float\"", ",", "reflect", ".", "TypeOf", "(", "v", ")", ".", "Name", "(", ")", ")", "\n", "}", "\n", "f", ".", "Valid", "=", "err", "==", "nil", "\n", "return", "err", "\n", "}" ]
// UnmarshalJSON implements json.Unmarshaler. // It supports number and null input. // 0 will not be considered a null Float. // It also supports unmarshalling a sql.NullFloat64.
[ "UnmarshalJSON", "implements", "json", ".", "Unmarshaler", ".", "It", "supports", "number", "and", "null", "input", ".", "0", "will", "not", "be", "considered", "a", "null", "Float", ".", "It", "also", "supports", "unmarshalling", "a", "sql", ".", "NullFloat64", "." ]
80515d440932108546bcade467bb7d6968e812e2
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/float.go#L54-L80
test
guregu/null
float.go
UnmarshalText
func (f *Float) UnmarshalText(text []byte) error { str := string(text) if str == "" || str == "null" { f.Valid = false return nil } var err error f.Float64, err = strconv.ParseFloat(string(text), 64) f.Valid = err == nil return err }
go
func (f *Float) UnmarshalText(text []byte) error { str := string(text) if str == "" || str == "null" { f.Valid = false return nil } var err error f.Float64, err = strconv.ParseFloat(string(text), 64) f.Valid = err == nil return err }
[ "func", "(", "f", "*", "Float", ")", "UnmarshalText", "(", "text", "[", "]", "byte", ")", "error", "{", "str", ":=", "string", "(", "text", ")", "\n", "if", "str", "==", "\"\"", "||", "str", "==", "\"null\"", "{", "f", ".", "Valid", "=", "false", "\n", "return", "nil", "\n", "}", "\n", "var", "err", "error", "\n", "f", ".", "Float64", ",", "err", "=", "strconv", ".", "ParseFloat", "(", "string", "(", "text", ")", ",", "64", ")", "\n", "f", ".", "Valid", "=", "err", "==", "nil", "\n", "return", "err", "\n", "}" ]
// UnmarshalText implements encoding.TextUnmarshaler. // It will unmarshal to a null Float if the input is a blank or not an integer. // It will return an error if the input is not an integer, blank, or "null".
[ "UnmarshalText", "implements", "encoding", ".", "TextUnmarshaler", ".", "It", "will", "unmarshal", "to", "a", "null", "Float", "if", "the", "input", "is", "a", "blank", "or", "not", "an", "integer", ".", "It", "will", "return", "an", "error", "if", "the", "input", "is", "not", "an", "integer", "blank", "or", "null", "." ]
80515d440932108546bcade467bb7d6968e812e2
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/float.go#L85-L95
test
guregu/null
float.go
MarshalJSON
func (f Float) MarshalJSON() ([]byte, error) { if !f.Valid { return []byte("null"), nil } if math.IsInf(f.Float64, 0) || math.IsNaN(f.Float64) { return nil, &json.UnsupportedValueError{ Value: reflect.ValueOf(f.Float64), Str: strconv.FormatFloat(f.Float64, 'g', -1, 64), } } return []byte(strconv.FormatFloat(f.Float64, 'f', -1, 64)), nil }
go
func (f Float) MarshalJSON() ([]byte, error) { if !f.Valid { return []byte("null"), nil } if math.IsInf(f.Float64, 0) || math.IsNaN(f.Float64) { return nil, &json.UnsupportedValueError{ Value: reflect.ValueOf(f.Float64), Str: strconv.FormatFloat(f.Float64, 'g', -1, 64), } } return []byte(strconv.FormatFloat(f.Float64, 'f', -1, 64)), nil }
[ "func", "(", "f", "Float", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "!", "f", ".", "Valid", "{", "return", "[", "]", "byte", "(", "\"null\"", ")", ",", "nil", "\n", "}", "\n", "if", "math", ".", "IsInf", "(", "f", ".", "Float64", ",", "0", ")", "||", "math", ".", "IsNaN", "(", "f", ".", "Float64", ")", "{", "return", "nil", ",", "&", "json", ".", "UnsupportedValueError", "{", "Value", ":", "reflect", ".", "ValueOf", "(", "f", ".", "Float64", ")", ",", "Str", ":", "strconv", ".", "FormatFloat", "(", "f", ".", "Float64", ",", "'g'", ",", "-", "1", ",", "64", ")", ",", "}", "\n", "}", "\n", "return", "[", "]", "byte", "(", "strconv", ".", "FormatFloat", "(", "f", ".", "Float64", ",", "'f'", ",", "-", "1", ",", "64", ")", ")", ",", "nil", "\n", "}" ]
// MarshalJSON implements json.Marshaler. // It will encode null if this Float is null.
[ "MarshalJSON", "implements", "json", ".", "Marshaler", ".", "It", "will", "encode", "null", "if", "this", "Float", "is", "null", "." ]
80515d440932108546bcade467bb7d6968e812e2
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/float.go#L99-L110
test
weaveworks/mesh
gossip_channel.go
newGossipChannel
func newGossipChannel(channelName string, ourself *localPeer, r *routes, g Gossiper, logger Logger) *gossipChannel { return &gossipChannel{ name: channelName, ourself: ourself, routes: r, gossiper: g, logger: logger, } }
go
func newGossipChannel(channelName string, ourself *localPeer, r *routes, g Gossiper, logger Logger) *gossipChannel { return &gossipChannel{ name: channelName, ourself: ourself, routes: r, gossiper: g, logger: logger, } }
[ "func", "newGossipChannel", "(", "channelName", "string", ",", "ourself", "*", "localPeer", ",", "r", "*", "routes", ",", "g", "Gossiper", ",", "logger", "Logger", ")", "*", "gossipChannel", "{", "return", "&", "gossipChannel", "{", "name", ":", "channelName", ",", "ourself", ":", "ourself", ",", "routes", ":", "r", ",", "gossiper", ":", "g", ",", "logger", ":", "logger", ",", "}", "\n", "}" ]
// newGossipChannel returns a named, usable channel. // It delegates receiving duties to the passed Gossiper.
[ "newGossipChannel", "returns", "a", "named", "usable", "channel", ".", "It", "delegates", "receiving", "duties", "to", "the", "passed", "Gossiper", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/gossip_channel.go#L20-L28
test
weaveworks/mesh
gossip_channel.go
GossipUnicast
func (c *gossipChannel) GossipUnicast(dstPeerName PeerName, msg []byte) error { return c.relayUnicast(dstPeerName, gobEncode(c.name, c.ourself.Name, dstPeerName, msg)) }
go
func (c *gossipChannel) GossipUnicast(dstPeerName PeerName, msg []byte) error { return c.relayUnicast(dstPeerName, gobEncode(c.name, c.ourself.Name, dstPeerName, msg)) }
[ "func", "(", "c", "*", "gossipChannel", ")", "GossipUnicast", "(", "dstPeerName", "PeerName", ",", "msg", "[", "]", "byte", ")", "error", "{", "return", "c", ".", "relayUnicast", "(", "dstPeerName", ",", "gobEncode", "(", "c", ".", "name", ",", "c", ".", "ourself", ".", "Name", ",", "dstPeerName", ",", "msg", ")", ")", "\n", "}" ]
// GossipUnicast implements Gossip, relaying msg to dst, which must be a // member of the channel.
[ "GossipUnicast", "implements", "Gossip", "relaying", "msg", "to", "dst", "which", "must", "be", "a", "member", "of", "the", "channel", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/gossip_channel.go#L76-L78
test
weaveworks/mesh
gossip_channel.go
GossipBroadcast
func (c *gossipChannel) GossipBroadcast(update GossipData) { c.relayBroadcast(c.ourself.Name, update) }
go
func (c *gossipChannel) GossipBroadcast(update GossipData) { c.relayBroadcast(c.ourself.Name, update) }
[ "func", "(", "c", "*", "gossipChannel", ")", "GossipBroadcast", "(", "update", "GossipData", ")", "{", "c", ".", "relayBroadcast", "(", "c", ".", "ourself", ".", "Name", ",", "update", ")", "\n", "}" ]
// GossipBroadcast implements Gossip, relaying update to all members of the // channel.
[ "GossipBroadcast", "implements", "Gossip", "relaying", "update", "to", "all", "members", "of", "the", "channel", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/gossip_channel.go#L82-L84
test
weaveworks/mesh
gossip_channel.go
Send
func (c *gossipChannel) Send(data GossipData) { c.relay(c.ourself.Name, data) }
go
func (c *gossipChannel) Send(data GossipData) { c.relay(c.ourself.Name, data) }
[ "func", "(", "c", "*", "gossipChannel", ")", "Send", "(", "data", "GossipData", ")", "{", "c", ".", "relay", "(", "c", ".", "ourself", ".", "Name", ",", "data", ")", "\n", "}" ]
// Send relays data into the channel topology via random neighbours.
[ "Send", "relays", "data", "into", "the", "channel", "topology", "via", "random", "neighbours", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/gossip_channel.go#L87-L89
test
weaveworks/mesh
gossip_channel.go
SendDown
func (c *gossipChannel) SendDown(conn Connection, data GossipData) { c.senderFor(conn).Send(data) }
go
func (c *gossipChannel) SendDown(conn Connection, data GossipData) { c.senderFor(conn).Send(data) }
[ "func", "(", "c", "*", "gossipChannel", ")", "SendDown", "(", "conn", "Connection", ",", "data", "GossipData", ")", "{", "c", ".", "senderFor", "(", "conn", ")", ".", "Send", "(", "data", ")", "\n", "}" ]
// SendDown relays data into the channel topology via conn.
[ "SendDown", "relays", "data", "into", "the", "channel", "topology", "via", "conn", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/gossip_channel.go#L92-L94
test
weaveworks/mesh
gossip_channel.go
gobEncode
func gobEncode(items ...interface{}) []byte { buf := new(bytes.Buffer) enc := gob.NewEncoder(buf) for _, i := range items { if err := enc.Encode(i); err != nil { panic(err) } } return buf.Bytes() }
go
func gobEncode(items ...interface{}) []byte { buf := new(bytes.Buffer) enc := gob.NewEncoder(buf) for _, i := range items { if err := enc.Encode(i); err != nil { panic(err) } } return buf.Bytes() }
[ "func", "gobEncode", "(", "items", "...", "interface", "{", "}", ")", "[", "]", "byte", "{", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "enc", ":=", "gob", ".", "NewEncoder", "(", "buf", ")", "\n", "for", "_", ",", "i", ":=", "range", "items", "{", "if", "err", ":=", "enc", ".", "Encode", "(", "i", ")", ";", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "buf", ".", "Bytes", "(", ")", "\n", "}" ]
// GobEncode gob-encodes each item and returns the resulting byte slice.
[ "GobEncode", "gob", "-", "encodes", "each", "item", "and", "returns", "the", "resulting", "byte", "slice", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/gossip_channel.go#L143-L152
test
weaveworks/mesh
token_bucket.go
newTokenBucket
func newTokenBucket(capacity int64, tokenInterval time.Duration) *tokenBucket { tb := tokenBucket{ capacity: capacity, tokenInterval: tokenInterval, refillDuration: tokenInterval * time.Duration(capacity)} tb.earliestUnspentToken = tb.capacityToken() return &tb }
go
func newTokenBucket(capacity int64, tokenInterval time.Duration) *tokenBucket { tb := tokenBucket{ capacity: capacity, tokenInterval: tokenInterval, refillDuration: tokenInterval * time.Duration(capacity)} tb.earliestUnspentToken = tb.capacityToken() return &tb }
[ "func", "newTokenBucket", "(", "capacity", "int64", ",", "tokenInterval", "time", ".", "Duration", ")", "*", "tokenBucket", "{", "tb", ":=", "tokenBucket", "{", "capacity", ":", "capacity", ",", "tokenInterval", ":", "tokenInterval", ",", "refillDuration", ":", "tokenInterval", "*", "time", ".", "Duration", "(", "capacity", ")", "}", "\n", "tb", ".", "earliestUnspentToken", "=", "tb", ".", "capacityToken", "(", ")", "\n", "return", "&", "tb", "\n", "}" ]
// newTokenBucket returns a bucket containing capacity tokens, refilled at a // rate of one token per tokenInterval.
[ "newTokenBucket", "returns", "a", "bucket", "containing", "capacity", "tokens", "refilled", "at", "a", "rate", "of", "one", "token", "per", "tokenInterval", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/token_bucket.go#L18-L27
test
weaveworks/mesh
token_bucket.go
wait
func (tb *tokenBucket) wait() { // If earliest unspent token is in the future, sleep until then time.Sleep(time.Until(tb.earliestUnspentToken)) // Alternatively, enforce bucket capacity if necessary capacityToken := tb.capacityToken() if tb.earliestUnspentToken.Before(capacityToken) { tb.earliestUnspentToken = capacityToken } // 'Remove' a token from the bucket tb.earliestUnspentToken = tb.earliestUnspentToken.Add(tb.tokenInterval) }
go
func (tb *tokenBucket) wait() { // If earliest unspent token is in the future, sleep until then time.Sleep(time.Until(tb.earliestUnspentToken)) // Alternatively, enforce bucket capacity if necessary capacityToken := tb.capacityToken() if tb.earliestUnspentToken.Before(capacityToken) { tb.earliestUnspentToken = capacityToken } // 'Remove' a token from the bucket tb.earliestUnspentToken = tb.earliestUnspentToken.Add(tb.tokenInterval) }
[ "func", "(", "tb", "*", "tokenBucket", ")", "wait", "(", ")", "{", "time", ".", "Sleep", "(", "time", ".", "Until", "(", "tb", ".", "earliestUnspentToken", ")", ")", "\n", "capacityToken", ":=", "tb", ".", "capacityToken", "(", ")", "\n", "if", "tb", ".", "earliestUnspentToken", ".", "Before", "(", "capacityToken", ")", "{", "tb", ".", "earliestUnspentToken", "=", "capacityToken", "\n", "}", "\n", "tb", ".", "earliestUnspentToken", "=", "tb", ".", "earliestUnspentToken", ".", "Add", "(", "tb", ".", "tokenInterval", ")", "\n", "}" ]
// Blocks until there is a token available. // Not safe for concurrent use by multiple goroutines.
[ "Blocks", "until", "there", "is", "a", "token", "available", ".", "Not", "safe", "for", "concurrent", "use", "by", "multiple", "goroutines", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/token_bucket.go#L31-L43
test
weaveworks/mesh
token_bucket.go
capacityToken
func (tb *tokenBucket) capacityToken() time.Time { return time.Now().Add(-tb.refillDuration).Truncate(tb.tokenInterval) }
go
func (tb *tokenBucket) capacityToken() time.Time { return time.Now().Add(-tb.refillDuration).Truncate(tb.tokenInterval) }
[ "func", "(", "tb", "*", "tokenBucket", ")", "capacityToken", "(", ")", "time", ".", "Time", "{", "return", "time", ".", "Now", "(", ")", ".", "Add", "(", "-", "tb", ".", "refillDuration", ")", ".", "Truncate", "(", "tb", ".", "tokenInterval", ")", "\n", "}" ]
// Determine the historic token timestamp representing a full bucket
[ "Determine", "the", "historic", "token", "timestamp", "representing", "a", "full", "bucket" ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/token_bucket.go#L46-L48
test
weaveworks/mesh
_metcd/key_helpers.go
PrefixRangeEnd
func PrefixRangeEnd(prefix []byte) []byte { // https://github.com/coreos/etcd/blob/17e32b6/clientv3/op.go#L187 end := make([]byte, len(prefix)) copy(end, prefix) for i := len(end) - 1; i >= 0; i-- { if end[i] < 0xff { end[i] = end[i] + 1 end = end[:i+1] return end } } // next prefix does not exist (e.g., 0xffff); // default to WithFromKey policy return []byte{0} }
go
func PrefixRangeEnd(prefix []byte) []byte { // https://github.com/coreos/etcd/blob/17e32b6/clientv3/op.go#L187 end := make([]byte, len(prefix)) copy(end, prefix) for i := len(end) - 1; i >= 0; i-- { if end[i] < 0xff { end[i] = end[i] + 1 end = end[:i+1] return end } } // next prefix does not exist (e.g., 0xffff); // default to WithFromKey policy return []byte{0} }
[ "func", "PrefixRangeEnd", "(", "prefix", "[", "]", "byte", ")", "[", "]", "byte", "{", "end", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "prefix", ")", ")", "\n", "copy", "(", "end", ",", "prefix", ")", "\n", "for", "i", ":=", "len", "(", "end", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "if", "end", "[", "i", "]", "<", "0xff", "{", "end", "[", "i", "]", "=", "end", "[", "i", "]", "+", "1", "\n", "end", "=", "end", "[", ":", "i", "+", "1", "]", "\n", "return", "end", "\n", "}", "\n", "}", "\n", "return", "[", "]", "byte", "{", "0", "}", "\n", "}" ]
// PrefixRangeEnd allows Get, Delete, and Watch requests to operate on all keys // with a matching prefix. Pass the prefix to this function, and use the result // as the RangeEnd value.
[ "PrefixRangeEnd", "allows", "Get", "Delete", "and", "Watch", "requests", "to", "operate", "on", "all", "keys", "with", "a", "matching", "prefix", ".", "Pass", "the", "prefix", "to", "this", "function", "and", "use", "the", "result", "as", "the", "RangeEnd", "value", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/_metcd/key_helpers.go#L6-L20
test
weaveworks/mesh
local_peer.go
newLocalPeer
func newLocalPeer(name PeerName, nickName string, router *Router) *localPeer { actionChan := make(chan localPeerAction, ChannelSize) peer := &localPeer{ Peer: newPeer(name, nickName, randomPeerUID(), 0, randomPeerShortID()), router: router, actionChan: actionChan, } go peer.actorLoop(actionChan) return peer }
go
func newLocalPeer(name PeerName, nickName string, router *Router) *localPeer { actionChan := make(chan localPeerAction, ChannelSize) peer := &localPeer{ Peer: newPeer(name, nickName, randomPeerUID(), 0, randomPeerShortID()), router: router, actionChan: actionChan, } go peer.actorLoop(actionChan) return peer }
[ "func", "newLocalPeer", "(", "name", "PeerName", ",", "nickName", "string", ",", "router", "*", "Router", ")", "*", "localPeer", "{", "actionChan", ":=", "make", "(", "chan", "localPeerAction", ",", "ChannelSize", ")", "\n", "peer", ":=", "&", "localPeer", "{", "Peer", ":", "newPeer", "(", "name", ",", "nickName", ",", "randomPeerUID", "(", ")", ",", "0", ",", "randomPeerShortID", "(", ")", ")", ",", "router", ":", "router", ",", "actionChan", ":", "actionChan", ",", "}", "\n", "go", "peer", ".", "actorLoop", "(", "actionChan", ")", "\n", "return", "peer", "\n", "}" ]
// newLocalPeer returns a usable LocalPeer.
[ "newLocalPeer", "returns", "a", "usable", "LocalPeer", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/local_peer.go#L24-L33
test
weaveworks/mesh
local_peer.go
getConnections
func (peer *localPeer) getConnections() connectionSet { connections := make(connectionSet) peer.RLock() defer peer.RUnlock() for _, conn := range peer.connections { connections[conn] = struct{}{} } return connections }
go
func (peer *localPeer) getConnections() connectionSet { connections := make(connectionSet) peer.RLock() defer peer.RUnlock() for _, conn := range peer.connections { connections[conn] = struct{}{} } return connections }
[ "func", "(", "peer", "*", "localPeer", ")", "getConnections", "(", ")", "connectionSet", "{", "connections", ":=", "make", "(", "connectionSet", ")", "\n", "peer", ".", "RLock", "(", ")", "\n", "defer", "peer", ".", "RUnlock", "(", ")", "\n", "for", "_", ",", "conn", ":=", "range", "peer", ".", "connections", "{", "connections", "[", "conn", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "return", "connections", "\n", "}" ]
// Connections returns all the connections that the local peer is aware of.
[ "Connections", "returns", "all", "the", "connections", "that", "the", "local", "peer", "is", "aware", "of", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/local_peer.go#L36-L44
test
weaveworks/mesh
local_peer.go
createConnection
func (peer *localPeer) createConnection(localAddr string, peerAddr string, acceptNewPeer bool, logger Logger) error { if err := peer.checkConnectionLimit(); err != nil { return err } localTCPAddr, err := net.ResolveTCPAddr("tcp", localAddr) if err != nil { return err } remoteTCPAddr, err := net.ResolveTCPAddr("tcp", peerAddr) if err != nil { return err } tcpConn, err := net.DialTCP("tcp", localTCPAddr, remoteTCPAddr) if err != nil { return err } connRemote := newRemoteConnection(peer.Peer, nil, peerAddr, true, false) startLocalConnection(connRemote, tcpConn, peer.router, acceptNewPeer, logger) return nil }
go
func (peer *localPeer) createConnection(localAddr string, peerAddr string, acceptNewPeer bool, logger Logger) error { if err := peer.checkConnectionLimit(); err != nil { return err } localTCPAddr, err := net.ResolveTCPAddr("tcp", localAddr) if err != nil { return err } remoteTCPAddr, err := net.ResolveTCPAddr("tcp", peerAddr) if err != nil { return err } tcpConn, err := net.DialTCP("tcp", localTCPAddr, remoteTCPAddr) if err != nil { return err } connRemote := newRemoteConnection(peer.Peer, nil, peerAddr, true, false) startLocalConnection(connRemote, tcpConn, peer.router, acceptNewPeer, logger) return nil }
[ "func", "(", "peer", "*", "localPeer", ")", "createConnection", "(", "localAddr", "string", ",", "peerAddr", "string", ",", "acceptNewPeer", "bool", ",", "logger", "Logger", ")", "error", "{", "if", "err", ":=", "peer", ".", "checkConnectionLimit", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "localTCPAddr", ",", "err", ":=", "net", ".", "ResolveTCPAddr", "(", "\"tcp\"", ",", "localAddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "remoteTCPAddr", ",", "err", ":=", "net", ".", "ResolveTCPAddr", "(", "\"tcp\"", ",", "peerAddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "tcpConn", ",", "err", ":=", "net", ".", "DialTCP", "(", "\"tcp\"", ",", "localTCPAddr", ",", "remoteTCPAddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "connRemote", ":=", "newRemoteConnection", "(", "peer", ".", "Peer", ",", "nil", ",", "peerAddr", ",", "true", ",", "false", ")", "\n", "startLocalConnection", "(", "connRemote", ",", "tcpConn", ",", "peer", ".", "router", ",", "acceptNewPeer", ",", "logger", ")", "\n", "return", "nil", "\n", "}" ]
// createConnection creates a new connection, originating from // localAddr, to peerAddr. If acceptNewPeer is false, peerAddr must // already be a member of the mesh.
[ "createConnection", "creates", "a", "new", "connection", "originating", "from", "localAddr", "to", "peerAddr", ".", "If", "acceptNewPeer", "is", "false", "peerAddr", "must", "already", "be", "a", "member", "of", "the", "mesh", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/local_peer.go#L81-L100
test
weaveworks/mesh
local_peer.go
doAddConnection
func (peer *localPeer) doAddConnection(conn ourConnection, isRestartedPeer bool) error { resultChan := make(chan error) peer.actionChan <- func() { resultChan <- peer.handleAddConnection(conn, isRestartedPeer) } return <-resultChan }
go
func (peer *localPeer) doAddConnection(conn ourConnection, isRestartedPeer bool) error { resultChan := make(chan error) peer.actionChan <- func() { resultChan <- peer.handleAddConnection(conn, isRestartedPeer) } return <-resultChan }
[ "func", "(", "peer", "*", "localPeer", ")", "doAddConnection", "(", "conn", "ourConnection", ",", "isRestartedPeer", "bool", ")", "error", "{", "resultChan", ":=", "make", "(", "chan", "error", ")", "\n", "peer", ".", "actionChan", "<-", "func", "(", ")", "{", "resultChan", "<-", "peer", ".", "handleAddConnection", "(", "conn", ",", "isRestartedPeer", ")", "\n", "}", "\n", "return", "<-", "resultChan", "\n", "}" ]
// ACTOR client API // Synchronous.
[ "ACTOR", "client", "API", "Synchronous", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/local_peer.go#L105-L111
test
weaveworks/mesh
connection.go
startLocalConnection
func startLocalConnection(connRemote *remoteConnection, tcpConn *net.TCPConn, router *Router, acceptNewPeer bool, logger Logger) { if connRemote.local != router.Ourself.Peer { panic("attempt to create local connection from a peer which is not ourself") } errorChan := make(chan error, 1) finished := make(chan struct{}) conn := &LocalConnection{ remoteConnection: *connRemote, // NB, we're taking a copy of connRemote here. router: router, tcpConn: tcpConn, trustRemote: router.trusts(connRemote), uid: randUint64(), errorChan: errorChan, finished: finished, logger: logger, } conn.senders = newGossipSenders(conn, finished) go conn.run(errorChan, finished, acceptNewPeer) }
go
func startLocalConnection(connRemote *remoteConnection, tcpConn *net.TCPConn, router *Router, acceptNewPeer bool, logger Logger) { if connRemote.local != router.Ourself.Peer { panic("attempt to create local connection from a peer which is not ourself") } errorChan := make(chan error, 1) finished := make(chan struct{}) conn := &LocalConnection{ remoteConnection: *connRemote, // NB, we're taking a copy of connRemote here. router: router, tcpConn: tcpConn, trustRemote: router.trusts(connRemote), uid: randUint64(), errorChan: errorChan, finished: finished, logger: logger, } conn.senders = newGossipSenders(conn, finished) go conn.run(errorChan, finished, acceptNewPeer) }
[ "func", "startLocalConnection", "(", "connRemote", "*", "remoteConnection", ",", "tcpConn", "*", "net", ".", "TCPConn", ",", "router", "*", "Router", ",", "acceptNewPeer", "bool", ",", "logger", "Logger", ")", "{", "if", "connRemote", ".", "local", "!=", "router", ".", "Ourself", ".", "Peer", "{", "panic", "(", "\"attempt to create local connection from a peer which is not ourself\"", ")", "\n", "}", "\n", "errorChan", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "finished", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "conn", ":=", "&", "LocalConnection", "{", "remoteConnection", ":", "*", "connRemote", ",", "router", ":", "router", ",", "tcpConn", ":", "tcpConn", ",", "trustRemote", ":", "router", ".", "trusts", "(", "connRemote", ")", ",", "uid", ":", "randUint64", "(", ")", ",", "errorChan", ":", "errorChan", ",", "finished", ":", "finished", ",", "logger", ":", "logger", ",", "}", "\n", "conn", ".", "senders", "=", "newGossipSenders", "(", "conn", ",", "finished", ")", "\n", "go", "conn", ".", "run", "(", "errorChan", ",", "finished", ",", "acceptNewPeer", ")", "\n", "}" ]
// If the connection is successful, it will end up in the local peer's // connections map.
[ "If", "the", "connection", "is", "successful", "it", "will", "end", "up", "in", "the", "local", "peer", "s", "connections", "map", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/connection.go#L82-L100
test
weaveworks/mesh
connection.go
SendProtocolMsg
func (conn *LocalConnection) SendProtocolMsg(m protocolMsg) error { if err := conn.sendProtocolMsg(m); err != nil { conn.shutdown(err) return err } return nil }
go
func (conn *LocalConnection) SendProtocolMsg(m protocolMsg) error { if err := conn.sendProtocolMsg(m); err != nil { conn.shutdown(err) return err } return nil }
[ "func", "(", "conn", "*", "LocalConnection", ")", "SendProtocolMsg", "(", "m", "protocolMsg", ")", "error", "{", "if", "err", ":=", "conn", ".", "sendProtocolMsg", "(", "m", ")", ";", "err", "!=", "nil", "{", "conn", ".", "shutdown", "(", "err", ")", "\n", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SendProtocolMsg implements ProtocolSender.
[ "SendProtocolMsg", "implements", "ProtocolSender", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/connection.go#L126-L132
test
weaveworks/mesh
status.go
NewStatus
func NewStatus(router *Router) *Status { return &Status{ Protocol: Protocol, ProtocolMinVersion: int(router.ProtocolMinVersion), ProtocolMaxVersion: ProtocolMaxVersion, Encryption: router.usingPassword(), PeerDiscovery: router.PeerDiscovery, Name: router.Ourself.Name.String(), NickName: router.Ourself.NickName, Port: router.Port, Peers: makePeerStatusSlice(router.Peers), UnicastRoutes: makeUnicastRouteStatusSlice(router.Routes), BroadcastRoutes: makeBroadcastRouteStatusSlice(router.Routes), Connections: makeLocalConnectionStatusSlice(router.ConnectionMaker), TerminationCount: router.ConnectionMaker.terminationCount, Targets: router.ConnectionMaker.Targets(false), OverlayDiagnostics: router.Overlay.Diagnostics(), TrustedSubnets: makeTrustedSubnetsSlice(router.TrustedSubnets), } }
go
func NewStatus(router *Router) *Status { return &Status{ Protocol: Protocol, ProtocolMinVersion: int(router.ProtocolMinVersion), ProtocolMaxVersion: ProtocolMaxVersion, Encryption: router.usingPassword(), PeerDiscovery: router.PeerDiscovery, Name: router.Ourself.Name.String(), NickName: router.Ourself.NickName, Port: router.Port, Peers: makePeerStatusSlice(router.Peers), UnicastRoutes: makeUnicastRouteStatusSlice(router.Routes), BroadcastRoutes: makeBroadcastRouteStatusSlice(router.Routes), Connections: makeLocalConnectionStatusSlice(router.ConnectionMaker), TerminationCount: router.ConnectionMaker.terminationCount, Targets: router.ConnectionMaker.Targets(false), OverlayDiagnostics: router.Overlay.Diagnostics(), TrustedSubnets: makeTrustedSubnetsSlice(router.TrustedSubnets), } }
[ "func", "NewStatus", "(", "router", "*", "Router", ")", "*", "Status", "{", "return", "&", "Status", "{", "Protocol", ":", "Protocol", ",", "ProtocolMinVersion", ":", "int", "(", "router", ".", "ProtocolMinVersion", ")", ",", "ProtocolMaxVersion", ":", "ProtocolMaxVersion", ",", "Encryption", ":", "router", ".", "usingPassword", "(", ")", ",", "PeerDiscovery", ":", "router", ".", "PeerDiscovery", ",", "Name", ":", "router", ".", "Ourself", ".", "Name", ".", "String", "(", ")", ",", "NickName", ":", "router", ".", "Ourself", ".", "NickName", ",", "Port", ":", "router", ".", "Port", ",", "Peers", ":", "makePeerStatusSlice", "(", "router", ".", "Peers", ")", ",", "UnicastRoutes", ":", "makeUnicastRouteStatusSlice", "(", "router", ".", "Routes", ")", ",", "BroadcastRoutes", ":", "makeBroadcastRouteStatusSlice", "(", "router", ".", "Routes", ")", ",", "Connections", ":", "makeLocalConnectionStatusSlice", "(", "router", ".", "ConnectionMaker", ")", ",", "TerminationCount", ":", "router", ".", "ConnectionMaker", ".", "terminationCount", ",", "Targets", ":", "router", ".", "ConnectionMaker", ".", "Targets", "(", "false", ")", ",", "OverlayDiagnostics", ":", "router", ".", "Overlay", ".", "Diagnostics", "(", ")", ",", "TrustedSubnets", ":", "makeTrustedSubnetsSlice", "(", "router", ".", "TrustedSubnets", ")", ",", "}", "\n", "}" ]
// NewStatus returns a Status object, taken as a snapshot from the router.
[ "NewStatus", "returns", "a", "Status", "object", "taken", "as", "a", "snapshot", "from", "the", "router", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/status.go#L30-L49
test
weaveworks/mesh
status.go
makePeerStatusSlice
func makePeerStatusSlice(peers *Peers) []PeerStatus { var slice []PeerStatus peers.forEach(func(peer *Peer) { var connections []connectionStatus if peer == peers.ourself.Peer { for conn := range peers.ourself.getConnections() { connections = append(connections, makeConnectionStatus(conn)) } } else { // Modifying peer.connections requires a write lock on // Peers, and since we are holding a read lock (due to the // ForEach), access without locking the peer is safe. for _, conn := range peer.connections { connections = append(connections, makeConnectionStatus(conn)) } } slice = append(slice, PeerStatus{ peer.Name.String(), peer.NickName, peer.UID, peer.ShortID, peer.Version, connections, }) }) return slice }
go
func makePeerStatusSlice(peers *Peers) []PeerStatus { var slice []PeerStatus peers.forEach(func(peer *Peer) { var connections []connectionStatus if peer == peers.ourself.Peer { for conn := range peers.ourself.getConnections() { connections = append(connections, makeConnectionStatus(conn)) } } else { // Modifying peer.connections requires a write lock on // Peers, and since we are holding a read lock (due to the // ForEach), access without locking the peer is safe. for _, conn := range peer.connections { connections = append(connections, makeConnectionStatus(conn)) } } slice = append(slice, PeerStatus{ peer.Name.String(), peer.NickName, peer.UID, peer.ShortID, peer.Version, connections, }) }) return slice }
[ "func", "makePeerStatusSlice", "(", "peers", "*", "Peers", ")", "[", "]", "PeerStatus", "{", "var", "slice", "[", "]", "PeerStatus", "\n", "peers", ".", "forEach", "(", "func", "(", "peer", "*", "Peer", ")", "{", "var", "connections", "[", "]", "connectionStatus", "\n", "if", "peer", "==", "peers", ".", "ourself", ".", "Peer", "{", "for", "conn", ":=", "range", "peers", ".", "ourself", ".", "getConnections", "(", ")", "{", "connections", "=", "append", "(", "connections", ",", "makeConnectionStatus", "(", "conn", ")", ")", "\n", "}", "\n", "}", "else", "{", "for", "_", ",", "conn", ":=", "range", "peer", ".", "connections", "{", "connections", "=", "append", "(", "connections", ",", "makeConnectionStatus", "(", "conn", ")", ")", "\n", "}", "\n", "}", "\n", "slice", "=", "append", "(", "slice", ",", "PeerStatus", "{", "peer", ".", "Name", ".", "String", "(", ")", ",", "peer", ".", "NickName", ",", "peer", ".", "UID", ",", "peer", ".", "ShortID", ",", "peer", ".", "Version", ",", "connections", ",", "}", ")", "\n", "}", ")", "\n", "return", "slice", "\n", "}" ]
// makePeerStatusSlice takes a snapshot of the state of peers.
[ "makePeerStatusSlice", "takes", "a", "snapshot", "of", "the", "state", "of", "peers", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/status.go#L62-L90
test
weaveworks/mesh
status.go
makeUnicastRouteStatusSlice
func makeUnicastRouteStatusSlice(r *routes) []unicastRouteStatus { r.RLock() defer r.RUnlock() var slice []unicastRouteStatus for dest, via := range r.unicast { slice = append(slice, unicastRouteStatus{dest.String(), via.String()}) } return slice }
go
func makeUnicastRouteStatusSlice(r *routes) []unicastRouteStatus { r.RLock() defer r.RUnlock() var slice []unicastRouteStatus for dest, via := range r.unicast { slice = append(slice, unicastRouteStatus{dest.String(), via.String()}) } return slice }
[ "func", "makeUnicastRouteStatusSlice", "(", "r", "*", "routes", ")", "[", "]", "unicastRouteStatus", "{", "r", ".", "RLock", "(", ")", "\n", "defer", "r", ".", "RUnlock", "(", ")", "\n", "var", "slice", "[", "]", "unicastRouteStatus", "\n", "for", "dest", ",", "via", ":=", "range", "r", ".", "unicast", "{", "slice", "=", "append", "(", "slice", ",", "unicastRouteStatus", "{", "dest", ".", "String", "(", ")", ",", "via", ".", "String", "(", ")", "}", ")", "\n", "}", "\n", "return", "slice", "\n", "}" ]
// makeUnicastRouteStatusSlice takes a snapshot of the unicast routes in routes.
[ "makeUnicastRouteStatusSlice", "takes", "a", "snapshot", "of", "the", "unicast", "routes", "in", "routes", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/status.go#L116-L125
test
weaveworks/mesh
status.go
makeBroadcastRouteStatusSlice
func makeBroadcastRouteStatusSlice(r *routes) []broadcastRouteStatus { r.RLock() defer r.RUnlock() var slice []broadcastRouteStatus for source, via := range r.broadcast { var hops []string for _, hop := range via { hops = append(hops, hop.String()) } slice = append(slice, broadcastRouteStatus{source.String(), hops}) } return slice }
go
func makeBroadcastRouteStatusSlice(r *routes) []broadcastRouteStatus { r.RLock() defer r.RUnlock() var slice []broadcastRouteStatus for source, via := range r.broadcast { var hops []string for _, hop := range via { hops = append(hops, hop.String()) } slice = append(slice, broadcastRouteStatus{source.String(), hops}) } return slice }
[ "func", "makeBroadcastRouteStatusSlice", "(", "r", "*", "routes", ")", "[", "]", "broadcastRouteStatus", "{", "r", ".", "RLock", "(", ")", "\n", "defer", "r", ".", "RUnlock", "(", ")", "\n", "var", "slice", "[", "]", "broadcastRouteStatus", "\n", "for", "source", ",", "via", ":=", "range", "r", ".", "broadcast", "{", "var", "hops", "[", "]", "string", "\n", "for", "_", ",", "hop", ":=", "range", "via", "{", "hops", "=", "append", "(", "hops", ",", "hop", ".", "String", "(", ")", ")", "\n", "}", "\n", "slice", "=", "append", "(", "slice", ",", "broadcastRouteStatus", "{", "source", ".", "String", "(", ")", ",", "hops", "}", ")", "\n", "}", "\n", "return", "slice", "\n", "}" ]
// makeBroadcastRouteStatusSlice takes a snapshot of the broadcast routes in routes.
[ "makeBroadcastRouteStatusSlice", "takes", "a", "snapshot", "of", "the", "broadcast", "routes", "in", "routes", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/status.go#L134-L147
test
weaveworks/mesh
status.go
makeLocalConnectionStatusSlice
func makeLocalConnectionStatusSlice(cm *connectionMaker) []LocalConnectionStatus { resultChan := make(chan []LocalConnectionStatus) cm.actionChan <- func() bool { var slice []LocalConnectionStatus for conn := range cm.connections { state := "pending" if conn.isEstablished() { state = "established" } lc, _ := conn.(*LocalConnection) attrs := lc.OverlayConn.Attrs() name, ok := attrs["name"] if !ok { name = "none" } info := fmt.Sprintf("%-6v %v", name, conn.Remote()) if lc.router.usingPassword() { if lc.untrusted() { info = fmt.Sprintf("%-11v %v", "encrypted", info) if attrs != nil { attrs["encrypted"] = true } } else { info = fmt.Sprintf("%-11v %v", "unencrypted", info) } } slice = append(slice, LocalConnectionStatus{conn.remoteTCPAddress(), conn.isOutbound(), state, info, attrs}) } for address, target := range cm.targets { add := func(state, info string) { slice = append(slice, LocalConnectionStatus{address, true, state, info, nil}) } switch target.state { case targetWaiting: until := "never" if !target.tryAfter.IsZero() { until = target.tryAfter.String() } if target.lastError == nil { // shouldn't happen add("waiting", "until: "+until) } else { add("failed", target.lastError.Error()+", retry: "+until) } case targetAttempting: if target.lastError == nil { add("connecting", "") } else { add("retrying", target.lastError.Error()) } case targetConnected: case targetSuspended: } } resultChan <- slice return false } return <-resultChan }
go
func makeLocalConnectionStatusSlice(cm *connectionMaker) []LocalConnectionStatus { resultChan := make(chan []LocalConnectionStatus) cm.actionChan <- func() bool { var slice []LocalConnectionStatus for conn := range cm.connections { state := "pending" if conn.isEstablished() { state = "established" } lc, _ := conn.(*LocalConnection) attrs := lc.OverlayConn.Attrs() name, ok := attrs["name"] if !ok { name = "none" } info := fmt.Sprintf("%-6v %v", name, conn.Remote()) if lc.router.usingPassword() { if lc.untrusted() { info = fmt.Sprintf("%-11v %v", "encrypted", info) if attrs != nil { attrs["encrypted"] = true } } else { info = fmt.Sprintf("%-11v %v", "unencrypted", info) } } slice = append(slice, LocalConnectionStatus{conn.remoteTCPAddress(), conn.isOutbound(), state, info, attrs}) } for address, target := range cm.targets { add := func(state, info string) { slice = append(slice, LocalConnectionStatus{address, true, state, info, nil}) } switch target.state { case targetWaiting: until := "never" if !target.tryAfter.IsZero() { until = target.tryAfter.String() } if target.lastError == nil { // shouldn't happen add("waiting", "until: "+until) } else { add("failed", target.lastError.Error()+", retry: "+until) } case targetAttempting: if target.lastError == nil { add("connecting", "") } else { add("retrying", target.lastError.Error()) } case targetConnected: case targetSuspended: } } resultChan <- slice return false } return <-resultChan }
[ "func", "makeLocalConnectionStatusSlice", "(", "cm", "*", "connectionMaker", ")", "[", "]", "LocalConnectionStatus", "{", "resultChan", ":=", "make", "(", "chan", "[", "]", "LocalConnectionStatus", ")", "\n", "cm", ".", "actionChan", "<-", "func", "(", ")", "bool", "{", "var", "slice", "[", "]", "LocalConnectionStatus", "\n", "for", "conn", ":=", "range", "cm", ".", "connections", "{", "state", ":=", "\"pending\"", "\n", "if", "conn", ".", "isEstablished", "(", ")", "{", "state", "=", "\"established\"", "\n", "}", "\n", "lc", ",", "_", ":=", "conn", ".", "(", "*", "LocalConnection", ")", "\n", "attrs", ":=", "lc", ".", "OverlayConn", ".", "Attrs", "(", ")", "\n", "name", ",", "ok", ":=", "attrs", "[", "\"name\"", "]", "\n", "if", "!", "ok", "{", "name", "=", "\"none\"", "\n", "}", "\n", "info", ":=", "fmt", ".", "Sprintf", "(", "\"%-6v %v\"", ",", "name", ",", "conn", ".", "Remote", "(", ")", ")", "\n", "if", "lc", ".", "router", ".", "usingPassword", "(", ")", "{", "if", "lc", ".", "untrusted", "(", ")", "{", "info", "=", "fmt", ".", "Sprintf", "(", "\"%-11v %v\"", ",", "\"encrypted\"", ",", "info", ")", "\n", "if", "attrs", "!=", "nil", "{", "attrs", "[", "\"encrypted\"", "]", "=", "true", "\n", "}", "\n", "}", "else", "{", "info", "=", "fmt", ".", "Sprintf", "(", "\"%-11v %v\"", ",", "\"unencrypted\"", ",", "info", ")", "\n", "}", "\n", "}", "\n", "slice", "=", "append", "(", "slice", ",", "LocalConnectionStatus", "{", "conn", ".", "remoteTCPAddress", "(", ")", ",", "conn", ".", "isOutbound", "(", ")", ",", "state", ",", "info", ",", "attrs", "}", ")", "\n", "}", "\n", "for", "address", ",", "target", ":=", "range", "cm", ".", "targets", "{", "add", ":=", "func", "(", "state", ",", "info", "string", ")", "{", "slice", "=", "append", "(", "slice", ",", "LocalConnectionStatus", "{", "address", ",", "true", ",", "state", ",", "info", ",", "nil", "}", ")", "\n", "}", "\n", "switch", "target", ".", "state", "{", "case", "targetWaiting", ":", "until", ":=", "\"never\"", "\n", "if", "!", "target", ".", "tryAfter", ".", "IsZero", "(", ")", "{", "until", "=", "target", ".", "tryAfter", ".", "String", "(", ")", "\n", "}", "\n", "if", "target", ".", "lastError", "==", "nil", "{", "add", "(", "\"waiting\"", ",", "\"until: \"", "+", "until", ")", "\n", "}", "else", "{", "add", "(", "\"failed\"", ",", "target", ".", "lastError", ".", "Error", "(", ")", "+", "\", retry: \"", "+", "until", ")", "\n", "}", "\n", "case", "targetAttempting", ":", "if", "target", ".", "lastError", "==", "nil", "{", "add", "(", "\"connecting\"", ",", "\"\"", ")", "\n", "}", "else", "{", "add", "(", "\"retrying\"", ",", "target", ".", "lastError", ".", "Error", "(", ")", ")", "\n", "}", "\n", "case", "targetConnected", ":", "case", "targetSuspended", ":", "}", "\n", "}", "\n", "resultChan", "<-", "slice", "\n", "return", "false", "\n", "}", "\n", "return", "<-", "resultChan", "\n", "}" ]
// makeLocalConnectionStatusSlice takes a snapshot of the active local // connections in the ConnectionMaker.
[ "makeLocalConnectionStatusSlice", "takes", "a", "snapshot", "of", "the", "active", "local", "connections", "in", "the", "ConnectionMaker", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/status.go#L160-L217
test
weaveworks/mesh
status.go
makeTrustedSubnetsSlice
func makeTrustedSubnetsSlice(trustedSubnets []*net.IPNet) []string { trustedSubnetStrs := []string{} for _, trustedSubnet := range trustedSubnets { trustedSubnetStrs = append(trustedSubnetStrs, trustedSubnet.String()) } return trustedSubnetStrs }
go
func makeTrustedSubnetsSlice(trustedSubnets []*net.IPNet) []string { trustedSubnetStrs := []string{} for _, trustedSubnet := range trustedSubnets { trustedSubnetStrs = append(trustedSubnetStrs, trustedSubnet.String()) } return trustedSubnetStrs }
[ "func", "makeTrustedSubnetsSlice", "(", "trustedSubnets", "[", "]", "*", "net", ".", "IPNet", ")", "[", "]", "string", "{", "trustedSubnetStrs", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "trustedSubnet", ":=", "range", "trustedSubnets", "{", "trustedSubnetStrs", "=", "append", "(", "trustedSubnetStrs", ",", "trustedSubnet", ".", "String", "(", ")", ")", "\n", "}", "\n", "return", "trustedSubnetStrs", "\n", "}" ]
// makeTrustedSubnetsSlice makes a human-readable copy of the trustedSubnets.
[ "makeTrustedSubnetsSlice", "makes", "a", "human", "-", "readable", "copy", "of", "the", "trustedSubnets", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/status.go#L220-L226
test
weaveworks/mesh
_metcd/etcd_store.go
Range
func (s *etcdStore) Range(ctx context.Context, req *etcdserverpb.RangeRequest) (*etcdserverpb.RangeResponse, error) { ireq := etcdserverpb.InternalRaftRequest{ID: <-s.idgen, Range: req} msgc, errc, err := s.proposeInternalRaftRequest(ireq) if err != nil { return nil, err } select { case <-ctx.Done(): s.cancelInternalRaftRequest(ireq) return nil, ctx.Err() case msg := <-msgc: return msg.(*etcdserverpb.RangeResponse), nil case err := <-errc: return nil, err case <-s.quitc: return nil, errStopped } }
go
func (s *etcdStore) Range(ctx context.Context, req *etcdserverpb.RangeRequest) (*etcdserverpb.RangeResponse, error) { ireq := etcdserverpb.InternalRaftRequest{ID: <-s.idgen, Range: req} msgc, errc, err := s.proposeInternalRaftRequest(ireq) if err != nil { return nil, err } select { case <-ctx.Done(): s.cancelInternalRaftRequest(ireq) return nil, ctx.Err() case msg := <-msgc: return msg.(*etcdserverpb.RangeResponse), nil case err := <-errc: return nil, err case <-s.quitc: return nil, errStopped } }
[ "func", "(", "s", "*", "etcdStore", ")", "Range", "(", "ctx", "context", ".", "Context", ",", "req", "*", "etcdserverpb", ".", "RangeRequest", ")", "(", "*", "etcdserverpb", ".", "RangeResponse", ",", "error", ")", "{", "ireq", ":=", "etcdserverpb", ".", "InternalRaftRequest", "{", "ID", ":", "<-", "s", ".", "idgen", ",", "Range", ":", "req", "}", "\n", "msgc", ",", "errc", ",", "err", ":=", "s", ".", "proposeInternalRaftRequest", "(", "ireq", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "s", ".", "cancelInternalRaftRequest", "(", "ireq", ")", "\n", "return", "nil", ",", "ctx", ".", "Err", "(", ")", "\n", "case", "msg", ":=", "<-", "msgc", ":", "return", "msg", ".", "(", "*", "etcdserverpb", ".", "RangeResponse", ")", ",", "nil", "\n", "case", "err", ":=", "<-", "errc", ":", "return", "nil", ",", "err", "\n", "case", "<-", "s", ".", "quitc", ":", "return", "nil", ",", "errStopped", "\n", "}", "\n", "}" ]
// Range implements gRPC KVServer. // Range gets the keys in the range from the store.
[ "Range", "implements", "gRPC", "KVServer", ".", "Range", "gets", "the", "keys", "in", "the", "range", "from", "the", "store", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/_metcd/etcd_store.go#L94-L111
test
weaveworks/mesh
_metcd/etcd_store.go
Put
func (s *etcdStore) Put(ctx context.Context, req *etcdserverpb.PutRequest) (*etcdserverpb.PutResponse, error) { ireq := etcdserverpb.InternalRaftRequest{ID: <-s.idgen, Put: req} msgc, errc, err := s.proposeInternalRaftRequest(ireq) if err != nil { return nil, err } select { case <-ctx.Done(): s.cancelInternalRaftRequest(ireq) return nil, ctx.Err() case msg := <-msgc: return msg.(*etcdserverpb.PutResponse), nil case err := <-errc: return nil, err case <-s.quitc: return nil, errStopped } }
go
func (s *etcdStore) Put(ctx context.Context, req *etcdserverpb.PutRequest) (*etcdserverpb.PutResponse, error) { ireq := etcdserverpb.InternalRaftRequest{ID: <-s.idgen, Put: req} msgc, errc, err := s.proposeInternalRaftRequest(ireq) if err != nil { return nil, err } select { case <-ctx.Done(): s.cancelInternalRaftRequest(ireq) return nil, ctx.Err() case msg := <-msgc: return msg.(*etcdserverpb.PutResponse), nil case err := <-errc: return nil, err case <-s.quitc: return nil, errStopped } }
[ "func", "(", "s", "*", "etcdStore", ")", "Put", "(", "ctx", "context", ".", "Context", ",", "req", "*", "etcdserverpb", ".", "PutRequest", ")", "(", "*", "etcdserverpb", ".", "PutResponse", ",", "error", ")", "{", "ireq", ":=", "etcdserverpb", ".", "InternalRaftRequest", "{", "ID", ":", "<-", "s", ".", "idgen", ",", "Put", ":", "req", "}", "\n", "msgc", ",", "errc", ",", "err", ":=", "s", ".", "proposeInternalRaftRequest", "(", "ireq", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "s", ".", "cancelInternalRaftRequest", "(", "ireq", ")", "\n", "return", "nil", ",", "ctx", ".", "Err", "(", ")", "\n", "case", "msg", ":=", "<-", "msgc", ":", "return", "msg", ".", "(", "*", "etcdserverpb", ".", "PutResponse", ")", ",", "nil", "\n", "case", "err", ":=", "<-", "errc", ":", "return", "nil", ",", "err", "\n", "case", "<-", "s", ".", "quitc", ":", "return", "nil", ",", "errStopped", "\n", "}", "\n", "}" ]
// Put implements gRPC KVServer. // Put puts the given key into the store. // A put request increases the revision of the store, // and generates one event in the event history.
[ "Put", "implements", "gRPC", "KVServer", ".", "Put", "puts", "the", "given", "key", "into", "the", "store", ".", "A", "put", "request", "increases", "the", "revision", "of", "the", "store", "and", "generates", "one", "event", "in", "the", "event", "history", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/_metcd/etcd_store.go#L117-L134
test
weaveworks/mesh
_metcd/etcd_store.go
DeleteRange
func (s *etcdStore) DeleteRange(ctx context.Context, req *etcdserverpb.DeleteRangeRequest) (*etcdserverpb.DeleteRangeResponse, error) { ireq := etcdserverpb.InternalRaftRequest{ID: <-s.idgen, DeleteRange: req} msgc, errc, err := s.proposeInternalRaftRequest(ireq) if err != nil { return nil, err } select { case <-ctx.Done(): s.cancelInternalRaftRequest(ireq) return nil, ctx.Err() case msg := <-msgc: return msg.(*etcdserverpb.DeleteRangeResponse), nil case err := <-errc: return nil, err case <-s.quitc: return nil, errStopped } }
go
func (s *etcdStore) DeleteRange(ctx context.Context, req *etcdserverpb.DeleteRangeRequest) (*etcdserverpb.DeleteRangeResponse, error) { ireq := etcdserverpb.InternalRaftRequest{ID: <-s.idgen, DeleteRange: req} msgc, errc, err := s.proposeInternalRaftRequest(ireq) if err != nil { return nil, err } select { case <-ctx.Done(): s.cancelInternalRaftRequest(ireq) return nil, ctx.Err() case msg := <-msgc: return msg.(*etcdserverpb.DeleteRangeResponse), nil case err := <-errc: return nil, err case <-s.quitc: return nil, errStopped } }
[ "func", "(", "s", "*", "etcdStore", ")", "DeleteRange", "(", "ctx", "context", ".", "Context", ",", "req", "*", "etcdserverpb", ".", "DeleteRangeRequest", ")", "(", "*", "etcdserverpb", ".", "DeleteRangeResponse", ",", "error", ")", "{", "ireq", ":=", "etcdserverpb", ".", "InternalRaftRequest", "{", "ID", ":", "<-", "s", ".", "idgen", ",", "DeleteRange", ":", "req", "}", "\n", "msgc", ",", "errc", ",", "err", ":=", "s", ".", "proposeInternalRaftRequest", "(", "ireq", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "s", ".", "cancelInternalRaftRequest", "(", "ireq", ")", "\n", "return", "nil", ",", "ctx", ".", "Err", "(", ")", "\n", "case", "msg", ":=", "<-", "msgc", ":", "return", "msg", ".", "(", "*", "etcdserverpb", ".", "DeleteRangeResponse", ")", ",", "nil", "\n", "case", "err", ":=", "<-", "errc", ":", "return", "nil", ",", "err", "\n", "case", "<-", "s", ".", "quitc", ":", "return", "nil", ",", "errStopped", "\n", "}", "\n", "}" ]
// Delete implements gRPC KVServer. // Delete deletes the given range from the store. // A delete request increase the revision of the store, // and generates one event in the event history.
[ "Delete", "implements", "gRPC", "KVServer", ".", "Delete", "deletes", "the", "given", "range", "from", "the", "store", ".", "A", "delete", "request", "increase", "the", "revision", "of", "the", "store", "and", "generates", "one", "event", "in", "the", "event", "history", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/_metcd/etcd_store.go#L140-L157
test
weaveworks/mesh
_metcd/etcd_store.go
Txn
func (s *etcdStore) Txn(ctx context.Context, req *etcdserverpb.TxnRequest) (*etcdserverpb.TxnResponse, error) { ireq := etcdserverpb.InternalRaftRequest{ID: <-s.idgen, Txn: req} msgc, errc, err := s.proposeInternalRaftRequest(ireq) if err != nil { return nil, err } select { case <-ctx.Done(): s.cancelInternalRaftRequest(ireq) return nil, ctx.Err() case msg := <-msgc: return msg.(*etcdserverpb.TxnResponse), nil case err := <-errc: return nil, err case <-s.quitc: return nil, errStopped } }
go
func (s *etcdStore) Txn(ctx context.Context, req *etcdserverpb.TxnRequest) (*etcdserverpb.TxnResponse, error) { ireq := etcdserverpb.InternalRaftRequest{ID: <-s.idgen, Txn: req} msgc, errc, err := s.proposeInternalRaftRequest(ireq) if err != nil { return nil, err } select { case <-ctx.Done(): s.cancelInternalRaftRequest(ireq) return nil, ctx.Err() case msg := <-msgc: return msg.(*etcdserverpb.TxnResponse), nil case err := <-errc: return nil, err case <-s.quitc: return nil, errStopped } }
[ "func", "(", "s", "*", "etcdStore", ")", "Txn", "(", "ctx", "context", ".", "Context", ",", "req", "*", "etcdserverpb", ".", "TxnRequest", ")", "(", "*", "etcdserverpb", ".", "TxnResponse", ",", "error", ")", "{", "ireq", ":=", "etcdserverpb", ".", "InternalRaftRequest", "{", "ID", ":", "<-", "s", ".", "idgen", ",", "Txn", ":", "req", "}", "\n", "msgc", ",", "errc", ",", "err", ":=", "s", ".", "proposeInternalRaftRequest", "(", "ireq", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "s", ".", "cancelInternalRaftRequest", "(", "ireq", ")", "\n", "return", "nil", ",", "ctx", ".", "Err", "(", ")", "\n", "case", "msg", ":=", "<-", "msgc", ":", "return", "msg", ".", "(", "*", "etcdserverpb", ".", "TxnResponse", ")", ",", "nil", "\n", "case", "err", ":=", "<-", "errc", ":", "return", "nil", ",", "err", "\n", "case", "<-", "s", ".", "quitc", ":", "return", "nil", ",", "errStopped", "\n", "}", "\n", "}" ]
// Txn implements gRPC KVServer. // Txn processes all the requests in one transaction. // A txn request increases the revision of the store, // and generates events with the same revision in the event history. // It is not allowed to modify the same key several times within one txn.
[ "Txn", "implements", "gRPC", "KVServer", ".", "Txn", "processes", "all", "the", "requests", "in", "one", "transaction", ".", "A", "txn", "request", "increases", "the", "revision", "of", "the", "store", "and", "generates", "events", "with", "the", "same", "revision", "in", "the", "event", "history", ".", "It", "is", "not", "allowed", "to", "modify", "the", "same", "key", "several", "times", "within", "one", "txn", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/_metcd/etcd_store.go#L164-L181
test
weaveworks/mesh
_metcd/etcd_store.go
Compact
func (s *etcdStore) Compact(ctx context.Context, req *etcdserverpb.CompactionRequest) (*etcdserverpb.CompactionResponse, error) { // We don't have snapshotting yet, so compact just puts us in a bad state. // TODO(pb): fix this when we implement snapshotting. return nil, errors.New("not implemented") }
go
func (s *etcdStore) Compact(ctx context.Context, req *etcdserverpb.CompactionRequest) (*etcdserverpb.CompactionResponse, error) { // We don't have snapshotting yet, so compact just puts us in a bad state. // TODO(pb): fix this when we implement snapshotting. return nil, errors.New("not implemented") }
[ "func", "(", "s", "*", "etcdStore", ")", "Compact", "(", "ctx", "context", ".", "Context", ",", "req", "*", "etcdserverpb", ".", "CompactionRequest", ")", "(", "*", "etcdserverpb", ".", "CompactionResponse", ",", "error", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"not implemented\"", ")", "\n", "}" ]
// Compact implements gRPC KVServer. // Compact compacts the event history in s. User should compact the // event history periodically, or it will grow infinitely.
[ "Compact", "implements", "gRPC", "KVServer", ".", "Compact", "compacts", "the", "event", "history", "in", "s", ".", "User", "should", "compact", "the", "event", "history", "periodically", "or", "it", "will", "grow", "infinitely", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/_metcd/etcd_store.go#L186-L190
test
weaveworks/mesh
_metcd/etcd_store.go
proposeInternalRaftRequest
func (s *etcdStore) proposeInternalRaftRequest(req etcdserverpb.InternalRaftRequest) (<-chan proto.Message, <-chan error, error) { data, err := req.Marshal() if err != nil { return nil, nil, err } if len(data) > maxRequestBytes { return nil, nil, errTooBig } msgc, errc, err := s.registerPending(req.ID) if err != nil { return nil, nil, err } s.proposalc <- data return msgc, errc, nil }
go
func (s *etcdStore) proposeInternalRaftRequest(req etcdserverpb.InternalRaftRequest) (<-chan proto.Message, <-chan error, error) { data, err := req.Marshal() if err != nil { return nil, nil, err } if len(data) > maxRequestBytes { return nil, nil, errTooBig } msgc, errc, err := s.registerPending(req.ID) if err != nil { return nil, nil, err } s.proposalc <- data return msgc, errc, nil }
[ "func", "(", "s", "*", "etcdStore", ")", "proposeInternalRaftRequest", "(", "req", "etcdserverpb", ".", "InternalRaftRequest", ")", "(", "<-", "chan", "proto", ".", "Message", ",", "<-", "chan", "error", ",", "error", ")", "{", "data", ",", "err", ":=", "req", ".", "Marshal", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "data", ")", ">", "maxRequestBytes", "{", "return", "nil", ",", "nil", ",", "errTooBig", "\n", "}", "\n", "msgc", ",", "errc", ",", "err", ":=", "s", ".", "registerPending", "(", "req", ".", "ID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "s", ".", "proposalc", "<-", "data", "\n", "return", "msgc", ",", "errc", ",", "nil", "\n", "}" ]
// From public API method to proposalc.
[ "From", "public", "API", "method", "to", "proposalc", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/_metcd/etcd_store.go#L333-L347
test
weaveworks/mesh
_metcd/etcd_store.go
applyCompare
func applyCompare(kv mvcc.KV, c *etcdserverpb.Compare) (int64, bool) { ckvs, rev, err := kv.Range(c.Key, nil, 1, 0) if err != nil { if err == mvcc.ErrTxnIDMismatch { panic("unexpected txn ID mismatch error") } return rev, false } var ckv mvccpb.KeyValue if len(ckvs) != 0 { ckv = ckvs[0] } else { // Use the zero value of ckv normally. However... if c.Target == etcdserverpb.Compare_VALUE { // Always fail if we're comparing a value on a key that doesn't exist. // We can treat non-existence as the empty set explicitly, such that // even a key with a value of length 0 bytes is still a real key // that was written that way return rev, false } } // -1 is less, 0 is equal, 1 is greater var result int switch c.Target { case etcdserverpb.Compare_VALUE: tv, _ := c.TargetUnion.(*etcdserverpb.Compare_Value) if tv != nil { result = bytes.Compare(ckv.Value, tv.Value) } case etcdserverpb.Compare_CREATE: tv, _ := c.TargetUnion.(*etcdserverpb.Compare_CreateRevision) if tv != nil { result = compareInt64(ckv.CreateRevision, tv.CreateRevision) } case etcdserverpb.Compare_MOD: tv, _ := c.TargetUnion.(*etcdserverpb.Compare_ModRevision) if tv != nil { result = compareInt64(ckv.ModRevision, tv.ModRevision) } case etcdserverpb.Compare_VERSION: tv, _ := c.TargetUnion.(*etcdserverpb.Compare_Version) if tv != nil { result = compareInt64(ckv.Version, tv.Version) } } switch c.Result { case etcdserverpb.Compare_EQUAL: if result != 0 { return rev, false } case etcdserverpb.Compare_GREATER: if result != 1 { return rev, false } case etcdserverpb.Compare_LESS: if result != -1 { return rev, false } } return rev, true }
go
func applyCompare(kv mvcc.KV, c *etcdserverpb.Compare) (int64, bool) { ckvs, rev, err := kv.Range(c.Key, nil, 1, 0) if err != nil { if err == mvcc.ErrTxnIDMismatch { panic("unexpected txn ID mismatch error") } return rev, false } var ckv mvccpb.KeyValue if len(ckvs) != 0 { ckv = ckvs[0] } else { // Use the zero value of ckv normally. However... if c.Target == etcdserverpb.Compare_VALUE { // Always fail if we're comparing a value on a key that doesn't exist. // We can treat non-existence as the empty set explicitly, such that // even a key with a value of length 0 bytes is still a real key // that was written that way return rev, false } } // -1 is less, 0 is equal, 1 is greater var result int switch c.Target { case etcdserverpb.Compare_VALUE: tv, _ := c.TargetUnion.(*etcdserverpb.Compare_Value) if tv != nil { result = bytes.Compare(ckv.Value, tv.Value) } case etcdserverpb.Compare_CREATE: tv, _ := c.TargetUnion.(*etcdserverpb.Compare_CreateRevision) if tv != nil { result = compareInt64(ckv.CreateRevision, tv.CreateRevision) } case etcdserverpb.Compare_MOD: tv, _ := c.TargetUnion.(*etcdserverpb.Compare_ModRevision) if tv != nil { result = compareInt64(ckv.ModRevision, tv.ModRevision) } case etcdserverpb.Compare_VERSION: tv, _ := c.TargetUnion.(*etcdserverpb.Compare_Version) if tv != nil { result = compareInt64(ckv.Version, tv.Version) } } switch c.Result { case etcdserverpb.Compare_EQUAL: if result != 0 { return rev, false } case etcdserverpb.Compare_GREATER: if result != 1 { return rev, false } case etcdserverpb.Compare_LESS: if result != -1 { return rev, false } } return rev, true }
[ "func", "applyCompare", "(", "kv", "mvcc", ".", "KV", ",", "c", "*", "etcdserverpb", ".", "Compare", ")", "(", "int64", ",", "bool", ")", "{", "ckvs", ",", "rev", ",", "err", ":=", "kv", ".", "Range", "(", "c", ".", "Key", ",", "nil", ",", "1", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "mvcc", ".", "ErrTxnIDMismatch", "{", "panic", "(", "\"unexpected txn ID mismatch error\"", ")", "\n", "}", "\n", "return", "rev", ",", "false", "\n", "}", "\n", "var", "ckv", "mvccpb", ".", "KeyValue", "\n", "if", "len", "(", "ckvs", ")", "!=", "0", "{", "ckv", "=", "ckvs", "[", "0", "]", "\n", "}", "else", "{", "if", "c", ".", "Target", "==", "etcdserverpb", ".", "Compare_VALUE", "{", "return", "rev", ",", "false", "\n", "}", "\n", "}", "\n", "var", "result", "int", "\n", "switch", "c", ".", "Target", "{", "case", "etcdserverpb", ".", "Compare_VALUE", ":", "tv", ",", "_", ":=", "c", ".", "TargetUnion", ".", "(", "*", "etcdserverpb", ".", "Compare_Value", ")", "\n", "if", "tv", "!=", "nil", "{", "result", "=", "bytes", ".", "Compare", "(", "ckv", ".", "Value", ",", "tv", ".", "Value", ")", "\n", "}", "\n", "case", "etcdserverpb", ".", "Compare_CREATE", ":", "tv", ",", "_", ":=", "c", ".", "TargetUnion", ".", "(", "*", "etcdserverpb", ".", "Compare_CreateRevision", ")", "\n", "if", "tv", "!=", "nil", "{", "result", "=", "compareInt64", "(", "ckv", ".", "CreateRevision", ",", "tv", ".", "CreateRevision", ")", "\n", "}", "\n", "case", "etcdserverpb", ".", "Compare_MOD", ":", "tv", ",", "_", ":=", "c", ".", "TargetUnion", ".", "(", "*", "etcdserverpb", ".", "Compare_ModRevision", ")", "\n", "if", "tv", "!=", "nil", "{", "result", "=", "compareInt64", "(", "ckv", ".", "ModRevision", ",", "tv", ".", "ModRevision", ")", "\n", "}", "\n", "case", "etcdserverpb", ".", "Compare_VERSION", ":", "tv", ",", "_", ":=", "c", ".", "TargetUnion", ".", "(", "*", "etcdserverpb", ".", "Compare_Version", ")", "\n", "if", "tv", "!=", "nil", "{", "result", "=", "compareInt64", "(", "ckv", ".", "Version", ",", "tv", ".", "Version", ")", "\n", "}", "\n", "}", "\n", "switch", "c", ".", "Result", "{", "case", "etcdserverpb", ".", "Compare_EQUAL", ":", "if", "result", "!=", "0", "{", "return", "rev", ",", "false", "\n", "}", "\n", "case", "etcdserverpb", ".", "Compare_GREATER", ":", "if", "result", "!=", "1", "{", "return", "rev", ",", "false", "\n", "}", "\n", "case", "etcdserverpb", ".", "Compare_LESS", ":", "if", "result", "!=", "-", "1", "{", "return", "rev", ",", "false", "\n", "}", "\n", "}", "\n", "return", "rev", ",", "true", "\n", "}" ]
// applyCompare applies the compare request. // It returns the revision at which the comparison happens. If the comparison // succeeds, the it returns true. Otherwise it returns false.
[ "applyCompare", "applies", "the", "compare", "request", ".", "It", "returns", "the", "revision", "at", "which", "the", "comparison", "happens", ".", "If", "the", "comparison", "succeeds", "the", "it", "returns", "true", ".", "Otherwise", "it", "returns", "false", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/_metcd/etcd_store.go#L712-L775
test
weaveworks/mesh
peers.go
Descriptions
func (peers *Peers) Descriptions() []PeerDescription { peers.RLock() defer peers.RUnlock() descriptions := make([]PeerDescription, 0, len(peers.byName)) for _, peer := range peers.byName { descriptions = append(descriptions, PeerDescription{ Name: peer.Name, NickName: peer.peerSummary.NickName, UID: peer.UID, Self: peer.Name == peers.ourself.Name, NumConnections: len(peer.connections), }) } return descriptions }
go
func (peers *Peers) Descriptions() []PeerDescription { peers.RLock() defer peers.RUnlock() descriptions := make([]PeerDescription, 0, len(peers.byName)) for _, peer := range peers.byName { descriptions = append(descriptions, PeerDescription{ Name: peer.Name, NickName: peer.peerSummary.NickName, UID: peer.UID, Self: peer.Name == peers.ourself.Name, NumConnections: len(peer.connections), }) } return descriptions }
[ "func", "(", "peers", "*", "Peers", ")", "Descriptions", "(", ")", "[", "]", "PeerDescription", "{", "peers", ".", "RLock", "(", ")", "\n", "defer", "peers", ".", "RUnlock", "(", ")", "\n", "descriptions", ":=", "make", "(", "[", "]", "PeerDescription", ",", "0", ",", "len", "(", "peers", ".", "byName", ")", ")", "\n", "for", "_", ",", "peer", ":=", "range", "peers", ".", "byName", "{", "descriptions", "=", "append", "(", "descriptions", ",", "PeerDescription", "{", "Name", ":", "peer", ".", "Name", ",", "NickName", ":", "peer", ".", "peerSummary", ".", "NickName", ",", "UID", ":", "peer", ".", "UID", ",", "Self", ":", "peer", ".", "Name", "==", "peers", ".", "ourself", ".", "Name", ",", "NumConnections", ":", "len", "(", "peer", ".", "connections", ")", ",", "}", ")", "\n", "}", "\n", "return", "descriptions", "\n", "}" ]
// Descriptions returns descriptions for all known peers.
[ "Descriptions", "returns", "descriptions", "for", "all", "known", "peers", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peers.go#L69-L83
test
weaveworks/mesh
peers.go
OnGC
func (peers *Peers) OnGC(callback func(*Peer)) { peers.Lock() defer peers.Unlock() // Although the array underlying peers.onGC might be accessed // without holding the lock in unlockAndNotify, we don't // support removing callbacks, so a simple append here is // safe. peers.onGC = append(peers.onGC, callback) }
go
func (peers *Peers) OnGC(callback func(*Peer)) { peers.Lock() defer peers.Unlock() // Although the array underlying peers.onGC might be accessed // without holding the lock in unlockAndNotify, we don't // support removing callbacks, so a simple append here is // safe. peers.onGC = append(peers.onGC, callback) }
[ "func", "(", "peers", "*", "Peers", ")", "OnGC", "(", "callback", "func", "(", "*", "Peer", ")", ")", "{", "peers", ".", "Lock", "(", ")", "\n", "defer", "peers", ".", "Unlock", "(", ")", "\n", "peers", ".", "onGC", "=", "append", "(", "peers", ".", "onGC", ",", "callback", ")", "\n", "}" ]
// OnGC adds a new function to be set of functions that will be executed on // all subsequent GC runs, receiving the GC'd peer.
[ "OnGC", "adds", "a", "new", "function", "to", "be", "set", "of", "functions", "that", "will", "be", "executed", "on", "all", "subsequent", "GC", "runs", "receiving", "the", "GC", "d", "peer", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peers.go#L87-L96
test
weaveworks/mesh
peers.go
OnInvalidateShortIDs
func (peers *Peers) OnInvalidateShortIDs(callback func()) { peers.Lock() defer peers.Unlock() // Safe, as in OnGC peers.onInvalidateShortIDs = append(peers.onInvalidateShortIDs, callback) }
go
func (peers *Peers) OnInvalidateShortIDs(callback func()) { peers.Lock() defer peers.Unlock() // Safe, as in OnGC peers.onInvalidateShortIDs = append(peers.onInvalidateShortIDs, callback) }
[ "func", "(", "peers", "*", "Peers", ")", "OnInvalidateShortIDs", "(", "callback", "func", "(", ")", ")", "{", "peers", ".", "Lock", "(", ")", "\n", "defer", "peers", ".", "Unlock", "(", ")", "\n", "peers", ".", "onInvalidateShortIDs", "=", "append", "(", "peers", ".", "onInvalidateShortIDs", ",", "callback", ")", "\n", "}" ]
// OnInvalidateShortIDs adds a new function to a set of functions that will be // executed on all subsequent GC runs, when the mapping from short IDs to // peers has changed.
[ "OnInvalidateShortIDs", "adds", "a", "new", "function", "to", "a", "set", "of", "functions", "that", "will", "be", "executed", "on", "all", "subsequent", "GC", "runs", "when", "the", "mapping", "from", "short", "IDs", "to", "peers", "has", "changed", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peers.go#L101-L107
test
weaveworks/mesh
peers.go
chooseShortID
func (peers *Peers) chooseShortID() (PeerShortID, bool) { rng := rand.New(rand.NewSource(int64(randUint64()))) // First, just try picking some short IDs at random, and // seeing if they are available: for i := 0; i < 10; i++ { shortID := PeerShortID(rng.Intn(1 << peerShortIDBits)) if peers.byShortID[shortID].peer == nil { return shortID, true } } // Looks like most short IDs are used. So count the number of // unused ones, and pick one at random. available := int(1 << peerShortIDBits) for _, entry := range peers.byShortID { if entry.peer != nil { available-- } } if available == 0 { // All short IDs are used. return 0, false } n := rng.Intn(available) var i PeerShortID for { if peers.byShortID[i].peer == nil { if n == 0 { return i, true } n-- } i++ } }
go
func (peers *Peers) chooseShortID() (PeerShortID, bool) { rng := rand.New(rand.NewSource(int64(randUint64()))) // First, just try picking some short IDs at random, and // seeing if they are available: for i := 0; i < 10; i++ { shortID := PeerShortID(rng.Intn(1 << peerShortIDBits)) if peers.byShortID[shortID].peer == nil { return shortID, true } } // Looks like most short IDs are used. So count the number of // unused ones, and pick one at random. available := int(1 << peerShortIDBits) for _, entry := range peers.byShortID { if entry.peer != nil { available-- } } if available == 0 { // All short IDs are used. return 0, false } n := rng.Intn(available) var i PeerShortID for { if peers.byShortID[i].peer == nil { if n == 0 { return i, true } n-- } i++ } }
[ "func", "(", "peers", "*", "Peers", ")", "chooseShortID", "(", ")", "(", "PeerShortID", ",", "bool", ")", "{", "rng", ":=", "rand", ".", "New", "(", "rand", ".", "NewSource", "(", "int64", "(", "randUint64", "(", ")", ")", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "10", ";", "i", "++", "{", "shortID", ":=", "PeerShortID", "(", "rng", ".", "Intn", "(", "1", "<<", "peerShortIDBits", ")", ")", "\n", "if", "peers", ".", "byShortID", "[", "shortID", "]", ".", "peer", "==", "nil", "{", "return", "shortID", ",", "true", "\n", "}", "\n", "}", "\n", "available", ":=", "int", "(", "1", "<<", "peerShortIDBits", ")", "\n", "for", "_", ",", "entry", ":=", "range", "peers", ".", "byShortID", "{", "if", "entry", ".", "peer", "!=", "nil", "{", "available", "--", "\n", "}", "\n", "}", "\n", "if", "available", "==", "0", "{", "return", "0", ",", "false", "\n", "}", "\n", "n", ":=", "rng", ".", "Intn", "(", "available", ")", "\n", "var", "i", "PeerShortID", "\n", "for", "{", "if", "peers", ".", "byShortID", "[", "i", "]", ".", "peer", "==", "nil", "{", "if", "n", "==", "0", "{", "return", "i", ",", "true", "\n", "}", "\n", "n", "--", "\n", "}", "\n", "i", "++", "\n", "}", "\n", "}" ]
// Choose an available short ID at random.
[ "Choose", "an", "available", "short", "ID", "at", "random", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peers.go#L239-L278
test
weaveworks/mesh
peers.go
fetchWithDefault
func (peers *Peers) fetchWithDefault(peer *Peer) *Peer { peers.Lock() var pending peersPendingNotifications defer peers.unlockAndNotify(&pending) if existingPeer, found := peers.byName[peer.Name]; found { existingPeer.localRefCount++ return existingPeer } peers.byName[peer.Name] = peer peers.addByShortID(peer, &pending) peer.localRefCount++ return peer }
go
func (peers *Peers) fetchWithDefault(peer *Peer) *Peer { peers.Lock() var pending peersPendingNotifications defer peers.unlockAndNotify(&pending) if existingPeer, found := peers.byName[peer.Name]; found { existingPeer.localRefCount++ return existingPeer } peers.byName[peer.Name] = peer peers.addByShortID(peer, &pending) peer.localRefCount++ return peer }
[ "func", "(", "peers", "*", "Peers", ")", "fetchWithDefault", "(", "peer", "*", "Peer", ")", "*", "Peer", "{", "peers", ".", "Lock", "(", ")", "\n", "var", "pending", "peersPendingNotifications", "\n", "defer", "peers", ".", "unlockAndNotify", "(", "&", "pending", ")", "\n", "if", "existingPeer", ",", "found", ":=", "peers", ".", "byName", "[", "peer", ".", "Name", "]", ";", "found", "{", "existingPeer", ".", "localRefCount", "++", "\n", "return", "existingPeer", "\n", "}", "\n", "peers", ".", "byName", "[", "peer", ".", "Name", "]", "=", "peer", "\n", "peers", ".", "addByShortID", "(", "peer", ",", "&", "pending", ")", "\n", "peer", ".", "localRefCount", "++", "\n", "return", "peer", "\n", "}" ]
// fetchWithDefault will use reference fields of the passed peer object to // look up and return an existing, matching peer. If no matching peer is // found, the passed peer is saved and returned.
[ "fetchWithDefault", "will", "use", "reference", "fields", "of", "the", "passed", "peer", "object", "to", "look", "up", "and", "return", "an", "existing", "matching", "peer", ".", "If", "no", "matching", "peer", "is", "found", "the", "passed", "peer", "is", "saved", "and", "returned", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peers.go#L283-L297
test
weaveworks/mesh
peers.go
Fetch
func (peers *Peers) Fetch(name PeerName) *Peer { peers.RLock() defer peers.RUnlock() return peers.byName[name] }
go
func (peers *Peers) Fetch(name PeerName) *Peer { peers.RLock() defer peers.RUnlock() return peers.byName[name] }
[ "func", "(", "peers", "*", "Peers", ")", "Fetch", "(", "name", "PeerName", ")", "*", "Peer", "{", "peers", ".", "RLock", "(", ")", "\n", "defer", "peers", ".", "RUnlock", "(", ")", "\n", "return", "peers", ".", "byName", "[", "name", "]", "\n", "}" ]
// Fetch returns a peer matching the passed name, without incrementing its // refcount. If no matching peer is found, Fetch returns nil.
[ "Fetch", "returns", "a", "peer", "matching", "the", "passed", "name", "without", "incrementing", "its", "refcount", ".", "If", "no", "matching", "peer", "is", "found", "Fetch", "returns", "nil", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peers.go#L301-L305
test
weaveworks/mesh
peers.go
fetchAndAddRef
func (peers *Peers) fetchAndAddRef(name PeerName) *Peer { peers.Lock() defer peers.Unlock() peer := peers.byName[name] if peer != nil { peer.localRefCount++ } return peer }
go
func (peers *Peers) fetchAndAddRef(name PeerName) *Peer { peers.Lock() defer peers.Unlock() peer := peers.byName[name] if peer != nil { peer.localRefCount++ } return peer }
[ "func", "(", "peers", "*", "Peers", ")", "fetchAndAddRef", "(", "name", "PeerName", ")", "*", "Peer", "{", "peers", ".", "Lock", "(", ")", "\n", "defer", "peers", ".", "Unlock", "(", ")", "\n", "peer", ":=", "peers", ".", "byName", "[", "name", "]", "\n", "if", "peer", "!=", "nil", "{", "peer", ".", "localRefCount", "++", "\n", "}", "\n", "return", "peer", "\n", "}" ]
// Like fetch, but increments local refcount.
[ "Like", "fetch", "but", "increments", "local", "refcount", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peers.go#L308-L316
test
weaveworks/mesh
peers.go
FetchByShortID
func (peers *Peers) FetchByShortID(shortID PeerShortID) *Peer { peers.RLock() defer peers.RUnlock() return peers.byShortID[shortID].peer }
go
func (peers *Peers) FetchByShortID(shortID PeerShortID) *Peer { peers.RLock() defer peers.RUnlock() return peers.byShortID[shortID].peer }
[ "func", "(", "peers", "*", "Peers", ")", "FetchByShortID", "(", "shortID", "PeerShortID", ")", "*", "Peer", "{", "peers", ".", "RLock", "(", ")", "\n", "defer", "peers", ".", "RUnlock", "(", ")", "\n", "return", "peers", ".", "byShortID", "[", "shortID", "]", ".", "peer", "\n", "}" ]
// FetchByShortID returns a peer matching the passed short ID. // If no matching peer is found, FetchByShortID returns nil.
[ "FetchByShortID", "returns", "a", "peer", "matching", "the", "passed", "short", "ID", ".", "If", "no", "matching", "peer", "is", "found", "FetchByShortID", "returns", "nil", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peers.go#L320-L324
test
weaveworks/mesh
peers.go
GarbageCollect
func (peers *Peers) GarbageCollect() { peers.Lock() var pending peersPendingNotifications defer peers.unlockAndNotify(&pending) peers.garbageCollect(&pending) }
go
func (peers *Peers) GarbageCollect() { peers.Lock() var pending peersPendingNotifications defer peers.unlockAndNotify(&pending) peers.garbageCollect(&pending) }
[ "func", "(", "peers", "*", "Peers", ")", "GarbageCollect", "(", ")", "{", "peers", ".", "Lock", "(", ")", "\n", "var", "pending", "peersPendingNotifications", "\n", "defer", "peers", ".", "unlockAndNotify", "(", "&", "pending", ")", "\n", "peers", ".", "garbageCollect", "(", "&", "pending", ")", "\n", "}" ]
// GarbageCollect takes a lock, triggers a GC, and invokes the accumulated GC // callbacks.
[ "GarbageCollect", "takes", "a", "lock", "triggers", "a", "GC", "and", "invokes", "the", "accumulated", "GC", "callbacks", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peers.go#L409-L415
test
weaveworks/mesh
routes.go
newRoutes
func newRoutes(ourself *localPeer, peers *Peers) *routes { recalculate := make(chan *struct{}, 1) wait := make(chan chan struct{}) action := make(chan func()) r := &routes{ ourself: ourself, peers: peers, unicast: unicastRoutes{ourself.Name: UnknownPeerName}, unicastAll: unicastRoutes{ourself.Name: UnknownPeerName}, broadcast: broadcastRoutes{ourself.Name: []PeerName{}}, broadcastAll: broadcastRoutes{ourself.Name: []PeerName{}}, recalc: recalculate, wait: wait, action: action, } go r.run(recalculate, wait, action) return r }
go
func newRoutes(ourself *localPeer, peers *Peers) *routes { recalculate := make(chan *struct{}, 1) wait := make(chan chan struct{}) action := make(chan func()) r := &routes{ ourself: ourself, peers: peers, unicast: unicastRoutes{ourself.Name: UnknownPeerName}, unicastAll: unicastRoutes{ourself.Name: UnknownPeerName}, broadcast: broadcastRoutes{ourself.Name: []PeerName{}}, broadcastAll: broadcastRoutes{ourself.Name: []PeerName{}}, recalc: recalculate, wait: wait, action: action, } go r.run(recalculate, wait, action) return r }
[ "func", "newRoutes", "(", "ourself", "*", "localPeer", ",", "peers", "*", "Peers", ")", "*", "routes", "{", "recalculate", ":=", "make", "(", "chan", "*", "struct", "{", "}", ",", "1", ")", "\n", "wait", ":=", "make", "(", "chan", "chan", "struct", "{", "}", ")", "\n", "action", ":=", "make", "(", "chan", "func", "(", ")", ")", "\n", "r", ":=", "&", "routes", "{", "ourself", ":", "ourself", ",", "peers", ":", "peers", ",", "unicast", ":", "unicastRoutes", "{", "ourself", ".", "Name", ":", "UnknownPeerName", "}", ",", "unicastAll", ":", "unicastRoutes", "{", "ourself", ".", "Name", ":", "UnknownPeerName", "}", ",", "broadcast", ":", "broadcastRoutes", "{", "ourself", ".", "Name", ":", "[", "]", "PeerName", "{", "}", "}", ",", "broadcastAll", ":", "broadcastRoutes", "{", "ourself", ".", "Name", ":", "[", "]", "PeerName", "{", "}", "}", ",", "recalc", ":", "recalculate", ",", "wait", ":", "wait", ",", "action", ":", "action", ",", "}", "\n", "go", "r", ".", "run", "(", "recalculate", ",", "wait", ",", "action", ")", "\n", "return", "r", "\n", "}" ]
// newRoutes returns a usable Routes based on the LocalPeer and existing Peers.
[ "newRoutes", "returns", "a", "usable", "Routes", "based", "on", "the", "LocalPeer", "and", "existing", "Peers", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/routes.go#L29-L46
test
weaveworks/mesh
routes.go
OnChange
func (r *routes) OnChange(callback func()) { r.Lock() defer r.Unlock() r.onChange = append(r.onChange, callback) }
go
func (r *routes) OnChange(callback func()) { r.Lock() defer r.Unlock() r.onChange = append(r.onChange, callback) }
[ "func", "(", "r", "*", "routes", ")", "OnChange", "(", "callback", "func", "(", ")", ")", "{", "r", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "Unlock", "(", ")", "\n", "r", ".", "onChange", "=", "append", "(", "r", ".", "onChange", ",", "callback", ")", "\n", "}" ]
// OnChange appends callback to the functions that will be called whenever the // routes are recalculated.
[ "OnChange", "appends", "callback", "to", "the", "functions", "that", "will", "be", "called", "whenever", "the", "routes", "are", "recalculated", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/routes.go#L50-L54
test
weaveworks/mesh
routes.go
Unicast
func (r *routes) Unicast(name PeerName) (PeerName, bool) { r.RLock() defer r.RUnlock() hop, found := r.unicast[name] return hop, found }
go
func (r *routes) Unicast(name PeerName) (PeerName, bool) { r.RLock() defer r.RUnlock() hop, found := r.unicast[name] return hop, found }
[ "func", "(", "r", "*", "routes", ")", "Unicast", "(", "name", "PeerName", ")", "(", "PeerName", ",", "bool", ")", "{", "r", ".", "RLock", "(", ")", "\n", "defer", "r", ".", "RUnlock", "(", ")", "\n", "hop", ",", "found", ":=", "r", ".", "unicast", "[", "name", "]", "\n", "return", "hop", ",", "found", "\n", "}" ]
// Unicast returns the next hop on the unicast route to the named peer, // based on established and symmetric connections.
[ "Unicast", "returns", "the", "next", "hop", "on", "the", "unicast", "route", "to", "the", "named", "peer", "based", "on", "established", "and", "symmetric", "connections", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/routes.go#L63-L68
test
weaveworks/mesh
routes.go
UnicastAll
func (r *routes) UnicastAll(name PeerName) (PeerName, bool) { r.RLock() defer r.RUnlock() hop, found := r.unicastAll[name] return hop, found }
go
func (r *routes) UnicastAll(name PeerName) (PeerName, bool) { r.RLock() defer r.RUnlock() hop, found := r.unicastAll[name] return hop, found }
[ "func", "(", "r", "*", "routes", ")", "UnicastAll", "(", "name", "PeerName", ")", "(", "PeerName", ",", "bool", ")", "{", "r", ".", "RLock", "(", ")", "\n", "defer", "r", ".", "RUnlock", "(", ")", "\n", "hop", ",", "found", ":=", "r", ".", "unicastAll", "[", "name", "]", "\n", "return", "hop", ",", "found", "\n", "}" ]
// UnicastAll returns the next hop on the unicast route to the named peer, // based on all connections.
[ "UnicastAll", "returns", "the", "next", "hop", "on", "the", "unicast", "route", "to", "the", "named", "peer", "based", "on", "all", "connections", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/routes.go#L72-L77
test
weaveworks/mesh
routes.go
Broadcast
func (r *routes) Broadcast(name PeerName) []PeerName { return r.lookupOrCalculate(name, &r.broadcast, true) }
go
func (r *routes) Broadcast(name PeerName) []PeerName { return r.lookupOrCalculate(name, &r.broadcast, true) }
[ "func", "(", "r", "*", "routes", ")", "Broadcast", "(", "name", "PeerName", ")", "[", "]", "PeerName", "{", "return", "r", ".", "lookupOrCalculate", "(", "name", ",", "&", "r", ".", "broadcast", ",", "true", ")", "\n", "}" ]
// Broadcast returns the set of peer names that should be notified // when we receive a broadcast message originating from the named peer // based on established and symmetric connections.
[ "Broadcast", "returns", "the", "set", "of", "peer", "names", "that", "should", "be", "notified", "when", "we", "receive", "a", "broadcast", "message", "originating", "from", "the", "named", "peer", "based", "on", "established", "and", "symmetric", "connections", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/routes.go#L82-L84
test
weaveworks/mesh
routes.go
BroadcastAll
func (r *routes) BroadcastAll(name PeerName) []PeerName { return r.lookupOrCalculate(name, &r.broadcastAll, false) }
go
func (r *routes) BroadcastAll(name PeerName) []PeerName { return r.lookupOrCalculate(name, &r.broadcastAll, false) }
[ "func", "(", "r", "*", "routes", ")", "BroadcastAll", "(", "name", "PeerName", ")", "[", "]", "PeerName", "{", "return", "r", ".", "lookupOrCalculate", "(", "name", ",", "&", "r", ".", "broadcastAll", ",", "false", ")", "\n", "}" ]
// BroadcastAll returns the set of peer names that should be notified // when we receive a broadcast message originating from the named peer // based on all connections.
[ "BroadcastAll", "returns", "the", "set", "of", "peer", "names", "that", "should", "be", "notified", "when", "we", "receive", "a", "broadcast", "message", "originating", "from", "the", "named", "peer", "based", "on", "all", "connections", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/routes.go#L89-L91
test
weaveworks/mesh
meshconn/peer.go
NewPeer
func NewPeer(name mesh.PeerName, uid mesh.PeerUID, logger mesh.Logger) *Peer { p := &Peer{ name: name, uid: uid, gossip: nil, // initially no gossip recv: make(chan pkt), actions: make(chan func()), quit: make(chan struct{}), logger: logger, } go p.loop() return p }
go
func NewPeer(name mesh.PeerName, uid mesh.PeerUID, logger mesh.Logger) *Peer { p := &Peer{ name: name, uid: uid, gossip: nil, // initially no gossip recv: make(chan pkt), actions: make(chan func()), quit: make(chan struct{}), logger: logger, } go p.loop() return p }
[ "func", "NewPeer", "(", "name", "mesh", ".", "PeerName", ",", "uid", "mesh", ".", "PeerUID", ",", "logger", "mesh", ".", "Logger", ")", "*", "Peer", "{", "p", ":=", "&", "Peer", "{", "name", ":", "name", ",", "uid", ":", "uid", ",", "gossip", ":", "nil", ",", "recv", ":", "make", "(", "chan", "pkt", ")", ",", "actions", ":", "make", "(", "chan", "func", "(", ")", ")", ",", "quit", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "logger", ":", "logger", ",", "}", "\n", "go", "p", ".", "loop", "(", ")", "\n", "return", "p", "\n", "}" ]
// NewPeer returns a Peer, which can be used as a net.PacketConn. // Clients must Register a mesh.Gossip before calling ReadFrom or WriteTo. // Clients should aggressively consume from ReadFrom.
[ "NewPeer", "returns", "a", "Peer", "which", "can", "be", "used", "as", "a", "net", ".", "PacketConn", ".", "Clients", "must", "Register", "a", "mesh", ".", "Gossip", "before", "calling", "ReadFrom", "or", "WriteTo", ".", "Clients", "should", "aggressively", "consume", "from", "ReadFrom", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/meshconn/peer.go#L46-L58
test
weaveworks/mesh
meshconn/peer.go
Register
func (p *Peer) Register(gossip mesh.Gossip) { p.actions <- func() { p.gossip = gossip } }
go
func (p *Peer) Register(gossip mesh.Gossip) { p.actions <- func() { p.gossip = gossip } }
[ "func", "(", "p", "*", "Peer", ")", "Register", "(", "gossip", "mesh", ".", "Gossip", ")", "{", "p", ".", "actions", "<-", "func", "(", ")", "{", "p", ".", "gossip", "=", "gossip", "}", "\n", "}" ]
// Register injects the mesh.Gossip and enables full-duplex communication. // Clients should consume from ReadFrom without blocking.
[ "Register", "injects", "the", "mesh", ".", "Gossip", "and", "enables", "full", "-", "duplex", "communication", ".", "Clients", "should", "consume", "from", "ReadFrom", "without", "blocking", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/meshconn/peer.go#L73-L75
test
weaveworks/mesh
meshconn/peer.go
ReadFrom
func (p *Peer) ReadFrom(b []byte) (n int, remote net.Addr, err error) { c := make(chan struct{}) p.actions <- func() { go func() { // so as not to block loop defer close(c) select { case pkt := <-p.recv: n = copy(b, pkt.Buf) remote = MeshAddr{PeerName: pkt.SrcName, PeerUID: pkt.SrcUID} if n < len(pkt.Buf) { err = ErrShortRead } case <-p.quit: err = ErrPeerClosed } }() } <-c return n, remote, err }
go
func (p *Peer) ReadFrom(b []byte) (n int, remote net.Addr, err error) { c := make(chan struct{}) p.actions <- func() { go func() { // so as not to block loop defer close(c) select { case pkt := <-p.recv: n = copy(b, pkt.Buf) remote = MeshAddr{PeerName: pkt.SrcName, PeerUID: pkt.SrcUID} if n < len(pkt.Buf) { err = ErrShortRead } case <-p.quit: err = ErrPeerClosed } }() } <-c return n, remote, err }
[ "func", "(", "p", "*", "Peer", ")", "ReadFrom", "(", "b", "[", "]", "byte", ")", "(", "n", "int", ",", "remote", "net", ".", "Addr", ",", "err", "error", ")", "{", "c", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "p", ".", "actions", "<-", "func", "(", ")", "{", "go", "func", "(", ")", "{", "defer", "close", "(", "c", ")", "\n", "select", "{", "case", "pkt", ":=", "<-", "p", ".", "recv", ":", "n", "=", "copy", "(", "b", ",", "pkt", ".", "Buf", ")", "\n", "remote", "=", "MeshAddr", "{", "PeerName", ":", "pkt", ".", "SrcName", ",", "PeerUID", ":", "pkt", ".", "SrcUID", "}", "\n", "if", "n", "<", "len", "(", "pkt", ".", "Buf", ")", "{", "err", "=", "ErrShortRead", "\n", "}", "\n", "case", "<-", "p", ".", "quit", ":", "err", "=", "ErrPeerClosed", "\n", "}", "\n", "}", "(", ")", "\n", "}", "\n", "<-", "c", "\n", "return", "n", ",", "remote", ",", "err", "\n", "}" ]
// ReadFrom implements net.PacketConn. // Clients should consume from ReadFrom without blocking.
[ "ReadFrom", "implements", "net", ".", "PacketConn", ".", "Clients", "should", "consume", "from", "ReadFrom", "without", "blocking", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/meshconn/peer.go#L79-L98
test
weaveworks/mesh
meshconn/peer.go
WriteTo
func (p *Peer) WriteTo(b []byte, dst net.Addr) (n int, err error) { c := make(chan struct{}) p.actions <- func() { defer close(c) if p.gossip == nil { err = ErrGossipNotRegistered return } meshAddr, ok := dst.(MeshAddr) if !ok { err = ErrNotMeshAddr return } pkt := pkt{SrcName: p.name, SrcUID: p.uid, Buf: b} if meshAddr.PeerName == p.name { p.recv <- pkt return } // TODO(pb): detect and support broadcast buf := pkt.encode() n = len(buf) err = p.gossip.GossipUnicast(meshAddr.PeerName, buf) } <-c return n, err }
go
func (p *Peer) WriteTo(b []byte, dst net.Addr) (n int, err error) { c := make(chan struct{}) p.actions <- func() { defer close(c) if p.gossip == nil { err = ErrGossipNotRegistered return } meshAddr, ok := dst.(MeshAddr) if !ok { err = ErrNotMeshAddr return } pkt := pkt{SrcName: p.name, SrcUID: p.uid, Buf: b} if meshAddr.PeerName == p.name { p.recv <- pkt return } // TODO(pb): detect and support broadcast buf := pkt.encode() n = len(buf) err = p.gossip.GossipUnicast(meshAddr.PeerName, buf) } <-c return n, err }
[ "func", "(", "p", "*", "Peer", ")", "WriteTo", "(", "b", "[", "]", "byte", ",", "dst", "net", ".", "Addr", ")", "(", "n", "int", ",", "err", "error", ")", "{", "c", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "p", ".", "actions", "<-", "func", "(", ")", "{", "defer", "close", "(", "c", ")", "\n", "if", "p", ".", "gossip", "==", "nil", "{", "err", "=", "ErrGossipNotRegistered", "\n", "return", "\n", "}", "\n", "meshAddr", ",", "ok", ":=", "dst", ".", "(", "MeshAddr", ")", "\n", "if", "!", "ok", "{", "err", "=", "ErrNotMeshAddr", "\n", "return", "\n", "}", "\n", "pkt", ":=", "pkt", "{", "SrcName", ":", "p", ".", "name", ",", "SrcUID", ":", "p", ".", "uid", ",", "Buf", ":", "b", "}", "\n", "if", "meshAddr", ".", "PeerName", "==", "p", ".", "name", "{", "p", ".", "recv", "<-", "pkt", "\n", "return", "\n", "}", "\n", "buf", ":=", "pkt", ".", "encode", "(", ")", "\n", "n", "=", "len", "(", "buf", ")", "\n", "err", "=", "p", ".", "gossip", ".", "GossipUnicast", "(", "meshAddr", ".", "PeerName", ",", "buf", ")", "\n", "}", "\n", "<-", "c", "\n", "return", "n", ",", "err", "\n", "}" ]
// WriteTo implements net.PacketConn.
[ "WriteTo", "implements", "net", ".", "PacketConn", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/meshconn/peer.go#L101-L126
test
weaveworks/mesh
meshconn/peer.go
LocalAddr
func (p *Peer) LocalAddr() net.Addr { return MeshAddr{PeerName: p.name, PeerUID: p.uid} }
go
func (p *Peer) LocalAddr() net.Addr { return MeshAddr{PeerName: p.name, PeerUID: p.uid} }
[ "func", "(", "p", "*", "Peer", ")", "LocalAddr", "(", ")", "net", ".", "Addr", "{", "return", "MeshAddr", "{", "PeerName", ":", "p", ".", "name", ",", "PeerUID", ":", "p", ".", "uid", "}", "\n", "}" ]
// LocalAddr implements net.PacketConn.
[ "LocalAddr", "implements", "net", ".", "PacketConn", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/meshconn/peer.go#L135-L137
test
weaveworks/mesh
meshconn/peer.go
OnGossip
func (p *Peer) OnGossip(buf []byte) (delta mesh.GossipData, err error) { return pktSlice{makePkt(buf)}, nil }
go
func (p *Peer) OnGossip(buf []byte) (delta mesh.GossipData, err error) { return pktSlice{makePkt(buf)}, nil }
[ "func", "(", "p", "*", "Peer", ")", "OnGossip", "(", "buf", "[", "]", "byte", ")", "(", "delta", "mesh", ".", "GossipData", ",", "err", "error", ")", "{", "return", "pktSlice", "{", "makePkt", "(", "buf", ")", "}", ",", "nil", "\n", "}" ]
// OnGossip implements mesh.Gossiper. // The buf is a single pkt.
[ "OnGossip", "implements", "mesh", ".", "Gossiper", ".", "The", "buf", "is", "a", "single", "pkt", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/meshconn/peer.go#L164-L166
test
weaveworks/mesh
meshconn/peer.go
OnGossipBroadcast
func (p *Peer) OnGossipBroadcast(_ mesh.PeerName, buf []byte) (received mesh.GossipData, err error) { pkt := makePkt(buf) p.recv <- pkt // to ReadFrom return pktSlice{pkt}, nil }
go
func (p *Peer) OnGossipBroadcast(_ mesh.PeerName, buf []byte) (received mesh.GossipData, err error) { pkt := makePkt(buf) p.recv <- pkt // to ReadFrom return pktSlice{pkt}, nil }
[ "func", "(", "p", "*", "Peer", ")", "OnGossipBroadcast", "(", "_", "mesh", ".", "PeerName", ",", "buf", "[", "]", "byte", ")", "(", "received", "mesh", ".", "GossipData", ",", "err", "error", ")", "{", "pkt", ":=", "makePkt", "(", "buf", ")", "\n", "p", ".", "recv", "<-", "pkt", "\n", "return", "pktSlice", "{", "pkt", "}", ",", "nil", "\n", "}" ]
// OnGossipBroadcast implements mesh.Gossiper. // The buf is a single pkt
[ "OnGossipBroadcast", "implements", "mesh", ".", "Gossiper", ".", "The", "buf", "is", "a", "single", "pkt" ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/meshconn/peer.go#L170-L174
test
weaveworks/mesh
meshconn/peer.go
OnGossipUnicast
func (p *Peer) OnGossipUnicast(_ mesh.PeerName, buf []byte) error { pkt := makePkt(buf) p.recv <- pkt // to ReadFrom return nil }
go
func (p *Peer) OnGossipUnicast(_ mesh.PeerName, buf []byte) error { pkt := makePkt(buf) p.recv <- pkt // to ReadFrom return nil }
[ "func", "(", "p", "*", "Peer", ")", "OnGossipUnicast", "(", "_", "mesh", ".", "PeerName", ",", "buf", "[", "]", "byte", ")", "error", "{", "pkt", ":=", "makePkt", "(", "buf", ")", "\n", "p", ".", "recv", "<-", "pkt", "\n", "return", "nil", "\n", "}" ]
// OnGossipUnicast implements mesh.Gossiper. // The buf is a single pkt.
[ "OnGossipUnicast", "implements", "mesh", ".", "Gossiper", ".", "The", "buf", "is", "a", "single", "pkt", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/meshconn/peer.go#L178-L182
test
weaveworks/mesh
_metcd/server.go
NewDefaultServer
func NewDefaultServer( minPeerCount int, terminatec <-chan struct{}, terminatedc chan<- error, logger mesh.Logger, ) Server { var ( peerName = mustPeerName() nickName = mustHostname() host = "0.0.0.0" port = 6379 password = "" channel = "metcd" ) router := mesh.NewRouter(mesh.Config{ Host: host, Port: port, ProtocolMinVersion: mesh.ProtocolMinVersion, Password: []byte(password), ConnLimit: 64, PeerDiscovery: true, TrustedSubnets: []*net.IPNet{}, }, peerName, nickName, mesh.NullOverlay{}, logger) // Create a meshconn.Peer and connect it to a channel. peer := meshconn.NewPeer(router.Ourself.Peer.Name, router.Ourself.UID, logger) gossip := router.NewGossip(channel, peer) peer.Register(gossip) // Start the router and join the mesh. // Note that we don't ever stop the router. // This may or may not be a problem. // TODO(pb): determine if this is a super huge problem router.Start() return NewServer(router, peer, minPeerCount, terminatec, terminatedc, logger) }
go
func NewDefaultServer( minPeerCount int, terminatec <-chan struct{}, terminatedc chan<- error, logger mesh.Logger, ) Server { var ( peerName = mustPeerName() nickName = mustHostname() host = "0.0.0.0" port = 6379 password = "" channel = "metcd" ) router := mesh.NewRouter(mesh.Config{ Host: host, Port: port, ProtocolMinVersion: mesh.ProtocolMinVersion, Password: []byte(password), ConnLimit: 64, PeerDiscovery: true, TrustedSubnets: []*net.IPNet{}, }, peerName, nickName, mesh.NullOverlay{}, logger) // Create a meshconn.Peer and connect it to a channel. peer := meshconn.NewPeer(router.Ourself.Peer.Name, router.Ourself.UID, logger) gossip := router.NewGossip(channel, peer) peer.Register(gossip) // Start the router and join the mesh. // Note that we don't ever stop the router. // This may or may not be a problem. // TODO(pb): determine if this is a super huge problem router.Start() return NewServer(router, peer, minPeerCount, terminatec, terminatedc, logger) }
[ "func", "NewDefaultServer", "(", "minPeerCount", "int", ",", "terminatec", "<-", "chan", "struct", "{", "}", ",", "terminatedc", "chan", "<-", "error", ",", "logger", "mesh", ".", "Logger", ",", ")", "Server", "{", "var", "(", "peerName", "=", "mustPeerName", "(", ")", "\n", "nickName", "=", "mustHostname", "(", ")", "\n", "host", "=", "\"0.0.0.0\"", "\n", "port", "=", "6379", "\n", "password", "=", "\"\"", "\n", "channel", "=", "\"metcd\"", "\n", ")", "\n", "router", ":=", "mesh", ".", "NewRouter", "(", "mesh", ".", "Config", "{", "Host", ":", "host", ",", "Port", ":", "port", ",", "ProtocolMinVersion", ":", "mesh", ".", "ProtocolMinVersion", ",", "Password", ":", "[", "]", "byte", "(", "password", ")", ",", "ConnLimit", ":", "64", ",", "PeerDiscovery", ":", "true", ",", "TrustedSubnets", ":", "[", "]", "*", "net", ".", "IPNet", "{", "}", ",", "}", ",", "peerName", ",", "nickName", ",", "mesh", ".", "NullOverlay", "{", "}", ",", "logger", ")", "\n", "peer", ":=", "meshconn", ".", "NewPeer", "(", "router", ".", "Ourself", ".", "Peer", ".", "Name", ",", "router", ".", "Ourself", ".", "UID", ",", "logger", ")", "\n", "gossip", ":=", "router", ".", "NewGossip", "(", "channel", ",", "peer", ")", "\n", "peer", ".", "Register", "(", "gossip", ")", "\n", "router", ".", "Start", "(", ")", "\n", "return", "NewServer", "(", "router", ",", "peer", ",", "minPeerCount", ",", "terminatec", ",", "terminatedc", ",", "logger", ")", "\n", "}" ]
// NewDefaultServer is like NewServer, but we take care of creating a // mesh.Router and meshconn.Peer for you, with sane defaults. If you need more // fine-grained control, create the components yourself and use NewServer.
[ "NewDefaultServer", "is", "like", "NewServer", "but", "we", "take", "care", "of", "creating", "a", "mesh", ".", "Router", "and", "meshconn", ".", "Peer", "for", "you", "with", "sane", "defaults", ".", "If", "you", "need", "more", "fine", "-", "grained", "control", "create", "the", "components", "yourself", "and", "use", "NewServer", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/_metcd/server.go#L61-L97
test
weaveworks/mesh
peer_name_hash.go
PeerNameFromUserInput
func PeerNameFromUserInput(userInput string) (PeerName, error) { // fixed-length identity nameByteAry := sha256.Sum256([]byte(userInput)) return PeerNameFromBin(nameByteAry[:NameSize]), nil }
go
func PeerNameFromUserInput(userInput string) (PeerName, error) { // fixed-length identity nameByteAry := sha256.Sum256([]byte(userInput)) return PeerNameFromBin(nameByteAry[:NameSize]), nil }
[ "func", "PeerNameFromUserInput", "(", "userInput", "string", ")", "(", "PeerName", ",", "error", ")", "{", "nameByteAry", ":=", "sha256", ".", "Sum256", "(", "[", "]", "byte", "(", "userInput", ")", ")", "\n", "return", "PeerNameFromBin", "(", "nameByteAry", "[", ":", "NameSize", "]", ")", ",", "nil", "\n", "}" ]
// PeerNameFromUserInput parses PeerName from a user-provided string.
[ "PeerNameFromUserInput", "parses", "PeerName", "from", "a", "user", "-", "provided", "string", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peer_name_hash.go#L27-L31
test
weaveworks/mesh
peer_name_hash.go
bytes
func (name PeerName) bytes() []byte { res, err := hex.DecodeString(string(name)) if err != nil { panic("unable to decode name to bytes: " + name) } return res }
go
func (name PeerName) bytes() []byte { res, err := hex.DecodeString(string(name)) if err != nil { panic("unable to decode name to bytes: " + name) } return res }
[ "func", "(", "name", "PeerName", ")", "bytes", "(", ")", "[", "]", "byte", "{", "res", ",", "err", ":=", "hex", ".", "DecodeString", "(", "string", "(", "name", ")", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "\"unable to decode name to bytes: \"", "+", "name", ")", "\n", "}", "\n", "return", "res", "\n", "}" ]
// bytes encodes PeerName as a byte slice.
[ "bytes", "encodes", "PeerName", "as", "a", "byte", "slice", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peer_name_hash.go#L47-L53
test
weaveworks/mesh
router.go
NewRouter
func NewRouter(config Config, name PeerName, nickName string, overlay Overlay, logger Logger) (*Router, error) { router := &Router{Config: config, gossipChannels: make(gossipChannels)} if overlay == nil { overlay = NullOverlay{} } router.Overlay = overlay router.Ourself = newLocalPeer(name, nickName, router) router.Peers = newPeers(router.Ourself) router.Peers.OnGC(func(peer *Peer) { logger.Printf("Removed unreachable peer %s", peer) }) router.Routes = newRoutes(router.Ourself, router.Peers) router.ConnectionMaker = newConnectionMaker(router.Ourself, router.Peers, net.JoinHostPort(router.Host, "0"), router.Port, router.PeerDiscovery, logger) router.logger = logger gossip, err := router.NewGossip("topology", router) if err != nil { return nil, err } router.topologyGossip = gossip router.acceptLimiter = newTokenBucket(acceptMaxTokens, acceptTokenDelay) return router, nil }
go
func NewRouter(config Config, name PeerName, nickName string, overlay Overlay, logger Logger) (*Router, error) { router := &Router{Config: config, gossipChannels: make(gossipChannels)} if overlay == nil { overlay = NullOverlay{} } router.Overlay = overlay router.Ourself = newLocalPeer(name, nickName, router) router.Peers = newPeers(router.Ourself) router.Peers.OnGC(func(peer *Peer) { logger.Printf("Removed unreachable peer %s", peer) }) router.Routes = newRoutes(router.Ourself, router.Peers) router.ConnectionMaker = newConnectionMaker(router.Ourself, router.Peers, net.JoinHostPort(router.Host, "0"), router.Port, router.PeerDiscovery, logger) router.logger = logger gossip, err := router.NewGossip("topology", router) if err != nil { return nil, err } router.topologyGossip = gossip router.acceptLimiter = newTokenBucket(acceptMaxTokens, acceptTokenDelay) return router, nil }
[ "func", "NewRouter", "(", "config", "Config", ",", "name", "PeerName", ",", "nickName", "string", ",", "overlay", "Overlay", ",", "logger", "Logger", ")", "(", "*", "Router", ",", "error", ")", "{", "router", ":=", "&", "Router", "{", "Config", ":", "config", ",", "gossipChannels", ":", "make", "(", "gossipChannels", ")", "}", "\n", "if", "overlay", "==", "nil", "{", "overlay", "=", "NullOverlay", "{", "}", "\n", "}", "\n", "router", ".", "Overlay", "=", "overlay", "\n", "router", ".", "Ourself", "=", "newLocalPeer", "(", "name", ",", "nickName", ",", "router", ")", "\n", "router", ".", "Peers", "=", "newPeers", "(", "router", ".", "Ourself", ")", "\n", "router", ".", "Peers", ".", "OnGC", "(", "func", "(", "peer", "*", "Peer", ")", "{", "logger", ".", "Printf", "(", "\"Removed unreachable peer %s\"", ",", "peer", ")", "\n", "}", ")", "\n", "router", ".", "Routes", "=", "newRoutes", "(", "router", ".", "Ourself", ",", "router", ".", "Peers", ")", "\n", "router", ".", "ConnectionMaker", "=", "newConnectionMaker", "(", "router", ".", "Ourself", ",", "router", ".", "Peers", ",", "net", ".", "JoinHostPort", "(", "router", ".", "Host", ",", "\"0\"", ")", ",", "router", ".", "Port", ",", "router", ".", "PeerDiscovery", ",", "logger", ")", "\n", "router", ".", "logger", "=", "logger", "\n", "gossip", ",", "err", ":=", "router", ".", "NewGossip", "(", "\"topology\"", ",", "router", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "router", ".", "topologyGossip", "=", "gossip", "\n", "router", ".", "acceptLimiter", "=", "newTokenBucket", "(", "acceptMaxTokens", ",", "acceptTokenDelay", ")", "\n", "return", "router", ",", "nil", "\n", "}" ]
// NewRouter returns a new router. It must be started.
[ "NewRouter", "returns", "a", "new", "router", ".", "It", "must", "be", "started", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/router.go#L59-L82
test
weaveworks/mesh
router.go
sendAllGossip
func (router *Router) sendAllGossip() { for channel := range router.gossipChannelSet() { if gossip := channel.gossiper.Gossip(); gossip != nil { channel.Send(gossip) } } }
go
func (router *Router) sendAllGossip() { for channel := range router.gossipChannelSet() { if gossip := channel.gossiper.Gossip(); gossip != nil { channel.Send(gossip) } } }
[ "func", "(", "router", "*", "Router", ")", "sendAllGossip", "(", ")", "{", "for", "channel", ":=", "range", "router", ".", "gossipChannelSet", "(", ")", "{", "if", "gossip", ":=", "channel", ".", "gossiper", ".", "Gossip", "(", ")", ";", "gossip", "!=", "nil", "{", "channel", ".", "Send", "(", "gossip", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Relay all pending gossip data for each channel via random neighbours.
[ "Relay", "all", "pending", "gossip", "data", "for", "each", "channel", "via", "random", "neighbours", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/router.go#L196-L202
test
weaveworks/mesh
router.go
sendAllGossipDown
func (router *Router) sendAllGossipDown(conn Connection) { for channel := range router.gossipChannelSet() { if gossip := channel.gossiper.Gossip(); gossip != nil { channel.SendDown(conn, gossip) } } }
go
func (router *Router) sendAllGossipDown(conn Connection) { for channel := range router.gossipChannelSet() { if gossip := channel.gossiper.Gossip(); gossip != nil { channel.SendDown(conn, gossip) } } }
[ "func", "(", "router", "*", "Router", ")", "sendAllGossipDown", "(", "conn", "Connection", ")", "{", "for", "channel", ":=", "range", "router", ".", "gossipChannelSet", "(", ")", "{", "if", "gossip", ":=", "channel", ".", "gossiper", ".", "Gossip", "(", ")", ";", "gossip", "!=", "nil", "{", "channel", ".", "SendDown", "(", "conn", ",", "gossip", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Relay all pending gossip data for each channel via conn.
[ "Relay", "all", "pending", "gossip", "data", "for", "each", "channel", "via", "conn", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/router.go#L205-L211
test
weaveworks/mesh
router.go
broadcastTopologyUpdate
func (router *Router) broadcastTopologyUpdate(update []*Peer) { names := make(peerNameSet) for _, p := range update { names[p.Name] = struct{}{} } router.topologyGossip.GossipBroadcast(&topologyGossipData{peers: router.Peers, update: names}) }
go
func (router *Router) broadcastTopologyUpdate(update []*Peer) { names := make(peerNameSet) for _, p := range update { names[p.Name] = struct{}{} } router.topologyGossip.GossipBroadcast(&topologyGossipData{peers: router.Peers, update: names}) }
[ "func", "(", "router", "*", "Router", ")", "broadcastTopologyUpdate", "(", "update", "[", "]", "*", "Peer", ")", "{", "names", ":=", "make", "(", "peerNameSet", ")", "\n", "for", "_", ",", "p", ":=", "range", "update", "{", "names", "[", "p", ".", "Name", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "router", ".", "topologyGossip", ".", "GossipBroadcast", "(", "&", "topologyGossipData", "{", "peers", ":", "router", ".", "Peers", ",", "update", ":", "names", "}", ")", "\n", "}" ]
// BroadcastTopologyUpdate is invoked whenever there is a change to the mesh // topology, and broadcasts the new set of peers to the mesh.
[ "BroadcastTopologyUpdate", "is", "invoked", "whenever", "there", "is", "a", "change", "to", "the", "mesh", "topology", "and", "broadcasts", "the", "new", "set", "of", "peers", "to", "the", "mesh", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/router.go#L224-L230
test
weaveworks/mesh
router.go
OnGossipUnicast
func (router *Router) OnGossipUnicast(sender PeerName, msg []byte) error { return fmt.Errorf("unexpected topology gossip unicast: %v", msg) }
go
func (router *Router) OnGossipUnicast(sender PeerName, msg []byte) error { return fmt.Errorf("unexpected topology gossip unicast: %v", msg) }
[ "func", "(", "router", "*", "Router", ")", "OnGossipUnicast", "(", "sender", "PeerName", ",", "msg", "[", "]", "byte", ")", "error", "{", "return", "fmt", ".", "Errorf", "(", "\"unexpected topology gossip unicast: %v\"", ",", "msg", ")", "\n", "}" ]
// OnGossipUnicast implements Gossiper, but always returns an error, as a // router should only receive gossip broadcasts of TopologyGossipData.
[ "OnGossipUnicast", "implements", "Gossiper", "but", "always", "returns", "an", "error", "as", "a", "router", "should", "only", "receive", "gossip", "broadcasts", "of", "TopologyGossipData", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/router.go#L234-L236
test
weaveworks/mesh
router.go
OnGossipBroadcast
func (router *Router) OnGossipBroadcast(_ PeerName, update []byte) (GossipData, error) { origUpdate, _, err := router.applyTopologyUpdate(update) if err != nil || len(origUpdate) == 0 { return nil, err } return &topologyGossipData{peers: router.Peers, update: origUpdate}, nil }
go
func (router *Router) OnGossipBroadcast(_ PeerName, update []byte) (GossipData, error) { origUpdate, _, err := router.applyTopologyUpdate(update) if err != nil || len(origUpdate) == 0 { return nil, err } return &topologyGossipData{peers: router.Peers, update: origUpdate}, nil }
[ "func", "(", "router", "*", "Router", ")", "OnGossipBroadcast", "(", "_", "PeerName", ",", "update", "[", "]", "byte", ")", "(", "GossipData", ",", "error", ")", "{", "origUpdate", ",", "_", ",", "err", ":=", "router", ".", "applyTopologyUpdate", "(", "update", ")", "\n", "if", "err", "!=", "nil", "||", "len", "(", "origUpdate", ")", "==", "0", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "topologyGossipData", "{", "peers", ":", "router", ".", "Peers", ",", "update", ":", "origUpdate", "}", ",", "nil", "\n", "}" ]
// OnGossipBroadcast receives broadcasts of TopologyGossipData. // It returns the received update unchanged.
[ "OnGossipBroadcast", "receives", "broadcasts", "of", "TopologyGossipData", ".", "It", "returns", "the", "received", "update", "unchanged", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/router.go#L240-L246
test
weaveworks/mesh
router.go
Gossip
func (router *Router) Gossip() GossipData { return &topologyGossipData{peers: router.Peers, update: router.Peers.names()} }
go
func (router *Router) Gossip() GossipData { return &topologyGossipData{peers: router.Peers, update: router.Peers.names()} }
[ "func", "(", "router", "*", "Router", ")", "Gossip", "(", ")", "GossipData", "{", "return", "&", "topologyGossipData", "{", "peers", ":", "router", ".", "Peers", ",", "update", ":", "router", ".", "Peers", ".", "names", "(", ")", "}", "\n", "}" ]
// Gossip yields the current topology as GossipData.
[ "Gossip", "yields", "the", "current", "topology", "as", "GossipData", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/router.go#L249-L251
test
weaveworks/mesh
router.go
OnGossip
func (router *Router) OnGossip(update []byte) (GossipData, error) { _, newUpdate, err := router.applyTopologyUpdate(update) if err != nil || len(newUpdate) == 0 { return nil, err } return &topologyGossipData{peers: router.Peers, update: newUpdate}, nil }
go
func (router *Router) OnGossip(update []byte) (GossipData, error) { _, newUpdate, err := router.applyTopologyUpdate(update) if err != nil || len(newUpdate) == 0 { return nil, err } return &topologyGossipData{peers: router.Peers, update: newUpdate}, nil }
[ "func", "(", "router", "*", "Router", ")", "OnGossip", "(", "update", "[", "]", "byte", ")", "(", "GossipData", ",", "error", ")", "{", "_", ",", "newUpdate", ",", "err", ":=", "router", ".", "applyTopologyUpdate", "(", "update", ")", "\n", "if", "err", "!=", "nil", "||", "len", "(", "newUpdate", ")", "==", "0", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "topologyGossipData", "{", "peers", ":", "router", ".", "Peers", ",", "update", ":", "newUpdate", "}", ",", "nil", "\n", "}" ]
// OnGossip receives broadcasts of TopologyGossipData. // It returns an "improved" version of the received update. // See peers.ApplyUpdate.
[ "OnGossip", "receives", "broadcasts", "of", "TopologyGossipData", ".", "It", "returns", "an", "improved", "version", "of", "the", "received", "update", ".", "See", "peers", ".", "ApplyUpdate", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/router.go#L256-L262
test
weaveworks/mesh
router.go
Encode
func (d *topologyGossipData) Encode() [][]byte { return [][]byte{d.peers.encodePeers(d.update)} }
go
func (d *topologyGossipData) Encode() [][]byte { return [][]byte{d.peers.encodePeers(d.update)} }
[ "func", "(", "d", "*", "topologyGossipData", ")", "Encode", "(", ")", "[", "]", "[", "]", "byte", "{", "return", "[", "]", "[", "]", "byte", "{", "d", ".", "peers", ".", "encodePeers", "(", "d", ".", "update", ")", "}", "\n", "}" ]
// Encode implements GossipData.
[ "Encode", "implements", "GossipData", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/router.go#L310-L312
test
weaveworks/mesh
examples/increment-only-counter/state.go
newState
func newState(self mesh.PeerName) *state { return &state{ set: map[mesh.PeerName]int{}, self: self, } }
go
func newState(self mesh.PeerName) *state { return &state{ set: map[mesh.PeerName]int{}, self: self, } }
[ "func", "newState", "(", "self", "mesh", ".", "PeerName", ")", "*", "state", "{", "return", "&", "state", "{", "set", ":", "map", "[", "mesh", ".", "PeerName", "]", "int", "{", "}", ",", "self", ":", "self", ",", "}", "\n", "}" ]
// Construct an empty state object, ready to receive updates. // This is suitable to use at program start. // Other peers will populate us with data.
[ "Construct", "an", "empty", "state", "object", "ready", "to", "receive", "updates", ".", "This", "is", "suitable", "to", "use", "at", "program", "start", ".", "Other", "peers", "will", "populate", "us", "with", "data", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/examples/increment-only-counter/state.go#L25-L30
test
weaveworks/mesh
examples/increment-only-counter/state.go
Merge
func (st *state) Merge(other mesh.GossipData) (complete mesh.GossipData) { return st.mergeComplete(other.(*state).copy().set) }
go
func (st *state) Merge(other mesh.GossipData) (complete mesh.GossipData) { return st.mergeComplete(other.(*state).copy().set) }
[ "func", "(", "st", "*", "state", ")", "Merge", "(", "other", "mesh", ".", "GossipData", ")", "(", "complete", "mesh", ".", "GossipData", ")", "{", "return", "st", ".", "mergeComplete", "(", "other", ".", "(", "*", "state", ")", ".", "copy", "(", ")", ".", "set", ")", "\n", "}" ]
// Merge merges the other GossipData into this one, // and returns our resulting, complete state.
[ "Merge", "merges", "the", "other", "GossipData", "into", "this", "one", "and", "returns", "our", "resulting", "complete", "state", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/examples/increment-only-counter/state.go#L73-L75
test
weaveworks/mesh
examples/increment-only-counter/state.go
mergeReceived
func (st *state) mergeReceived(set map[mesh.PeerName]int) (received mesh.GossipData) { st.mtx.Lock() defer st.mtx.Unlock() for peer, v := range set { if v <= st.set[peer] { delete(set, peer) // optimization: make the forwarded data smaller continue } st.set[peer] = v } return &state{ set: set, // all remaining elements were novel to us } }
go
func (st *state) mergeReceived(set map[mesh.PeerName]int) (received mesh.GossipData) { st.mtx.Lock() defer st.mtx.Unlock() for peer, v := range set { if v <= st.set[peer] { delete(set, peer) // optimization: make the forwarded data smaller continue } st.set[peer] = v } return &state{ set: set, // all remaining elements were novel to us } }
[ "func", "(", "st", "*", "state", ")", "mergeReceived", "(", "set", "map", "[", "mesh", ".", "PeerName", "]", "int", ")", "(", "received", "mesh", ".", "GossipData", ")", "{", "st", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "st", ".", "mtx", ".", "Unlock", "(", ")", "\n", "for", "peer", ",", "v", ":=", "range", "set", "{", "if", "v", "<=", "st", ".", "set", "[", "peer", "]", "{", "delete", "(", "set", ",", "peer", ")", "\n", "continue", "\n", "}", "\n", "st", ".", "set", "[", "peer", "]", "=", "v", "\n", "}", "\n", "return", "&", "state", "{", "set", ":", "set", ",", "}", "\n", "}" ]
// Merge the set into our state, abiding increment-only semantics. // Return a non-nil mesh.GossipData representation of the received set.
[ "Merge", "the", "set", "into", "our", "state", "abiding", "increment", "-", "only", "semantics", ".", "Return", "a", "non", "-", "nil", "mesh", ".", "GossipData", "representation", "of", "the", "received", "set", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/examples/increment-only-counter/state.go#L79-L94
test
weaveworks/mesh
examples/increment-only-counter/state.go
mergeComplete
func (st *state) mergeComplete(set map[mesh.PeerName]int) (complete mesh.GossipData) { st.mtx.Lock() defer st.mtx.Unlock() for peer, v := range set { if v > st.set[peer] { st.set[peer] = v } } return &state{ set: st.set, // n.b. can't .copy() due to lock contention } }
go
func (st *state) mergeComplete(set map[mesh.PeerName]int) (complete mesh.GossipData) { st.mtx.Lock() defer st.mtx.Unlock() for peer, v := range set { if v > st.set[peer] { st.set[peer] = v } } return &state{ set: st.set, // n.b. can't .copy() due to lock contention } }
[ "func", "(", "st", "*", "state", ")", "mergeComplete", "(", "set", "map", "[", "mesh", ".", "PeerName", "]", "int", ")", "(", "complete", "mesh", ".", "GossipData", ")", "{", "st", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "st", ".", "mtx", ".", "Unlock", "(", ")", "\n", "for", "peer", ",", "v", ":=", "range", "set", "{", "if", "v", ">", "st", ".", "set", "[", "peer", "]", "{", "st", ".", "set", "[", "peer", "]", "=", "v", "\n", "}", "\n", "}", "\n", "return", "&", "state", "{", "set", ":", "st", ".", "set", ",", "}", "\n", "}" ]
// Merge the set into our state, abiding increment-only semantics. // Return our resulting, complete state.
[ "Merge", "the", "set", "into", "our", "state", "abiding", "increment", "-", "only", "semantics", ".", "Return", "our", "resulting", "complete", "state", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/examples/increment-only-counter/state.go#L120-L133
test
weaveworks/mesh
surrogate_gossiper.go
OnGossipBroadcast
func (*surrogateGossiper) OnGossipBroadcast(_ PeerName, update []byte) (GossipData, error) { return newSurrogateGossipData(update), nil }
go
func (*surrogateGossiper) OnGossipBroadcast(_ PeerName, update []byte) (GossipData, error) { return newSurrogateGossipData(update), nil }
[ "func", "(", "*", "surrogateGossiper", ")", "OnGossipBroadcast", "(", "_", "PeerName", ",", "update", "[", "]", "byte", ")", "(", "GossipData", ",", "error", ")", "{", "return", "newSurrogateGossipData", "(", "update", ")", ",", "nil", "\n", "}" ]
// OnGossipBroadcast implements Gossiper.
[ "OnGossipBroadcast", "implements", "Gossiper", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/surrogate_gossiper.go#L33-L35
test
weaveworks/mesh
surrogate_gossiper.go
OnGossip
func (s *surrogateGossiper) OnGossip(update []byte) (GossipData, error) { hash := fnv.New64a() _, _ = hash.Write(update) updateHash := hash.Sum64() s.Lock() defer s.Unlock() for _, p := range s.prevUpdates { if updateHash == p.hash && bytes.Equal(update, p.update) { return nil, nil } } // Delete anything that's older than the gossip interval, so we don't grow forever // (this time limit is arbitrary; surrogateGossiper should pass on new gossip immediately // so there should be no reason for a duplicate to show up after a long time) updateTime := now() deleteBefore := updateTime.Add(-gossipInterval) keepFrom := len(s.prevUpdates) for i, p := range s.prevUpdates { if p.t.After(deleteBefore) { keepFrom = i break } } s.prevUpdates = append(s.prevUpdates[keepFrom:], prevUpdate{update, updateHash, updateTime}) return newSurrogateGossipData(update), nil }
go
func (s *surrogateGossiper) OnGossip(update []byte) (GossipData, error) { hash := fnv.New64a() _, _ = hash.Write(update) updateHash := hash.Sum64() s.Lock() defer s.Unlock() for _, p := range s.prevUpdates { if updateHash == p.hash && bytes.Equal(update, p.update) { return nil, nil } } // Delete anything that's older than the gossip interval, so we don't grow forever // (this time limit is arbitrary; surrogateGossiper should pass on new gossip immediately // so there should be no reason for a duplicate to show up after a long time) updateTime := now() deleteBefore := updateTime.Add(-gossipInterval) keepFrom := len(s.prevUpdates) for i, p := range s.prevUpdates { if p.t.After(deleteBefore) { keepFrom = i break } } s.prevUpdates = append(s.prevUpdates[keepFrom:], prevUpdate{update, updateHash, updateTime}) return newSurrogateGossipData(update), nil }
[ "func", "(", "s", "*", "surrogateGossiper", ")", "OnGossip", "(", "update", "[", "]", "byte", ")", "(", "GossipData", ",", "error", ")", "{", "hash", ":=", "fnv", ".", "New64a", "(", ")", "\n", "_", ",", "_", "=", "hash", ".", "Write", "(", "update", ")", "\n", "updateHash", ":=", "hash", ".", "Sum64", "(", ")", "\n", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n", "for", "_", ",", "p", ":=", "range", "s", ".", "prevUpdates", "{", "if", "updateHash", "==", "p", ".", "hash", "&&", "bytes", ".", "Equal", "(", "update", ",", "p", ".", "update", ")", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "}", "\n", "updateTime", ":=", "now", "(", ")", "\n", "deleteBefore", ":=", "updateTime", ".", "Add", "(", "-", "gossipInterval", ")", "\n", "keepFrom", ":=", "len", "(", "s", ".", "prevUpdates", ")", "\n", "for", "i", ",", "p", ":=", "range", "s", ".", "prevUpdates", "{", "if", "p", ".", "t", ".", "After", "(", "deleteBefore", ")", "{", "keepFrom", "=", "i", "\n", "break", "\n", "}", "\n", "}", "\n", "s", ".", "prevUpdates", "=", "append", "(", "s", ".", "prevUpdates", "[", "keepFrom", ":", "]", ",", "prevUpdate", "{", "update", ",", "updateHash", ",", "updateTime", "}", ")", "\n", "return", "newSurrogateGossipData", "(", "update", ")", ",", "nil", "\n", "}" ]
// OnGossip should return "everything new I've just learnt". // surrogateGossiper doesn't understand the content of messages, but it can eliminate simple duplicates
[ "OnGossip", "should", "return", "everything", "new", "I", "ve", "just", "learnt", ".", "surrogateGossiper", "doesn", "t", "understand", "the", "content", "of", "messages", "but", "it", "can", "eliminate", "simple", "duplicates" ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/surrogate_gossiper.go#L44-L69
test
weaveworks/mesh
protocol_crypto.go
generateKeyPair
func generateKeyPair() (publicKey, privateKey *[32]byte, err error) { return box.GenerateKey(rand.Reader) }
go
func generateKeyPair() (publicKey, privateKey *[32]byte, err error) { return box.GenerateKey(rand.Reader) }
[ "func", "generateKeyPair", "(", ")", "(", "publicKey", ",", "privateKey", "*", "[", "32", "]", "byte", ",", "err", "error", ")", "{", "return", "box", ".", "GenerateKey", "(", "rand", ".", "Reader", ")", "\n", "}" ]
// GenerateKeyPair is used during encrypted protocol introduction.
[ "GenerateKeyPair", "is", "used", "during", "encrypted", "protocol", "introduction", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/protocol_crypto.go#L22-L24
test
weaveworks/mesh
protocol_crypto.go
formSessionKey
func formSessionKey(remotePublicKey, localPrivateKey *[32]byte, secretKey []byte) *[32]byte { var sharedKey [32]byte box.Precompute(&sharedKey, remotePublicKey, localPrivateKey) sharedKeySlice := sharedKey[:] sharedKeySlice = append(sharedKeySlice, secretKey...) sessionKey := sha256.Sum256(sharedKeySlice) return &sessionKey }
go
func formSessionKey(remotePublicKey, localPrivateKey *[32]byte, secretKey []byte) *[32]byte { var sharedKey [32]byte box.Precompute(&sharedKey, remotePublicKey, localPrivateKey) sharedKeySlice := sharedKey[:] sharedKeySlice = append(sharedKeySlice, secretKey...) sessionKey := sha256.Sum256(sharedKeySlice) return &sessionKey }
[ "func", "formSessionKey", "(", "remotePublicKey", ",", "localPrivateKey", "*", "[", "32", "]", "byte", ",", "secretKey", "[", "]", "byte", ")", "*", "[", "32", "]", "byte", "{", "var", "sharedKey", "[", "32", "]", "byte", "\n", "box", ".", "Precompute", "(", "&", "sharedKey", ",", "remotePublicKey", ",", "localPrivateKey", ")", "\n", "sharedKeySlice", ":=", "sharedKey", "[", ":", "]", "\n", "sharedKeySlice", "=", "append", "(", "sharedKeySlice", ",", "secretKey", "...", ")", "\n", "sessionKey", ":=", "sha256", ".", "Sum256", "(", "sharedKeySlice", ")", "\n", "return", "&", "sessionKey", "\n", "}" ]
// FormSessionKey is used during encrypted protocol introduction.
[ "FormSessionKey", "is", "used", "during", "encrypted", "protocol", "introduction", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/protocol_crypto.go#L27-L34
test
weaveworks/mesh
protocol_crypto.go
newTCPCryptoState
func newTCPCryptoState(sessionKey *[32]byte, outbound bool) *tcpCryptoState { s := &tcpCryptoState{sessionKey: sessionKey} if outbound { s.nonce[0] |= (1 << 7) } s.nonce[0] |= (1 << 6) return s }
go
func newTCPCryptoState(sessionKey *[32]byte, outbound bool) *tcpCryptoState { s := &tcpCryptoState{sessionKey: sessionKey} if outbound { s.nonce[0] |= (1 << 7) } s.nonce[0] |= (1 << 6) return s }
[ "func", "newTCPCryptoState", "(", "sessionKey", "*", "[", "32", "]", "byte", ",", "outbound", "bool", ")", "*", "tcpCryptoState", "{", "s", ":=", "&", "tcpCryptoState", "{", "sessionKey", ":", "sessionKey", "}", "\n", "if", "outbound", "{", "s", ".", "nonce", "[", "0", "]", "|=", "(", "1", "<<", "7", ")", "\n", "}", "\n", "s", ".", "nonce", "[", "0", "]", "|=", "(", "1", "<<", "6", ")", "\n", "return", "s", "\n", "}" ]
// NewTCPCryptoState returns a valid TCPCryptoState.
[ "NewTCPCryptoState", "returns", "a", "valid", "TCPCryptoState", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/protocol_crypto.go#L55-L62
test
weaveworks/mesh
protocol_crypto.go
Send
func (sender *gobTCPSender) Send(msg []byte) error { return sender.encoder.Encode(msg) }
go
func (sender *gobTCPSender) Send(msg []byte) error { return sender.encoder.Encode(msg) }
[ "func", "(", "sender", "*", "gobTCPSender", ")", "Send", "(", "msg", "[", "]", "byte", ")", "error", "{", "return", "sender", ".", "encoder", ".", "Encode", "(", "msg", ")", "\n", "}" ]
// Send implements TCPSender by encoding the msg.
[ "Send", "implements", "TCPSender", "by", "encoding", "the", "msg", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/protocol_crypto.go#L85-L87
test
weaveworks/mesh
protocol_crypto.go
Send
func (sender *lengthPrefixTCPSender) Send(msg []byte) error { l := len(msg) if l > maxTCPMsgSize { return fmt.Errorf("outgoing message exceeds maximum size: %d > %d", l, maxTCPMsgSize) } // We copy the message so we can send it in a single Write // operation, thus making this thread-safe without locking. prefixedMsg := make([]byte, 4+l) binary.BigEndian.PutUint32(prefixedMsg, uint32(l)) copy(prefixedMsg[4:], msg) _, err := sender.writer.Write(prefixedMsg) return err }
go
func (sender *lengthPrefixTCPSender) Send(msg []byte) error { l := len(msg) if l > maxTCPMsgSize { return fmt.Errorf("outgoing message exceeds maximum size: %d > %d", l, maxTCPMsgSize) } // We copy the message so we can send it in a single Write // operation, thus making this thread-safe without locking. prefixedMsg := make([]byte, 4+l) binary.BigEndian.PutUint32(prefixedMsg, uint32(l)) copy(prefixedMsg[4:], msg) _, err := sender.writer.Write(prefixedMsg) return err }
[ "func", "(", "sender", "*", "lengthPrefixTCPSender", ")", "Send", "(", "msg", "[", "]", "byte", ")", "error", "{", "l", ":=", "len", "(", "msg", ")", "\n", "if", "l", ">", "maxTCPMsgSize", "{", "return", "fmt", ".", "Errorf", "(", "\"outgoing message exceeds maximum size: %d > %d\"", ",", "l", ",", "maxTCPMsgSize", ")", "\n", "}", "\n", "prefixedMsg", ":=", "make", "(", "[", "]", "byte", ",", "4", "+", "l", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint32", "(", "prefixedMsg", ",", "uint32", "(", "l", ")", ")", "\n", "copy", "(", "prefixedMsg", "[", "4", ":", "]", ",", "msg", ")", "\n", "_", ",", "err", ":=", "sender", ".", "writer", ".", "Write", "(", "prefixedMsg", ")", "\n", "return", "err", "\n", "}" ]
// Send implements TCPSender by writing the size of the msg as a big-endian // uint32 before the msg. msgs larger than MaxTCPMsgSize are rejected.
[ "Send", "implements", "TCPSender", "by", "writing", "the", "size", "of", "the", "msg", "as", "a", "big", "-", "endian", "uint32", "before", "the", "msg", ".", "msgs", "larger", "than", "MaxTCPMsgSize", "are", "rejected", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/protocol_crypto.go#L100-L112
test
weaveworks/mesh
protocol_crypto.go
Send
func (sender *encryptedTCPSender) Send(msg []byte) error { sender.Lock() defer sender.Unlock() encodedMsg := secretbox.Seal(nil, msg, &sender.state.nonce, sender.state.sessionKey) sender.state.advance() return sender.sender.Send(encodedMsg) }
go
func (sender *encryptedTCPSender) Send(msg []byte) error { sender.Lock() defer sender.Unlock() encodedMsg := secretbox.Seal(nil, msg, &sender.state.nonce, sender.state.sessionKey) sender.state.advance() return sender.sender.Send(encodedMsg) }
[ "func", "(", "sender", "*", "encryptedTCPSender", ")", "Send", "(", "msg", "[", "]", "byte", ")", "error", "{", "sender", ".", "Lock", "(", ")", "\n", "defer", "sender", ".", "Unlock", "(", ")", "\n", "encodedMsg", ":=", "secretbox", ".", "Seal", "(", "nil", ",", "msg", ",", "&", "sender", ".", "state", ".", "nonce", ",", "sender", ".", "state", ".", "sessionKey", ")", "\n", "sender", ".", "state", ".", "advance", "(", ")", "\n", "return", "sender", ".", "sender", ".", "Send", "(", "encodedMsg", ")", "\n", "}" ]
// Send implements TCPSender by sealing and sending the msg as-is.
[ "Send", "implements", "TCPSender", "by", "sealing", "and", "sending", "the", "msg", "as", "-", "is", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/protocol_crypto.go#L126-L132
test
weaveworks/mesh
protocol_crypto.go
Receive
func (receiver *gobTCPReceiver) Receive() ([]byte, error) { var msg []byte err := receiver.decoder.Decode(&msg) return msg, err }
go
func (receiver *gobTCPReceiver) Receive() ([]byte, error) { var msg []byte err := receiver.decoder.Decode(&msg) return msg, err }
[ "func", "(", "receiver", "*", "gobTCPReceiver", ")", "Receive", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "msg", "[", "]", "byte", "\n", "err", ":=", "receiver", ".", "decoder", ".", "Decode", "(", "&", "msg", ")", "\n", "return", "msg", ",", "err", "\n", "}" ]
// Receive implements TCPReciever by Gob decoding into a byte slice directly.
[ "Receive", "implements", "TCPReciever", "by", "Gob", "decoding", "into", "a", "byte", "slice", "directly", "." ]
512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/protocol_crypto.go#L150-L154
test